Biyernes, Marso 15, 2013

3.6 A C Program




3.6
            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
           
            : Nathalie 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”,
            GREETING);
           
           
            /* get quiz grades from user */
            printf(“Enter quiz 1: “);
            scanf("%f", &fQ1);
            printf(“Enter quiz 2: “);
            scanf("%f",
            &fQ2);
           
           
           
              
              
              
              
              
              
              
              
              
              33
             Chapter 3
            /* 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("Final Grade = %.2f", fFG);
            }
             
             
            Frequently Asked Questions
             
             1.
             What is a statement?
            All C programs are made up of a sequence of instructions. In C, instructions 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.
           
             3.
             What 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 34
             The Basic Program Structure
            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.
              
              
              
              
              
              
              
              
              
              
              35
             Chapter 3
             
            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 ‘’. It is wrong to have a pair of single quotes containing nothing.
            Therefore, do not write
           
            char ch;
            ch = ‘’;
           
            6. It is incorrect to omit the format string in a printf  or scanf  statement. For this reason, it is wrong to write
           
            int nValue;
           
            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
           
            int nValue;
            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;
             36
             The Basic Program Structure
           
            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:
           
            double dTotal;
           
            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 * R2
            where R 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.
           
           
           
           
           
           
              
              
              
              
              
              
              
              
              
              37
             Chapter 3
            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 that amount.
           
            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
           
           
           
             38
             




3.5 Main




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