Saturday, March 16, 2013

Computer Programming - Chapter 3



CHAPTER 3

 
Overview of C Program
   Has five sections as its program structure, namely: the introductorycomments, header files, constant definitions, function definition, andthe main program but In this chapter, only the introductorycomments, header files, constant definitions, and the main programwill be covered.
Arrangement of the parts of a C program:
<Introductory Comments>
<Header Files>
<Constant Definitions>
<Function Definition>
<Main Program>
<Variable Declaration>
<Statements>
Introductory comments:
Contain the name of the author, the date it was written, and anyassumptions made by the programmer. This is not required but it isrecommended for good programming practice.
The symbols /* signify the start of the comment, while */ signify theend of the comment. A comment enclosed in /* */ can encompassmore than one line.
Example 1.    /* Juan dela Cruz
*  Last Modified : March 22, 1999
*  The program will compute my GPA.
*/
Example 2.     /* This formula computes the interest */
Header files
        Header files are statements that tell the compiler what additionalfiles to process before   processing   the   actual   program.   These   files  contain   useful   functions (subprograms) that have been pre-written.

Format:

#include <<header file>>
Example:
#include <stdio.h>

Constant Definition

Constants are defined for values which will not change throughoutthe entire program.

Format:

#define <constant identifier> <literal>

EXAMPLE:

#define SCHOOL  “De La Salle University”
#define PI          3.1416
#define MID_INIT  ‘T’
#define MAX_STUD       45

 

 

 

 

Main Program

This is the main section or the main block of the entire program. Itis 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, variabledeclarations should be made. The statements enclosed within thebraces form part of the main program.
Variable declaration
       
        They are usually declared before the start of the program code. The variable declarations tell 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>;
                                                       
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 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).
Following ranges apply for Linux:
Data type
Range
Int
-2147483648 to + 2147483647
Long
-2147483648 to + 2147483647
Float
3.7e-38 to 3.4e38
Double
1.7e-308 to 1.7e308
Data type
Prefix
 Int
n
 Long
l
Float
f
Double
d
Char
c
Example:
                   Int               nAge ;
                   Float           fTotal ;
                   Double        dAmount ;
                   Char           cMenuOption ;
Assignment Statement
          It 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 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*/
                   chl=cLast;   /*chl gets the value of a variable*/
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´ ;
  1.           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.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjoAMTScANtsiGGgPeUDKkVRTng5x1EIaLUxBkp1H0ZyiA_ad3wO6jpIbi83OcUOb495ncjBXTPR1DU6x_m6HEh-kZdrKbZ3hy83YOBxMIlE1HIyeHlxk6uDIRBkOmolRPPbJTA3D0ossns/s1600/capture-20130313-184109.png                 Example 3. int x, y, z = 1;
In the above example, although x, y, and z are declared as variables that will contain integers, only z has been initialized with the value of 1. Both x and y still contain garbage values. To initialize all the variables, either assign each variable with a value or use successive assignment operators.

Example4:
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.

Example5:
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.
Example6:
 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.

Example7:
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 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.

Example8:
 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
Shortcuts on Assignment Statement
Increment 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”, n++);
printf (“%d \n”, n);
Output:
4
5
C also provides a decrement operator, --. Its function is similar to the increment operator.
Other 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;
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.
The 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:
                             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
The scanf statement
Text Box: FORMAT
 Scanf( <format string>, <input list> );
 

The scanf() function is passed a list of arguments that can be treated asformatstring  and input list. Its first argument string having formats that correspond to the various way the characters in the input stream are to be interpreted. It is merely a string and may contain conversation specifications or formats - begins with a % character and ends with a conversation 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.
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 as “the address if x
Example 2.         
Char a, b, c;
                   int n;
                   float x;
                   scanf ( “%c%c%c%d%f”,  &a,  &b,  &n,  &x  ) ;
          For the above example, we have the following format string“%c%c%c%d%f” , and the following input list: &a,  &b,  &n,  &x . The input list following the format string consists 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.
