Let's investigate the
various elements of a simple C program;
void main (void)
{
printf("Jamil Murad
Baloch");
}
Function Definition
All C programs are
divided into units called "functions". main() is a function. Every C program consists of one or more functions.
main () is the one to which control is passed from the operating system when
the program is run. The word void preceding main specifies that the function
main() will not return a value, the second void in parenthesis specifies that
the function takes no arguments.
Delimiters
following the function
definition are braces which signal the beginning and end of the body of the
function. The opening brace { indicates that a block of code that forms a
distinct unit is about to begin and the closing brace } terminates the block of
code.
Statement Terminator
The line in our program
that begins with the word "printf" is an example of a statement. A
statement in C is terminated with a semicolon.
The Printf ( ) Function
the program statement
printf("Jamil Murad
Baloch");
causes the phrase in
quotes to be printed on the screen. the word printf is actually a function
name, just as "main" is a function name.
Exploring the printf( ) function
Printing numbers
The printf ( ) function uses a unique format for printing constant and variables. let's look at an example:
void main ( )
{
printf ("This is the number five: %d",5);
}
The printf ( ) can be given more than one argument. In this example we gave it two arguments: ("This is the number five: %d") on the left and a value (5) on the right. These two arguments are separated by a coma.
Format Specifiers
the Format Specifiers tell printf ( ) where to put a value in a string and what format to use in printing that value. In this example the %d tells printf ( ) to print the value 5 as a decimal integer.%f could be used to print the 5 as a floating point number.
Printing Strings
Using Format specifiers we can print string constants as well as numbers. Here is an example that shows both a string and a number being printed together:
void main ( )
{
printf("%s is %d million miles\nfrom the sun.", "Venus", 67);
}
The output of the program will be:
Venus is 67 million miles
from the sun.
The printf ( ) has replaced the %s symbol with the string "Venus" and the %d symbol with the number 67.
Printing Characters
Printf ( ) can be used to print a single character.
void main ( )
{
printf ("The letter %c is pronounced %s.", 'j', "jay");
}
The output of the program will be:
The letter j is pronounced jay.
In this program 'j' is a character and "jay" is a string. Note that 'j' is surrounded by apostrophes while "jay" is surrounded by double quotes.

No comments:
Post a Comment