3.5
Main
Program
This is the main section or the main
block of the entire program. It is the first part of the program to be
executed.
Format:
main()
{ /*variable
declaration*/
/*statements*/
}
The open brace ({) signify the start
of the program, while the (}) signify the end of the program. Within the
braces, variable declarations should be made. The statements enclosed within
the braces form part of the main program.
24
The
Basic Program Structure
3.5.1
Variable
Declaration
Variables are usually declared before
the start of the program code. The variable declarations tell the C compiler
what type of data will be stored in each variable and how that data will be
represented in memory.
Format:
<datatype>
<variable list>;
At the moment, the type of data that
can be stored in a variable are integer, real, and character. For integer, the
keyword int is used to define the
data type. On the other hand, float and double
are used to define real values. The difference is in the range of numbers it
can accommodate. A char data type requires one byte of memory space and the
range of values that can be assumed is from 0 to 255. The number to character
coding that is used is ASCII. The amount of memory space required to store an
int, a float, and double is platform-dependent (depends on the machine and the
software). For Linux, the following ranges apply: Data Type
Range
int
-2147483648 to +2147483647
long
-2147483648 to +2147483647
float
3.4e-38 to 3.4e38
double
1.7e-308 to 1.7e308
As a convention, we add prefixes in
our variables to easily identify the data type of our variables.
Data
Type
Prefix
int n
long l
float f
double d
char c
Example.
int nAge;
float fTotal;
double
dAmount;
char cMenuOption;
A series of variables of the same
type can be declared at the same time. To do this, the variables are separated
by commas. Although the following example shows that multiple variables in one
declaration statement is possible, it is still best to declare one variable per
declaration statement for readability. Refer to Appendix C
for the coding standards.
25
Chapter
3
Example.
int nNum1, x, nMaxVal;
float fValue, fAverage;
double
dCapital,
dProfit;
char cFirstInit, cLast, ch1;
3.5.2
Assignment
Statement
An assignment statement stores a
value or a computational result in a variable. They are used commonly to
perform most arithmetic operations in a program.
Format:
<variable>
= <expression> ;
The symbol = is the assignment
operator, read as “becomes,” “gets,” or “takes the value of” rather than
“equals.” The variable before the assignment operator is assigned the value of
expression after it. The previous value of variable is erased. The expression
can be a variable, a constant, a literal, or a valid C expression.
Example 1.
x = 1;
/*x is assigned a numeric literal*/
fValue = PI;
/*fValue is assigned the value of a
constant, assuming PI was defined
to contain the constant 3.1416 */
ch1 = cLast; /*ch1 gets the value of
a variable*/
Variables are given an initial value
at the start of the program. This is usually done after the variable has been
declared. C provides a way to initialize a variable at the same time that it
was declared.
Format:
<datatype>
<variable> = <value>;
The value could either be a defined constant identifier or a literal.
Example 2.
int nMiles = 2;
float fVal1 = PI; /*assume PI is a
constant*/
char cCh = ‘N’;
26
The
Basic Program Structure
As mentioned before, a series of
variables can be declared at the same time.
But, take note that if the
declaration of a series of variables is done together with the initialization,
each variable have to initialized separately.
Example 3.
int x, y, z = 1;
In the above example, although x, y,
and z are
A garbage
value is
declared as variables that will
contain integers, only z has
anything contained in the
been initialized with the value of 1.
Both x and y still
memory location for the
contain garbage values. To initialize
all the variables, either
variable, which has no
assign each variable with a value or
use successive
significance or meaning.
assignment operators.
Example 4.
int x = 0, y = 1, z = 1;
The example shows that x is assigned
with 0, while y and z are assigned with 1. Supposing, we want to initialize x
to 1 also, we might as well use successive assignment operators.
Example 5. int x, y, z;
x = y = z = 1;
The value is assigned from right to
left. The variable z is assigned with 1
first, then the value of z will be
given to y, and lastly, the value of y will be given to x.
Note that because of how the values
are initialized, we cannot write something like this:
int x = y = z = 1;
The following example shows that
variables can also be assigned an expression.
Example 6. kms = KMS_PER_MILE * miles;
Before the assignment operation is
evaluated, the value of kms is unknown.
Assume that KMS_PER_MILE has a value
of 1.6, and miles has a value of 2. After the operation, kms would now have a
value of 1.6 * 2 or 3.2.
One should take note that the variable and expression must have the
same data type. Otherwise, the result of the expression will be converted to
the data type of the variable.
Example 7. int kms;
kms = 1.6 * 2;
As seen in Example 6, the result of the expression would be 3.2. However,
since kms is declared as an integer, the fractional part is dropped. Therefore, the
27
Chapter
3
value of kms after the assignment
operation is 3.
Example
7 can also be rewritten as int kms = 1.6 * 2; since we mentioned that we
can initialize a variable with a value while declaring it.
Example 8. sum = sum + 10;
If you can notice, the same variable
name appears both on the left and the right side of the assignment operator.
The statement instructs the computer to add the current value of sum to 10, and
the result is assigned back to sum. Assume sum has an initial value of 100.
Before assignment
:
sum has the value 100
After assignment
:
sum has the value 100+10 or 110
3.5.2.1Shortcuts
on Assignment Statement
3.5.2.1.1Increment
and Decrement
The statement i = i + 1; gets the
value of i, adds it with 1, and stores it again to i. As a result, if the
initial value of i is 5, after executing this statement, i will have the value
of 6. To simplify the increment statement, C allows us to use the increment and
decrement operators.
The increment operator ++ takes a
single variable as its operand. The variable is only incremented by one.
i++;
The value of the expression in which
the ++ operator is the value before it is incremented.
Example.
n = 4;
printf (“%d ”, n++);
printf (“%d ”, n);
Output:
4
5
C also provides a decrement operator,
--. Its function is similar to the increment operator.
28
The
Basic Program Structure
3.5.2.1.2Other
Assignment Operators
For assignment statements that add
more than 1, we can not use the
increment operator anymore. However, C provides some shortcut assignment
operators aside from =. These are the +=, -=, *=, /=, and %=.
Whenever we see the following format:
Before:
<variable> = <variable>
<operator> <expr>; We can now use the shortcut assignment operator
in the following format: After:
<variable>
<operator> = <expr>;
Example.
i = i + 2;
is
equivalent to
i += 2;
x = x – 15;
is
equivalent to
x -= 15;
amt = amt * (1 + rate);
is equal
to
amt
*= 1+ rate;
share = share / 4; is equal to share /= 4;
j = j % 2;
is
equivalent to
j %= 2;
3.5.3
Input and Output Statements
The functions scanf() and printf()
are used for input and output, respectively. (The f in printf and scanf stands
for “formatted”.) These functions
exist in the standard input/output (stdio) library and are available whenever a
C system resides.
3.5.3.1The
printf Statement
Format:
printf( <format string>[, <print
list>] ); The printf() function has a format string and print list
as its arguments. The simple statement
printf( “Let’s Eat!” );
prints the words Let’s Eat on screen.
To show the flexibility of the printf function, let us show the different ways
of printing the word Eat on screen:
29
Chapter
3
printf( “Let’s Eat!” );
printf( “Let’s %s!”, “Eat” );
printf( “Let’s %c%c%c!”, ‘E’, ‘a’,
‘t’ );
Single quotes are used to designate
character literal. The format %c prints the value of an expression as a
character. Note, also, that any space in the format string will be reflected on
the screen output.
When an argument is printed, the
place where it is printed is called its field
and the number of characters in its field is called its field width. The field
width can be specified in a format as an integer occurring between the % and
the conversion character. This is discussed in a short while.
The expression in print list are evaluated and converted
according to the formats in the format string. The % symbol introduces a
conversion format. A single conversion format is a string that begins with %
and ends with a conversion character.
Conversion Character
How the corresponding argument is
printed
c
as a character
d, i
as a decimal integer
f
as a real number; example: 1.230000
s
as a string
%
the % character is printed instead
3.5.3.2The
scanf Statement
Format:
scanf ( <format string> , <input
list> ); The scanf() function is passed a list of arguments that can be
treated as format string and input list. Its first argument is a format string having formats
that correspond to the various ways the characters in the input stream are to
be interpreted. It is merely a string and may contain conversion specifications,
or formats – begins with a % character and ends with a conversion character.
The input lists are addresses where input values are stored.
When the user inputs values into a
program, the sequence of characters (called input
stream) are received by the program. For example, if the user types in the
number 123, the program receives this as a sequence of characters. The scanf()
function can be used to convert a string of decimal digits into an integer
value and stores it at an appropriate place in the memory, specified by input list.
30
The
Basic Program Structure
Example 1. scanf( “%d”, &x );
The formatted %d is matched with
&x, causing the function to interpret the sequence of characters input as a
decimal integer and to store the result at “the address of x”.
Example 2.
char a, b, c;
int n;
float x;
scanf(“%c%c%c%d%f”, &a, &b,
&c, &n, &x );
For the above example, we have the
following format string
“%c%c%c%d%f”, and the following input list: &a, &b, &c,
&n, &x. The input list following the format string consist of addresses
separated by commas. It should be noted that the conversion characters in the
format string is not separated by spaces.
The table below shows the table
showing the commonly-used conversion characters.
Conversion Character
What characters in the input stream
are converted to
c
to a character
d
to a decimal integer
f, lf
to a real number (double), float
Note that for scanf, the conversion
character for double is lf, whereas
in printf, the conversion character is f
only.
3.5.3.3Other
Formatting
Explicit formatting information may
be included in a conversion specification of printf statements. If it is not
included, then defaults are used. For example, the format %f with corresponding
argument 3.77 will result in 3.770000 being printed.
The number is printed with six digits
to the right of the decimal point by default.
Between the % symbol that starts the
conversion specification and a conversion character that ends it, there may
appear (in order):
• zero or more flag characters, discussed below.
• an optional positive integer that specifies the minimum field width of the converted argument. If the converted argument
has fewer characters than the specified field width, then it will be padded
with spaces on the left or right, depending on whether the converted argument
is left- or right-justified.
31
Chapter
3
Numbers are right-justified,
therefore the spaces are padded at the left.
Similarly, spaces for characters and
strings are padded at the leftmost end. If the converted argument has more
characters than the specified field width, then the field width will be
extended to whatever is required. If the integer defining the field width
begins with a zero and the argument being printed is right-justified in its
field, then zeroes rather than spaces will be used for padding.
• an optional precision, which is specified by a period (.) followed by a
nonnegative integer. For d and i conversions, it specifies the minimum number of
digits to be printed. For f conversions, it specifies the number of digits to
the right of the decimal point. For an s conversion, it specifies the maximum
number of characters to be printed from a string.
The flag characters are:
• a minus sign, which means that the
converted argument is to be left-adjusted in its field. If there is no minus
sign, then the converted argument is to be right-adjusted in its field.
• a plus sign, which means that a
nonnegative number that comes from a signed conversion is to have a + appended.
All negative numbers
automatically start with a minus
sign.
• a zero means that zeroes are used
for padding, instead of spaces.
Code
Meaning
alert (ring bell)
newline
backspace
carriage return
formfeed
tab
\
backslash
\u8217?
single quotation mark
\u8221?
double quotation mark
Example.
Value
Format
Displayed
Output
234 %5d └┘└┘234
234 %1d 234
-234 %5d └┘-234
234 %8.5d
└┘└┘└┘00234
-99.42 %6.2f -99.42
-25.554 %6.2f -25.55
.123 %6.2f
└┘└┘0.12
32
The
Basic Program Structure
99.999 %6.2f 100.00
-9.536 %6.2f └┘-9.54
999.4 %6.2f 999.40
3.14159 %5.1f └┘└┘3.1
3.14159 %8.5f └┘3.14159
-.006 %4.2f -0.01
3.14159 %05.1f 003.1
3.14159 %+05.1f +03.1
3.14159 %+5.1f └┘+3.1
3.14159 %-5.1f 3.1└┘└┘
-.006 %-6.2f
-0.01└┘
“hello” %8s └┘└┘└┘hello
“hello” %8.3s └┘└┘└┘└┘└┘hel
**└┘ symbolize 1 space
Walang komento:
Mag-post ng isang Komento