Note that the scanf, the conversion character for double is lf, whereas in printf, the conversion character is f only.
Other Formatting
Explicit formatting information may be included in a conversion specification of printf statement. 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. 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.
·         anoptional 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.
Example.
          
 A C Program
Recall that in Chapter 1, we formulated our algorithm to compute for the final grade. Now that we have seen the different parts of a C program and we have discussed some simple statements in C, let us now put it together.
                   /***********************************************
                             File Name             :grade.c
                             Author                           :Nathatlie Rose Lim
                             Last Modified                 :April 25, 2002
                             This program computes the final grade.
                   ***********************************************/
          #include <stdio.h>
#define GREETING “Hello, Let’s compute your grade.”
main()
{
                   float fQ1, fQ2, fMp1, fMp2, fFE, fTE, fFG;
                   printf ( “%s\n” , GREETING) ;
                  
                   /* get quiz grades from user */
printf(“Enter quiz 1: “);
scanf("%f", &fQ1);
printf(“Enter quiz 2: “);
scanf("%f", &fQ2);
                   /* get project grades from user */
printf(“Enter project 1: “);
scanf("%f", &fMp1);
printf(“Enter project 2: “);
scanf("%f", &fMp2);       
/* get final exam grade from user */
printf(“Enter final exam: “);
scanf("%f", &fFE);
/* get teacher’s eval from user */
printf(“Enter teacher’s evaluation: “);
scanf("%f", &fTE);
/* compute final grade */
fFG = 0.50 * ((fQ1 + fQ2)/2) +
                             0.15 * ((fMp1 + fMp2)/2) +
          0.3 * fFE + 0.05 * fTE;
printf("\nThe Final Grade = %.2f\n", fFG);
}
Frequently Asked Questions
1.What is a statement?
All C programs are made up of a sequence of instructions. In Cinstructions are also called statements. In the English language, a statement is terminated by a period, a question mark, or an exclamation point. In C, a statement is terminated by a semicolon.
2.What is the use of { } symbols?
The symbol { and } are called open and close brace, respectively. They signify the start and the end of a block. Note that the braces always come in pairs.
3What is the use of /* */ symbols?
These symbols group comments inside the program. Comments are not instructions, rather they simply provide additional information (a textual description) such as what the program is doing, what are the inputs and outputs, etc. Comments are optional and may be placed anywhere within the program source code.
4. What is a variable?
A variable is an entity that is used to store data. It is the name that the programmer uses to indicate what space in the memory he wants to access. For this space to be accessed, it should be reserved first. Reserving a memory space and giving it a name is called variable declaration. The type of data (data type) to be stored in the memory will indicate how much space is going to be reserved. Each variable has a name, an associated physical memory space (in RAM), a data type, a value, a scope, and a lifetime.
5. What is a data type?
          A data type specifies :
·         the kind of values that can be assumed by a variable of that type
·         the range of values that can be assumed by a variable of that type
·         the amount of memory (in bytes) needed by a variable to store a value of that type
6.Can I use any name for the variables?
Yes, as long as you follow the naming conventions, and do not use the reserved words in C. It is recommended, however, as a good programming practice, for you to use a name that is descriptive or suggestive. Refer to Appendix C to make the format of your variables more readable.
7. What is the value of the variable initially?
By default, the value of a variable is garbage, i.e., there is something stored in that memory space but that something is invalid for the intended use. Using variables with garbage values will cause logical errors.
8. What will happen if I assigned a value whose data type is different from the data type of the receiving variable?
The value will be converted. In general, one that requires smaller memory will fit into the variable with a larger space. The opposite will result to loss of information (which could cause a logical error). The basic rules of data type conversion are as follows:
·         int to float/double : value will be converted to floating-point value
·         float/double to int : the fractional part is dropped
·         char to int/float/double : the char value (based from ASCII character set) will be converted automatically to int/float/double with no problem
·         int to char : if the int value is within the possible range of char values (0 – 255) then that value is assigned and converted to the ASCII character equivalent; otherwise, the value assigned could be unpredictable
·         float/double to char : the fractional part will be discarded and with the whole number part, the same rule as int to char will be applied
9. Does the C language include commands for input/output?
No. Actually, the C programming language by itself does not include commands for input/output of data. However, there is a predefined standard input/output library that can be linked with the programmer’s object file. That is the reason why we need to include stdio.h.
Common Programming Errors
1.     Assigning a variable to a literal is an error. For this reason, it is an error to write
                            
 123 = a
2.     Assigning the value of a variable of the same name is syntactically correct, but is useless and actually does not make sense. For example:
int a;
a = 10;
a = a;
3.     The logical operator and should be &&, not &. The logical operator or should be ||, not |. Using & and | will not result to a syntax error, but will cause a logical error.
4.     In defining a constant, you do not need to use the assignment operator, =, nor end the statement with a semicolon (;). Thus, the following is incorrect
#define PI = 3.1416;
5.     A character literal is enclosed in a pair of single quotes. To represent null character, you have to use ‘\0’. It is wrong to have a pair of single quotes containing nothing. Therefore, do not write
charch;
ch = ‘’;
6.     It is incorrect to omit the format string in a printf or scanf statement. For this reason, it is wrong to write
                                     
intnValue;
                              scanf(nValue );
                             printf(nValue );
7.      There should be an ampersand (&) sign before a variable when used as an input variable. This specifies the memory location where the input will be stored. Thus, it is wrong to write
intnValue;
scanf( “%d”, nValue );
8.     The number of input variables should correspond to the number of conversion specification. The following statements will produce unpredictable results.
                               int nValue1, nValue2;
scanf( “%d%d”, &nValue1 );
scanf( “%d”, &nValue1, &nValue2 );
printf( “%d%d”, nValue1 );
printf( “%d”, nValue1, nValue2 );
9.      A variable declared to contain a double value should use %lf as the conversion character in a scanf statement. However, the conversion character should be %f in a printf statement, whether a variable is declared as a float or double. Thus, incorrect results will occur if you write:
doubledTotal;
scanf( “%f”, &dTotal );
                             printf( “%lf”, dTotal );
10. String literals are enclosed in a pair of double quotes (“). String literal cannot span more than one line. Thus, it is incorrect to write
                                           
printf( “Hello
                                                 World” );
Self Evaluation Exercises
1.     Write a program that inputs a 3-digit number and then display each of the digits.
2.      Write a program that asks the user to enter the radius of a circle and then computes for its area. Recall that the formula to compute for the area is AREA = 3.1416 *  where R2 is the radius. The output of the program must be similar to the one below. The area of the circle with radius 2 cm. is 12.56 sq. cm.
3.     Write a program that will ask the user that asks for a distance in kilometers and converts it to its metric equivalent.
4.     Write a program that inputs two real numbers then exchange their values. 
5.     Workers at a particular company were given a 15.5% salary increase. Moreover, the increase was effective 2 months ago. Write a program that takes the employee’s old salary as input and output the amount of retroactive pay (the increase that wasn’t given for the past 2 months) and the employee’s new salary.
Chapter Exercises
1.     Create a program that will get as input from the user the base and the height of a triangle. Compute the area of the triangle.
Example Run:
Enter base: 15
Enter height : 3
The area of the triangle is 22.5
2.     Create a program that converts a Fahrenheit measure to a Celsius measure (C = 5/9 x (F – 32)).
3.     Philippine currency is broken down into 1000, 500, 200, 100, 50, 20, and 10 peso bills, and 5 and 1 peso coins. Write a program that would input an integer amount in pesos and output the smallest number of bills and coins that would add up to thatamount.
4.     Write a program that displays the reverse of an input 3-digit number while retaining it as a whole.
5.     Ten young men agreed to purchase a gift worth Php10,000 for their boss. In addition, they agreed to continue their plan even if at least one of them dropped out. Write a program that would input the number of men who dropped out (assume 0 to 9 only) and output how much more will each have to contribute toward the purchase of the gift. The display should the format in the sample run below:
Example Run:
      Enter number of persons who dropped out: 3
      Original contribution per person: Php1000.00
      Additional contribution per person: Php428.57
      Computed contribution per person: Php1428.57

 



No comments:

Post a Comment