Write C programs for the following:
(a) Ramesh’s basic salary is input through the keyboard. His dearness allowance is 40% of basic salary, and house rent allowance is 20% of basic salary. Write a program to calculate his gross salary.
(b) The distance between two cities (in km.) is input through the keyboard. Write a program to convert and print this distance in meters, feet, inches and centimeters.
(c) If the marks obtained by a student in five different subjects are input through the keyboard, find out the aggregate marks and percentage marks obtained by the student. Assume that the maximum marks that can be obtained by a student in each subject is 100.
(d) Temperature of a city in Fahrenheit degrees is input through the keyboard. Write a program to convert this temperature into Centigrade degrees.
(e) The length & breadth of a rectangle and radius of a circle are input through the keyboard. Write a program to calculate the area & perimeter of the rectangle, and the area & circumference of the circle.
(f) Two numbers are input through the keyboard into two locations C and D. Write a program to interchange the contents of C and D.
(g) If a five-digit number is input through the keyboard, write a program to calculate the sum of its digits.
(Hint: Use the modulus operator ‘%’)
(h) If a five-digit number is input through the keyboard, write a program to reverse the number.
(i) If a four-digit number is input through the keyboard, write a program to obtain the sum of the first and last digit of this number.
(j) In a town, the percentage of men is 52. The percentage of total literacy is 48. If total percentage of literate men is 35 of the total population, write a program to find the total number of illiterate men and women if the population of the town is 80,000.
(k) A cashier has currency notes of denominations 10, 50 and 100. If the amount to be withdrawn is input through the keyboard in hundreds, find the total number of currency notes of each denomination the cashier will have to give to the withdrawer.
(l) If the total selling price of 15 items and the total profit earned on them is input through the keyboard, write a program to find the cost price of one item.
(m) If a five-digit number is input through the keyboard, write a program to print a new number by adding one to each of its digits. For example if the number that is input is 12391 then the output should be displayed as 23402.
C Language multiple select question chapter one
Pick up the correct alternative for each of the following questions:
(a) C language has been developed by
(1) Ken Thompson
(2) Dennis Ritchie
(3) Peter Norton
(4) Martin Richards
(b) C can be used on
(1) Only MS-DOS operating system
(2) Only Linux operating system
(3) Only Windows operating system
(4) All the above
(c) C programs are converted into machine language with the help of
(1) An Editor
(2) A compiler
(3) An operating system
(4) None of the above
(d) The real constant in C can be expressed in which of the following forms
(1) Fractional form only
(2) Exponential form only
(3) ASCII form only
(4) Both fractional and exponential forms
(e) A character variable can at a time store
(1) 1 character
(2) 8 characters
(3) 254 characters
(4) None of the above
(f) The statement char ch = ‘Z’ would store in ch
(1) The character Z
(2) ASCII value of Z
(3) Z along with the single inverted commas
(4) Both (1) and (2)
(g) Which of the following is NOT a character constant
(1) ‘Thank You’
(2) ‘Enter values of P, N, R’
(3) ‘23.56E-03’
(4) All the above
(h) The maximum value that an integer constant can have is
(1) -32767
(2) 32767
(3) 1.7014e+38
(4) –1.7014e+38
(i) A C variable cannot start with
(1) An alphabet
(2) A number
(3) A special symbol other than underscore
(4) Both (2) & (3) above
(j) Which of the following statement is wrong
(1) mes = 123.56 ;
(2) con = 'T' * 'A' ;
(3) this = 'T' * 20 ;
(4) 3 + a = b ;
(k) Which of the following shows the correct hierarchy of arithmetic operators in C
(1) **, * or /, + or -
(2) **, *, /, +, -
(3) **, /, *, +, -
(4) / or *, - or +
(l) In b = 6.6 / a + 2 * n ; which operation will be performed first?
(1) 6.6 / a
(2) a + 2
(3) 2 * n
(4) Depends upon compiler
(m) Which of the following is allowed in a C Arithmetic instruction
(1) [ ]
(2) { }
(3) ( )
(4) None of the above
(n) Which of the following statements is false
(1) Each new C instruction has to be written on a separate line
(2) Usually all C statements are entered in small case letters
(3) Blank spaces may be inserted between two words in a C statement
(4) Blank spaces cannot be inserted within a variable name
(o) If a is an integer variable, a = 5 / 2 ; will return a value
(1) 2.5
(2) 3
(3) 2
(4) 0
(p) The expression, a = 7 / 22 * ( 3.14 + 2 ) * 3 / 5 ; evaluates to
(1) 8.28
(2) 6.28
(3) 3.14
(4) 0
(q) The expression, a = 30 * 1000 + 2768 ; evaluates to
(1) 32768
(2) -32768
(3) 113040
(4) 0
(r) The expression x = 4 + 2 % - 8 evaluates to
(1) -6
(2) 6
(3) 4
(4) None of the above
(s) Hierarchy decides which operator
(1) is most important
(2) is used first
(3) is fastest
(4) operates on largest numbers
(t) An integer constant in C must have:
(1) At least one digit
(2) Atleast one decimal point
(3) A comma along with digits
(4) Digits separated by commas
(u) A character variable can never store more than
(1) 32 characters
(2) 8 characters
(3) 254 characters
(4) 1 character
(v) In C a variable cannot contain
(1) Blank spaces
(2) Hyphen
(3) Decimal point
(4) All the above
(w) Which of the following is FALSE in C
(1) Keywords can be used as variable names
(2) Variable names can contain a digit
(3) Variable names do not contain a blank space
(4) Capital letters can be used in variable names
(x) In C, Arithmetic instruction cannot contain
(1) variables
(2) constants
(3) variable names on right side of =
(4) constants on left side of =
(y) Which of the following shows the correct hierarchy of arithmetic operations in C
(1) / + * -
(2) * - / +
(3) + - / *
(4) * / + -
(z) What will be the value of d if d is a float after the operation d = 2 / 7.0?
(1) 0
(2) 0.2857
(3) Cannot be determined
(4) None of the above
(a) C language has been developed by
(1) Ken Thompson
(2) Dennis Ritchie
(3) Peter Norton
(4) Martin Richards
(b) C can be used on
(1) Only MS-DOS operating system
(2) Only Linux operating system
(3) Only Windows operating system
(4) All the above
(c) C programs are converted into machine language with the help of
(1) An Editor
(2) A compiler
(3) An operating system
(4) None of the above
(d) The real constant in C can be expressed in which of the following forms
(1) Fractional form only
(2) Exponential form only
(3) ASCII form only
(4) Both fractional and exponential forms
(e) A character variable can at a time store
(1) 1 character
(2) 8 characters
(3) 254 characters
(4) None of the above
(f) The statement char ch = ‘Z’ would store in ch
(1) The character Z
(2) ASCII value of Z
(3) Z along with the single inverted commas
(4) Both (1) and (2)
(g) Which of the following is NOT a character constant
(1) ‘Thank You’
(2) ‘Enter values of P, N, R’
(3) ‘23.56E-03’
(4) All the above
(h) The maximum value that an integer constant can have is
(1) -32767
(2) 32767
(3) 1.7014e+38
(4) –1.7014e+38
(i) A C variable cannot start with
(1) An alphabet
(2) A number
(3) A special symbol other than underscore
(4) Both (2) & (3) above
(j) Which of the following statement is wrong
(1) mes = 123.56 ;
(2) con = 'T' * 'A' ;
(3) this = 'T' * 20 ;
(4) 3 + a = b ;
(k) Which of the following shows the correct hierarchy of arithmetic operators in C
(1) **, * or /, + or -
(2) **, *, /, +, -
(3) **, /, *, +, -
(4) / or *, - or +
(l) In b = 6.6 / a + 2 * n ; which operation will be performed first?
(1) 6.6 / a
(2) a + 2
(3) 2 * n
(4) Depends upon compiler
(m) Which of the following is allowed in a C Arithmetic instruction
(1) [ ]
(2) { }
(3) ( )
(4) None of the above
(n) Which of the following statements is false
(1) Each new C instruction has to be written on a separate line
(2) Usually all C statements are entered in small case letters
(3) Blank spaces may be inserted between two words in a C statement
(4) Blank spaces cannot be inserted within a variable name
(o) If a is an integer variable, a = 5 / 2 ; will return a value
(1) 2.5
(2) 3
(3) 2
(4) 0
(p) The expression, a = 7 / 22 * ( 3.14 + 2 ) * 3 / 5 ; evaluates to
(1) 8.28
(2) 6.28
(3) 3.14
(4) 0
(q) The expression, a = 30 * 1000 + 2768 ; evaluates to
(1) 32768
(2) -32768
(3) 113040
(4) 0
(r) The expression x = 4 + 2 % - 8 evaluates to
(1) -6
(2) 6
(3) 4
(4) None of the above
(s) Hierarchy decides which operator
(1) is most important
(2) is used first
(3) is fastest
(4) operates on largest numbers
(t) An integer constant in C must have:
(1) At least one digit
(2) Atleast one decimal point
(3) A comma along with digits
(4) Digits separated by commas
(u) A character variable can never store more than
(1) 32 characters
(2) 8 characters
(3) 254 characters
(4) 1 character
(v) In C a variable cannot contain
(1) Blank spaces
(2) Hyphen
(3) Decimal point
(4) All the above
(w) Which of the following is FALSE in C
(1) Keywords can be used as variable names
(2) Variable names can contain a digit
(3) Variable names do not contain a blank space
(4) Capital letters can be used in variable names
(x) In C, Arithmetic instruction cannot contain
(1) variables
(2) constants
(3) variable names on right side of =
(4) constants on left side of =
(y) Which of the following shows the correct hierarchy of arithmetic operations in C
(1) / + * -
(2) * - / +
(3) + - / *
(4) * / + -
(z) What will be the value of d if d is a float after the operation d = 2 / 7.0?
(1) 0
(2) 0.2857
(3) Cannot be determined
(4) None of the above
Control Instructions in C
As the name suggests the ‘Control Instructions’ enable us to specify the order in which the various instructions in a program are to be executed by the computer. In other words the control instructions determine the ‘flow of control’ in a program. There are four types of control instructions in C. They are:
(a) Sequence Control Instruction
(b) Selection or Decision Control Instruction
(c) Repetition or Loop Control Instruction
(d) Case Control Instruction
The Sequence control instruction ensures that the instructions are executed in the same order in which they appear in the program. Decision and Case control instructions allow the computer to take a decision as to which instruction is to be executed next. The Loop control instruction helps computer to execute a group of statements repeatedly. In the following chapters we are going to learn these instructions in detail. Try your hand at the Exercise presented on the following pages before proceeding to the next chapter, which discusses the decision control instruction.
Summary
The three primary constants and variable types in C are integer, float and character.
A variable name can be of maximum 31 characters.
Do not use a keyword as a variable name.
An expression may contain any sequence of constants, variables and operators.
Operators having equal precedence are evaluated using associativity.
Left to right associativity means that the left operand of a operator must be unambiguous whereas right to left associativity means that the right operand of a operator must be unambiguous.
Input/output in C can be achieved using scanf( ) and printf( ) functions.
(a) Sequence Control Instruction
(b) Selection or Decision Control Instruction
(c) Repetition or Loop Control Instruction
(d) Case Control Instruction
The Sequence control instruction ensures that the instructions are executed in the same order in which they appear in the program. Decision and Case control instructions allow the computer to take a decision as to which instruction is to be executed next. The Loop control instruction helps computer to execute a group of statements repeatedly. In the following chapters we are going to learn these instructions in detail. Try your hand at the Exercise presented on the following pages before proceeding to the next chapter, which discusses the decision control instruction.
Summary
The three primary constants and variable types in C are integer, float and character.
A variable name can be of maximum 31 characters.
Do not use a keyword as a variable name.
An expression may contain any sequence of constants, variables and operators.
Operators having equal precedence are evaluated using associativity.
Left to right associativity means that the left operand of a operator must be unambiguous whereas right to left associativity means that the right operand of a operator must be unambiguous.
Input/output in C can be achieved using scanf( ) and printf( ) functions.
Associativity of Operators
When an expression contains two operators of equal priority the tie between them is settled using the associativity of the operators. Associativity can be of two types—Left to Right or Right to Left. Left to Right associativity means that the left operand must be unambiguous. Unambiguous in what sense? It must not be involved in evaluation of any other sub-expression. Similarly, in case of Right to Left associativity the right operand must be unambiguous. Let us understand this with an example.
Consider the expression
a = 3 / 2 * 5 ;
Here there is a tie between operators of same priority, that is between / and *. This tie is settled using the associativity of / and *. But both enjoy Left to Right associativity. Figure 1.10 shows for each operator which operand is unambiguous and which is not.
Since both / and * have L to R associativity and only / has unambiguous left operand (necessary condition for L to R associativity) it is performed earlier.
Consider one more expression
a = b = 3 ;
Here both assignment operators have the same priority and same associativity (Right to Left). Figure 1.11 shows for each operator which operand is unambiguous and which is not.
Since both = have R to L associativity and only the second = has unambiguous right operand (necessary condition for R to L associativity) the second = is performed earlier.
Consider yet another expression
z = a * b + c / d ;
Here * and / enjoys same priority and same associativity (Left to Right). Figure 1.12 shows for each operator which operand is unambiguous and which is not. Here since left operands for both operators are unambiguous Compiler is free to perform * or / operation as per its convenience.
since no matter which is performed earlier the result would be same.
Appendix A gives the associativity of all the operators available in C.
Consider the expression
a = 3 / 2 * 5 ;
Here there is a tie between operators of same priority, that is between / and *. This tie is settled using the associativity of / and *. But both enjoy Left to Right associativity. Figure 1.10 shows for each operator which operand is unambiguous and which is not.
Since both / and * have L to R associativity and only / has unambiguous left operand (necessary condition for L to R associativity) it is performed earlier.
Consider one more expression
a = b = 3 ;
Here both assignment operators have the same priority and same associativity (Right to Left). Figure 1.11 shows for each operator which operand is unambiguous and which is not.
Since both = have R to L associativity and only the second = has unambiguous right operand (necessary condition for R to L associativity) the second = is performed earlier.
Consider yet another expression
z = a * b + c / d ;
Here * and / enjoys same priority and same associativity (Left to Right). Figure 1.12 shows for each operator which operand is unambiguous and which is not. Here since left operands for both operators are unambiguous Compiler is free to perform * or / operation as per its convenience.
since no matter which is performed earlier the result would be same.
Appendix A gives the associativity of all the operators available in C.
Hierarchy of Operations
While executing an arithmetic statement, which has two or more operators, we may have some problems as to how exactly does it get executed. For example, does the expression 2 * x - 3 * y correspond to (2x)-(3y) or to 2(x-3y)? Similarly, does A / B * C correspond to A / (B * C) or to (A / B) * C? To answer these questions satisfactorily one has to understand the ‘hierarchy’ of operations. The priority or precedence in which the operations in an arithmetic statement are performed is called the hierarchy of operations. The hierarchy of commonly used operators is shown in Figure.
Now a few tips about usage of operators in general.
(a) Within parentheses the same hierarchy as mentioned in Figure 1.11 is operative. Also, if there are more than one set of parentheses, the operations within the innermost parentheses would be performed first, followed by the operations within the second innermost pair and so on.
We must always remember to use pairs of parentheses. A careless imbalance of the right and left parentheses is a common error. Best way to avoid this error is to type ( ) and then type an expression inside it.
A few examples would clarify the issue further.
Example 1.1: Determine the hierarchy of operations and evaluate the following expression:
i = 2 * 3 / 4 + 4 / 4 + 8 - 2 + 5 / 8
Stepwise evaluation of this expression is shown below:
i = 2 * 3 / 4 + 4 / 4 + 8 - 2 + 5 / 8
i = 6 / 4 + 4 / 4 + 8 - 2 + 5 / 8 operation: *
i = 1 + 4 / 4 + 8 - 2 + 5 / 8 operation: /
i = 1 + 1+ 8 - 2 + 5 / 8 operation: /
i = 1 + 1 + 8 - 2 + 0 operation: /
i = 2 + 8 - 2 + 0 operation: +
i = 10 - 2 + 0 operation: +
i = 8 + 0 operation : -
i = 8 operation: +
Note that 6 / 4 gives 1 and not 1.5. This so happens because 6 and 4 both are integers and therefore would evaluate to only an integer constant. Similarly 5 / 8 evaluates to zero, since 5 and 8 are integer constants and hence must return an integer value.
Example 1.2: Determine the hierarchy of operations and evaluate the following expression:
kk = 3 / 2 * 4 + 3 / 8 + 3
Stepwise evaluation of this expression is shown below:
kk = 3 / 2 * 4 + 3 / 8 + 3
kk = 1 * 4 + 3 / 8 + 3 operation: /
kk = 4 + 3 / 8 + 3 operation: *
kk = 4 + 0 + 3 operation: /
kk = 4 + 3 operation: +
kk = 7 operation: +
Note that 3 / 8 gives zero, again for the same reason mentioned in the previous example.
All operators in C are ranked according to their precedence. And mind you there are as many as 45 odd operators in C, and these can affect the evaluation of an expression in subtle and unexpected ways if we aren't careful. Unfortunately, there are no simple rules that one can follow, such as “BODMAS” that tells algebra students in which order does an expression evaluate. We have not encountered many out of these 45 operators, so we won’t pursue the subject of precedence any further here. However, it can be realized at this stage that it would be almost impossible to remember the precedence of all these operators. So a full-fledged list of all operators and their precedence is given in Appendix A. This may sound daunting, but when its contents are absorbed in small bites, it becomes more palatable.
So far we have seen how the computer evaluates an arithmetic statement written in C. But our knowledge would be incomplete unless we know how to convert a general arithmetic statement to a C statement. C can handle any complex expression with ease. Some of the examples of C expressions are shown in Figure 1.9.
Now a few tips about usage of operators in general.
(a) Within parentheses the same hierarchy as mentioned in Figure 1.11 is operative. Also, if there are more than one set of parentheses, the operations within the innermost parentheses would be performed first, followed by the operations within the second innermost pair and so on.
We must always remember to use pairs of parentheses. A careless imbalance of the right and left parentheses is a common error. Best way to avoid this error is to type ( ) and then type an expression inside it.
A few examples would clarify the issue further.
Example 1.1: Determine the hierarchy of operations and evaluate the following expression:
i = 2 * 3 / 4 + 4 / 4 + 8 - 2 + 5 / 8
Stepwise evaluation of this expression is shown below:
i = 2 * 3 / 4 + 4 / 4 + 8 - 2 + 5 / 8
i = 6 / 4 + 4 / 4 + 8 - 2 + 5 / 8 operation: *
i = 1 + 4 / 4 + 8 - 2 + 5 / 8 operation: /
i = 1 + 1+ 8 - 2 + 5 / 8 operation: /
i = 1 + 1 + 8 - 2 + 0 operation: /
i = 2 + 8 - 2 + 0 operation: +
i = 10 - 2 + 0 operation: +
i = 8 + 0 operation : -
i = 8 operation: +
Note that 6 / 4 gives 1 and not 1.5. This so happens because 6 and 4 both are integers and therefore would evaluate to only an integer constant. Similarly 5 / 8 evaluates to zero, since 5 and 8 are integer constants and hence must return an integer value.
Example 1.2: Determine the hierarchy of operations and evaluate the following expression:
kk = 3 / 2 * 4 + 3 / 8 + 3
Stepwise evaluation of this expression is shown below:
kk = 3 / 2 * 4 + 3 / 8 + 3
kk = 1 * 4 + 3 / 8 + 3 operation: /
kk = 4 + 3 / 8 + 3 operation: *
kk = 4 + 0 + 3 operation: /
kk = 4 + 3 operation: +
kk = 7 operation: +
Note that 3 / 8 gives zero, again for the same reason mentioned in the previous example.
All operators in C are ranked according to their precedence. And mind you there are as many as 45 odd operators in C, and these can affect the evaluation of an expression in subtle and unexpected ways if we aren't careful. Unfortunately, there are no simple rules that one can follow, such as “BODMAS” that tells algebra students in which order does an expression evaluate. We have not encountered many out of these 45 operators, so we won’t pursue the subject of precedence any further here. However, it can be realized at this stage that it would be almost impossible to remember the precedence of all these operators. So a full-fledged list of all operators and their precedence is given in Appendix A. This may sound daunting, but when its contents are absorbed in small bites, it becomes more palatable.
So far we have seen how the computer evaluates an arithmetic statement written in C. But our knowledge would be incomplete unless we know how to convert a general arithmetic statement to a C statement. C can handle any complex expression with ease. Some of the examples of C expressions are shown in Figure 1.9.
Integer and Float Conversions
In order to effectively develop C programs, it will be necessary to understand the rules that are used for the implicit conversion of floating point and integer values in C. These are mentioned below. Note them carefully.
An arithmetic operation between an integer and integer always yields an integer result.
An operation between a real and real always yields a real result.
An operation between an integer and real always yields a real result. In this operation the integer is first promoted to a real and then the operation is performed. Hence the result is real.
I think a few practical examples shown in the following figure would put the issue beyond doubt.
Operation
Result
Operation
Result
5 / 2
2
2 / 5
0
5.0 / 2
2.5
2.0 / 5
0.4
5 / 2.0
2.5
2 / 5.0
0.4
5.0 / 2.0
2.5
2.0 / 5.0
0.4
Type Conversion in Assignments
It may so happen that the type of the expression and the type of the variable on the left-hand side of the assignment operator may not be same. In such a case the value of the expression is promoted or demoted depending on the type of the variable on left-hand side of =.
For example, consider the following assignment statements.
int i ;
float b ;
i = 3.5 ;
b = 30 ;
Here in the first assignment statement though the expression’s value is a float (3.5) it cannot be stored in i since it is an int. In such a case the float is demoted to an int and then its value is stored. Hence what gets stored in i is 3. Exactly opposite happens in the next statement. Here, 30 is promoted to 30.000000 and then stored in b, since b being a float variable cannot hold anything except a float value.
Instead of a simple expression used in the above examples if a complex expression occurs, still the same rules apply. For example, consider the following program fragment.
float a, b, c ;
int s ;
s = a * b * c / 100 + 32 / 4 - 3 * 1.1 ;
Here, in the assignment statement some operands are ints whereas others are floats. As we know, during evaluation of the expression the ints would be promoted to floats and the result of the expression would be a float. But when this float value is assigned to s it is again demoted to an int and then stored in s.
Observe the results of the arithmetic statements shown in Figure 1.7. It has been assumed that k is an integer variable and a is a real variable.
Note that though the following statements give the same result, 0, the results are obtained differently.
k = 2 / 9 ;
k = 2.0 / 9 ;
In the first statement, since both 2 and 9 are integers, the result is an integer, i.e. 0. This 0 is then assigned to k. In the second statement 9 is promoted to 9.0 and then the division is performed. Division yields 0.222222. However, this cannot be stored in k, k being an int. Hence it gets demoted to 0 and then stored in k.
An arithmetic operation between an integer and integer always yields an integer result.
An operation between a real and real always yields a real result.
An operation between an integer and real always yields a real result. In this operation the integer is first promoted to a real and then the operation is performed. Hence the result is real.
I think a few practical examples shown in the following figure would put the issue beyond doubt.
Operation
Result
Operation
Result
5 / 2
2
2 / 5
0
5.0 / 2
2.5
2.0 / 5
0.4
5 / 2.0
2.5
2 / 5.0
0.4
5.0 / 2.0
2.5
2.0 / 5.0
0.4
Type Conversion in Assignments
It may so happen that the type of the expression and the type of the variable on the left-hand side of the assignment operator may not be same. In such a case the value of the expression is promoted or demoted depending on the type of the variable on left-hand side of =.
For example, consider the following assignment statements.
int i ;
float b ;
i = 3.5 ;
b = 30 ;
Here in the first assignment statement though the expression’s value is a float (3.5) it cannot be stored in i since it is an int. In such a case the float is demoted to an int and then its value is stored. Hence what gets stored in i is 3. Exactly opposite happens in the next statement. Here, 30 is promoted to 30.000000 and then stored in b, since b being a float variable cannot hold anything except a float value.
Instead of a simple expression used in the above examples if a complex expression occurs, still the same rules apply. For example, consider the following program fragment.
float a, b, c ;
int s ;
s = a * b * c / 100 + 32 / 4 - 3 * 1.1 ;
Here, in the assignment statement some operands are ints whereas others are floats. As we know, during evaluation of the expression the ints would be promoted to floats and the result of the expression would be a float. But when this float value is assigned to s it is again demoted to an int and then stored in s.
Observe the results of the arithmetic statements shown in Figure 1.7. It has been assumed that k is an integer variable and a is a real variable.
Note that though the following statements give the same result, 0, the results are obtained differently.
k = 2 / 9 ;
k = 2.0 / 9 ;
In the first statement, since both 2 and 9 are integers, the result is an integer, i.e. 0. This 0 is then assigned to k. In the second statement 9 is promoted to 9.0 and then the division is performed. Division yields 0.222222. However, this cannot be stored in k, k being an int. Hence it gets demoted to 0 and then stored in k.
C Instructions
Now that we have written a few programs let us look at the instructions that we used in these programs. There are basically three types of instructions in C:
Type Declaration Instruction
Arithmetic Instruction
Control Instruction
The purpose of each of these instructions is given below:
Type declaration instruction
−
To declare the type of variables used in a C program.
Arithmetic instruction
−
To perform arithmetic operations between con-stants and variables.
Control instruction
−
To control the sequence of execution of various state-ments in a C program.
Since, the elementary C programs would usually contain only the type declaration and the arithmetic instructions; we would discuss only these two instructions at this stage. The other types of instructions would be discussed in detail in the subsequent chapters.
Type Declaration Instruction
This instruction is used to declare the type of variables being used in the program. Any variable used in the program must be declared before using it in any statement. The type declaration statement is written at the beginning of main( ) function.
Ex.: int bas ;
float rs, grosssal ;
char name, code ;
There are several subtle variations of the type declaration instruction. These are discussed below:
(a)
(b)
While declaring the type of variable we can also initialize it as shown below.
int i = 10, j = 25 ;
float a = 1.5, b = 1.99 + 2.4 * 1.44 ;
The order in which we define the variables is sometimes important sometimes not. For example,
int i = 10, j = 25 ;
is same as
int j = 25, j = 10 ;
However,
float a = 1.5, b = a + 3.1 ;
is alright, but
float b = a + 3.1, a = 1.5 ;
is not. This is because here we are trying to use a even before defining it.
(c)
The following statements would work
int a, b, c, d ;
a = b = c = 10 ;
However, the following statement would not work
int a = b = c = d = 10 ;
Once again we are trying to use b (to assign to a) before defining it.
Arithmetic Instruction
A C arithmetic instruction consists of a variable name on the left hand side of = and variable names & constants on the right hand side of =. The variables and constants appearing on the right hand side of = are connected by arithmetic operators like +, -, *, and /.
Ex.: int ad ;
float kot, deta, alpha, beta, gamma ;
ad = 3200 ;
kot = 0.0056 ;
deta = alpha * beta / gamma + 3.2 * 2 / 5 ;
Here,
*, /, -, + are the arithmetic operators.
= is the assignment operator.
2, 5 and 3200 are integer constants.
3.2 and 0.0056 are real constants.
ad is an integer variable.
kot, deta, alpha, beta, gamma are real variables.
The variables and constants together are called ‘operands’ that are operated upon by the ‘arithmetic operators’ and the result is assigned, using the assignment operator, to the variable on left-hand side.
A C arithmetic statement could be of three types. These are as follows:
(a)
(b)
(c)
Integer mode arithmetic statement - This is an arithmetic statement in which all operands are either integer variables or integer constants.
Ex.: int i, king, issac, noteit ;
i = i + 1 ;
king = issac * 234 + noteit - 7689 ;
Real mode arithmetic statement - This is an arithmetic statement in which all operands are either real constants or real variables.
Ex.: float qbee, antink, si, prin, anoy, roi ;
qbee = antink + 23.123 / 4.5 * 0.3442 ;
si = prin * anoy * roi / 100.0 ;
Mixed mode arithmetic statement - This is an arithmetic statement in which some of the operands are integers and some of the operands are real.
Ex.: float si, prin, anoy, roi, avg ;
int a, b, c, num ;
si = prin * anoy * roi / 100.0 ;
avg = ( a + b + c + num ) / 4 ;
It is very important to understand how the execution of an arithmetic statement takes place. Firstly, the right hand side is evaluated using constants and the numerical values stored in the variable names. This value is then assigned to the variable on the left-hand side.
Though Arithmetic instructions look simple to use one often commits mistakes in writing them. Let us take a closer look at these statements. Note the following points carefully.
(a)
(b)
(c)
(d)
C allows only one variable on left-hand side of =. That is, z = k * l is legal, whereas k * l = z is illegal.
In addition to the division operator C also provides a modular division operator. This operator returns the remainder on dividing one integer with another. Thus the expression 10 / 2 yields 5, whereas, 10 % 2 yields 0. Note that the modulus operator (%) cannot be applied on a float. Also note that on using % the sign of the remainder is always same as the sign of the numerator. Thus –5 % 2 yields –1, whereas, 5 % -2 yields 1.
An arithmetic instruction is often used for storing character constants in character variables.
char a, b, d ;
a = 'F' ;
b = 'G' ;
d = '+' ;
When we do this the ASCII values of the characters are stored in the variables. ASCII values are used to represent any character in memory. The ASCII values of ‘F’ and ‘G’ are 70 and 71 (refer the ASCII Table in Appendix E).
Arithmetic operations can be performed on ints, floats and chars.
Thus the statements,
char x, y ;
int z ;
x = 'a' ;
y = 'b' ;
z = x + y ;
are perfectly valid, since the addition is performed on the ASCII values of the characters and not on characters themselves. The ASCII values of ‘a’ and ‘b’ are 97 and 98, and hence can definitely be added.
(e)
(f)
No operator is assumed to be present. It must be written explicitly. In the following example, the multiplication operator after b must be explicitly written.
a = c.d.b(xy) usual arithmetic statement
b = c * d * b * ( x * y ) C statement
Unlike other high level languages, there is no operator for performing exponentiation operation. Thus following statements are invalid.
a = 3 ** 2 ;
b = 3 ^ 2 ;
If we want to do the exponentiation we can get it done this way:
#include
main( )
{
int a ;
a = pow ( 3, 2 ) ;
printf ( “%d”, a ) ;
}
Here pow( ) function is a standard library function. It is being used to raise 3 to the power of 2. #include is a preprocessor directive. It is being used here to ensure that the pow( ) function works correctly. We would learn more about standard library functions in Chapter 5 and about preprocessor in Chapter 7.
Type Declaration Instruction
Arithmetic Instruction
Control Instruction
The purpose of each of these instructions is given below:
Type declaration instruction
−
To declare the type of variables used in a C program.
Arithmetic instruction
−
To perform arithmetic operations between con-stants and variables.
Control instruction
−
To control the sequence of execution of various state-ments in a C program.
Since, the elementary C programs would usually contain only the type declaration and the arithmetic instructions; we would discuss only these two instructions at this stage. The other types of instructions would be discussed in detail in the subsequent chapters.
Type Declaration Instruction
This instruction is used to declare the type of variables being used in the program. Any variable used in the program must be declared before using it in any statement. The type declaration statement is written at the beginning of main( ) function.
Ex.: int bas ;
float rs, grosssal ;
char name, code ;
There are several subtle variations of the type declaration instruction. These are discussed below:
(a)
(b)
While declaring the type of variable we can also initialize it as shown below.
int i = 10, j = 25 ;
float a = 1.5, b = 1.99 + 2.4 * 1.44 ;
The order in which we define the variables is sometimes important sometimes not. For example,
int i = 10, j = 25 ;
is same as
int j = 25, j = 10 ;
However,
float a = 1.5, b = a + 3.1 ;
is alright, but
float b = a + 3.1, a = 1.5 ;
is not. This is because here we are trying to use a even before defining it.
(c)
The following statements would work
int a, b, c, d ;
a = b = c = 10 ;
However, the following statement would not work
int a = b = c = d = 10 ;
Once again we are trying to use b (to assign to a) before defining it.
Arithmetic Instruction
A C arithmetic instruction consists of a variable name on the left hand side of = and variable names & constants on the right hand side of =. The variables and constants appearing on the right hand side of = are connected by arithmetic operators like +, -, *, and /.
Ex.: int ad ;
float kot, deta, alpha, beta, gamma ;
ad = 3200 ;
kot = 0.0056 ;
deta = alpha * beta / gamma + 3.2 * 2 / 5 ;
Here,
*, /, -, + are the arithmetic operators.
= is the assignment operator.
2, 5 and 3200 are integer constants.
3.2 and 0.0056 are real constants.
ad is an integer variable.
kot, deta, alpha, beta, gamma are real variables.
The variables and constants together are called ‘operands’ that are operated upon by the ‘arithmetic operators’ and the result is assigned, using the assignment operator, to the variable on left-hand side.
A C arithmetic statement could be of three types. These are as follows:
(a)
(b)
(c)
Integer mode arithmetic statement - This is an arithmetic statement in which all operands are either integer variables or integer constants.
Ex.: int i, king, issac, noteit ;
i = i + 1 ;
king = issac * 234 + noteit - 7689 ;
Real mode arithmetic statement - This is an arithmetic statement in which all operands are either real constants or real variables.
Ex.: float qbee, antink, si, prin, anoy, roi ;
qbee = antink + 23.123 / 4.5 * 0.3442 ;
si = prin * anoy * roi / 100.0 ;
Mixed mode arithmetic statement - This is an arithmetic statement in which some of the operands are integers and some of the operands are real.
Ex.: float si, prin, anoy, roi, avg ;
int a, b, c, num ;
si = prin * anoy * roi / 100.0 ;
avg = ( a + b + c + num ) / 4 ;
It is very important to understand how the execution of an arithmetic statement takes place. Firstly, the right hand side is evaluated using constants and the numerical values stored in the variable names. This value is then assigned to the variable on the left-hand side.
Though Arithmetic instructions look simple to use one often commits mistakes in writing them. Let us take a closer look at these statements. Note the following points carefully.
(a)
(b)
(c)
(d)
C allows only one variable on left-hand side of =. That is, z = k * l is legal, whereas k * l = z is illegal.
In addition to the division operator C also provides a modular division operator. This operator returns the remainder on dividing one integer with another. Thus the expression 10 / 2 yields 5, whereas, 10 % 2 yields 0. Note that the modulus operator (%) cannot be applied on a float. Also note that on using % the sign of the remainder is always same as the sign of the numerator. Thus –5 % 2 yields –1, whereas, 5 % -2 yields 1.
An arithmetic instruction is often used for storing character constants in character variables.
char a, b, d ;
a = 'F' ;
b = 'G' ;
d = '+' ;
When we do this the ASCII values of the characters are stored in the variables. ASCII values are used to represent any character in memory. The ASCII values of ‘F’ and ‘G’ are 70 and 71 (refer the ASCII Table in Appendix E).
Arithmetic operations can be performed on ints, floats and chars.
Thus the statements,
char x, y ;
int z ;
x = 'a' ;
y = 'b' ;
z = x + y ;
are perfectly valid, since the addition is performed on the ASCII values of the characters and not on characters themselves. The ASCII values of ‘a’ and ‘b’ are 97 and 98, and hence can definitely be added.
(e)
(f)
No operator is assumed to be present. It must be written explicitly. In the following example, the multiplication operator after b must be explicitly written.
a = c.d.b(xy) usual arithmetic statement
b = c * d * b * ( x * y ) C statement
Unlike other high level languages, there is no operator for performing exponentiation operation. Thus following statements are invalid.
a = 3 ** 2 ;
b = 3 ^ 2 ;
If we want to do the exponentiation we can get it done this way:
#include
main( )
{
int a ;
a = pow ( 3, 2 ) ;
printf ( “%d”, a ) ;
}
Here pow( ) function is a standard library function. It is being used to raise 3 to the power of 2. #include
Receiving Input in C
In the program discussed above we assumed the values of p, n and r to be 1000, 3 and 8.5. Every time we run the program we would get the same value for simple interest. If we want to calculate simple interest for some other set of values then we are required to make the relevant change in the program, and again compile and execute it. Thus the program is not general enough to calculate simple interest for any set of values without being required to make a change in the program. Moreover, if you distribute the EXE file of this program to somebody he would not even be able to make changes in the program. Hence it is a good practice to create a program that is general enough to work for any set of values.
To make the program general the program itself should ask the user to supply the values of p, n and r through the keyboard during execution. This can be achieved using a function called scanf( ). This function is a counter-part of the printf( ) function. printf( ) outputs the values to the screen whereas scanf( ) receives them from the keyboard. This is illustrated in the program shown below.
/* Calculation of simple interest */
/* Author gekay Date 25/05/2004 */
main( )
{
int p, n ;
float r, si ;
printf ( "Enter values of p, n, r" ) ;
scanf ( "%d %d %f", &p, &n, &r ) ;
si = p * n * r / 100 ;
printf ( "%f" , si ) ;
}
The first printf( ) outputs the message ‘Enter values of p, n, r’ on the screen. Here we have not used any expression in printf( ) which means that using expressions in printf( ) is optional.
Note that the ampersand (&) before the variables in the scanf( ) function is a must. & is an ‘Address of’ operator. It gives the location number used by the variable in memory. When we say &a, we are telling scanf( ) at which memory location should it store the value supplied by the user from the keyboard. The detailed working of the & operator would be taken up in Chapter 5.
Note that a blank, a tab or a new line must separate the values supplied to scanf( ). Note that a blank is creating using a spacebar, tab using the Tab key and new line using the Enter key. This is shown below:
Ex.: The three values separated by blank
1000 5 15.5
Ex.: The three values separated by tab.
1000 5 15.5
Ex.: The three values separated by newline.
1000
5
15.5
So much for the tips. How about another program to give you a feel of things...
/* Just for fun. Author: Bozo */
main( )
{
int num ;
printf ( "Enter a number" ) ;
scanf ( "%d", &num ) ;
printf ( "Now I am letting you on a secret..." ) ;
printf ( "You have just entered the number %d", num ) ;
}
To make the program general the program itself should ask the user to supply the values of p, n and r through the keyboard during execution. This can be achieved using a function called scanf( ). This function is a counter-part of the printf( ) function. printf( ) outputs the values to the screen whereas scanf( ) receives them from the keyboard. This is illustrated in the program shown below.
/* Calculation of simple interest */
/* Author gekay Date 25/05/2004 */
main( )
{
int p, n ;
float r, si ;
printf ( "Enter values of p, n, r" ) ;
scanf ( "%d %d %f", &p, &n, &r ) ;
si = p * n * r / 100 ;
printf ( "%f" , si ) ;
}
The first printf( ) outputs the message ‘Enter values of p, n, r’ on the screen. Here we have not used any expression in printf( ) which means that using expressions in printf( ) is optional.
Note that the ampersand (&) before the variables in the scanf( ) function is a must. & is an ‘Address of’ operator. It gives the location number used by the variable in memory. When we say &a, we are telling scanf( ) at which memory location should it store the value supplied by the user from the keyboard. The detailed working of the & operator would be taken up in Chapter 5.
Note that a blank, a tab or a new line must separate the values supplied to scanf( ). Note that a blank is creating using a spacebar, tab using the Tab key and new line using the Enter key. This is shown below:
Ex.: The three values separated by blank
1000 5 15.5
Ex.: The three values separated by tab.
1000 5 15.5
Ex.: The three values separated by newline.
1000
5
15.5
So much for the tips. How about another program to give you a feel of things...
/* Just for fun. Author: Bozo */
main( )
{
int num ;
printf ( "Enter a number" ) ;
scanf ( "%d", &num ) ;
printf ( "Now I am letting you on a secret..." ) ;
printf ( "You have just entered the number %d", num ) ;
}
Compilation and Execution in C Language
Once you have written the program you need to type it and instruct the machine to execute it. To type your C program you need another program called Editor. Once the program has been typed it needs to be converted to machine language (0s and 1s) before the machine can execute it. To carry out this conversion we need another program called Compiler. Compiler vendors provide an Integrated Development Environment (IDE) which consists of an Editor as well as the Compiler.
There are several such IDEs available in the market targeted towards different operating systems. For example, Turbo C, Turbo C++ and Microsoft C are some of the popular compilers that work under MS-DOS; Visual C++ and Borland C++ are the compilers that work under Windows, whereas gcc compiler works under Linux. Note that Turbo C++, Microsoft C++ and Borland C++ software also contain a C compiler bundled with them. If you are a beginner you would be better off using a simple compiler like Turbo C or Turbo C++. Once you have mastered the language elements you can then switch over to more sophisticated compilers like Visual C++ under Windows or gcc under Linux. Most of the programs in this book would work with all the compilers. Wherever there is a deviation I would point it out that time.
Assuming that you are using a Turbo C or Turbo C++ compiler here are the steps that you need to follow to compile and execute your first C program…
Start the compiler at C> prompt. The compiler (TC.EXE is usually present in C:\TC\BIN directory).
Select New from the File menu.
Type the program.
Save the program using F2 under a proper name (say Program1.c).
Use Ctrl + F9 to compile and execute the program.
Use Alt + F5 to view the output.
Note that on compiling the program its machine language equivalent is stored as an EXE file (Program1.EXE) on the disk. This file is called an executable file. If we copy this file to another machine we can execute it there without being required to recompile it. In fact the other machine need not even have a compiler to be able to execute the file.
A word of caution! If you run this program in Turbo C++ compiler, you may get an error — “The function printf should have a prototype”. To get rid of this error, perform the following steps and then recompile the program.
Select ‘Options’ menu and then select ‘Compiler | C++ Options’. In the dialog box that pops up, select ‘CPP always’ in the ‘Use C++ Compiler’ options.
Again select ‘Options’ menu and then select ‘Environment | Editor’. Make sure that the default extension is ‘C’ rather than ‘CPP’.
There are several such IDEs available in the market targeted towards different operating systems. For example, Turbo C, Turbo C++ and Microsoft C are some of the popular compilers that work under MS-DOS; Visual C++ and Borland C++ are the compilers that work under Windows, whereas gcc compiler works under Linux. Note that Turbo C++, Microsoft C++ and Borland C++ software also contain a C compiler bundled with them. If you are a beginner you would be better off using a simple compiler like Turbo C or Turbo C++. Once you have mastered the language elements you can then switch over to more sophisticated compilers like Visual C++ under Windows or gcc under Linux. Most of the programs in this book would work with all the compilers. Wherever there is a deviation I would point it out that time.
Assuming that you are using a Turbo C or Turbo C++ compiler here are the steps that you need to follow to compile and execute your first C program…
Start the compiler at C> prompt. The compiler (TC.EXE is usually present in C:\TC\BIN directory).
Select New from the File menu.
Type the program.
Save the program using F2 under a proper name (say Program1.c).
Use Ctrl + F9 to compile and execute the program.
Use Alt + F5 to view the output.
Note that on compiling the program its machine language equivalent is stored as an EXE file (Program1.EXE) on the disk. This file is called an executable file. If we copy this file to another machine we can execute it there without being required to recompile it. In fact the other machine need not even have a compiler to be able to execute the file.
A word of caution! If you run this program in Turbo C++ compiler, you may get an error — “The function printf should have a prototype”. To get rid of this error, perform the following steps and then recompile the program.
Select ‘Options’ menu and then select ‘Compiler | C++ Options’. In the dialog box that pops up, select ‘CPP always’ in the ‘Use C++ Compiler’ options.
Again select ‘Options’ menu and then select ‘Environment | Editor’. Make sure that the default extension is ‘C’ rather than ‘CPP’.
The First C Program
Armed with the knowledge about the types of variables, constants & keywords the next logical step is to combine them to form instructions. However, instead of this, we would write our first C program now. Once we have done that we would see in detail the instructions that it made use of.
Before we begin with our first C program do remember the following rules that are applicable to all C programs:
(a)
Each instruction in a C program is written as a separate statement. Therefore a complete C program would comprise of a series of statements.
The statements in a program must appear in the same order in which we wish them to be executed; unless of course the logic of the problem demands a deliberate ‘jump’ or transfer of control to a statement, which is out of sequence.
Blank spaces may be inserted between two words to improve the readability of the statement. However, no blank spaces are allowed within a variable, constant or keyword.
All statements are entered in small case letters.
C has no specific rules for the position at which a statement is to be written. That’s why it is often called a free-form language.
Every C statement must end with a ;. Thus ; acts as a statement terminator.
Let us now write down our first C program. It would simply calculate simple interest for a set of values representing principle, number of years and rate of interest.
/* Calculation of simple interest */
/* Author gekay Date: 25/05/2004 */
main( )
{
int p, n ;
float r, si ;
p = 1000 ;
n = 3 ;
r = 8.5 ;
/* formula for simple interest */
si = p * n * r / 100 ;
printf ( "%f" , si ) ;
}
Now a few useful tips about the program...
− Comment about the program should be enclosed within /* */. For example, the first two statements in our program are comments.
− Though comments are not necessary, it is a good practice to begin a program with a comment indicating the purpose of the program, its author and the date on which the program was written.
− Any number of comments can be written at any place in the program. For example, a comment can be written before the statement, after the statement or within the statement as shown below:
/* formula */ si = p * n * r / 100 ;
si = p * n * r / 100 ; /* formula */
si = p * n * r / /* formula */ 100 ;
− Sometimes it is not so obvious as to what a particular statement in a program accomplishes. At such times it is worthwhile mentioning the purpose of the statement (or a set of statements) using a comment. For example:
/* formula for simple interest */
si = p * n * r / 100 ;
− Often programmers seem to ignore writing of comments. But when a team is building big software well commented code is almost essential for other team members to understand it.
− Although a lot of comments are probably not necessary in this program, it is usually the case that programmers tend to use too few comments rather than too many. An adequate number of comments can save hours of misery and suffering when you later try to figure out what the program does.
− The normal language rules do not apply to text written within /* .. */. Thus we can type this text in small case, capital or a combination. This is because the comments are solely given for the understanding of the programmer or the fellow programmers and are completely ignored by the compiler.
− Comments cannot be nested. For example,
/* Cal of SI /* Author sam date 01/01/2002 */ */
is invalid.
− A comment can be split over more than one line, as in,
/* This is
a jazzy
comment */
Such a comment is often called a multi-line comment.
− main( ) is a collective name given to a set of statements. This name has to be main( ), it cannot be anything else. All statements that belong to main( ) are enclosed within a pair of braces { } as shown below.
main( )
{
statement 1 ;
statement 2 ;
statement 3 ;
}
− Technically speaking main( ) is a function. Every function has a pair of parentheses ( ) associated with it. We would discuss functions and their working in great detail in Chapter 5.
− Any variable used in the program must be declared before using it. For example,
int p, n ;
float r, si ;
− Any C statement always ends with a ;
For example,
float r, si ;
r = 8.5 ;
− In the statement,
si = p * n * r / 100 ;
* and / are the arithmetic operators. The arithmetic operators available in C are +, -, * and /. C is very rich in operators. There are about 45 operators available in C. Surprisingly there is no operator for exponentiation... a slip, which can be forgiven considering the fact that C has been developed by an individual, not by a committee.
− Once the value of si is calculated it needs to be displayed on the screen. Unlike other languages, C does not contain any instruction to display output on the screen. All output to screen is achieved using readymade library functions. One such function is printf( ). We have used it display on the screen the value contained in si.
The general form of printf( ) function is,
printf ( "",
can contain,
%f for printing real values
%d for printing integer values
%c for printing character values
In addition to format specifiers like %f, %d and %c the format string may also contain any other characters. These characters are printed as they are when the printf( ) is executed.
Following are some examples of usage of printf( ) function:
printf ( "%f", si ) ;
printf ( "%d %d %f %f", p, n, r, si ) ;
printf ( "Simple interest = Rs. %f", si ) ;
printf ( "Prin = %d \nRate = %f", p, r ) ;
The output of the last statement would look like this...
Prin = 1000
Rate = 8.5
What is ‘\n’ doing in this statement? It is called newline and it takes the cursor to the next line. Therefore, you get the output split over two lines. ‘\n’ is one of the several Escape Sequences available in C. These are discussed in detail in Chapter 11. Right now, all that we can say is ‘\n’ comes in handy when we want to format the output properly on separate lines.
printf( ) can not only print values of variables, it can also print the result of an expression. An expression is nothing but a valid combination of constants, variables and operators. Thus, 3, 3 + 2, c and a + b * c – d all are valid expressions. The results of these expressions can be printed as shown below:
printf ( "%d %d %d %d", 3, 3 + 2, c, a + b * c – d ) ;
Note that 3 and c also represent valid expressions.
Before we begin with our first C program do remember the following rules that are applicable to all C programs:
(a)
Each instruction in a C program is written as a separate statement. Therefore a complete C program would comprise of a series of statements.
The statements in a program must appear in the same order in which we wish them to be executed; unless of course the logic of the problem demands a deliberate ‘jump’ or transfer of control to a statement, which is out of sequence.
Blank spaces may be inserted between two words to improve the readability of the statement. However, no blank spaces are allowed within a variable, constant or keyword.
All statements are entered in small case letters.
C has no specific rules for the position at which a statement is to be written. That’s why it is often called a free-form language.
Every C statement must end with a ;. Thus ; acts as a statement terminator.
Let us now write down our first C program. It would simply calculate simple interest for a set of values representing principle, number of years and rate of interest.
/* Calculation of simple interest */
/* Author gekay Date: 25/05/2004 */
main( )
{
int p, n ;
float r, si ;
p = 1000 ;
n = 3 ;
r = 8.5 ;
/* formula for simple interest */
si = p * n * r / 100 ;
printf ( "%f" , si ) ;
}
Now a few useful tips about the program...
− Comment about the program should be enclosed within /* */. For example, the first two statements in our program are comments.
− Though comments are not necessary, it is a good practice to begin a program with a comment indicating the purpose of the program, its author and the date on which the program was written.
− Any number of comments can be written at any place in the program. For example, a comment can be written before the statement, after the statement or within the statement as shown below:
/* formula */ si = p * n * r / 100 ;
si = p * n * r / 100 ; /* formula */
si = p * n * r / /* formula */ 100 ;
− Sometimes it is not so obvious as to what a particular statement in a program accomplishes. At such times it is worthwhile mentioning the purpose of the statement (or a set of statements) using a comment. For example:
/* formula for simple interest */
si = p * n * r / 100 ;
− Often programmers seem to ignore writing of comments. But when a team is building big software well commented code is almost essential for other team members to understand it.
− Although a lot of comments are probably not necessary in this program, it is usually the case that programmers tend to use too few comments rather than too many. An adequate number of comments can save hours of misery and suffering when you later try to figure out what the program does.
− The normal language rules do not apply to text written within /* .. */. Thus we can type this text in small case, capital or a combination. This is because the comments are solely given for the understanding of the programmer or the fellow programmers and are completely ignored by the compiler.
− Comments cannot be nested. For example,
/* Cal of SI /* Author sam date 01/01/2002 */ */
is invalid.
− A comment can be split over more than one line, as in,
/* This is
a jazzy
comment */
Such a comment is often called a multi-line comment.
− main( ) is a collective name given to a set of statements. This name has to be main( ), it cannot be anything else. All statements that belong to main( ) are enclosed within a pair of braces { } as shown below.
main( )
{
statement 1 ;
statement 2 ;
statement 3 ;
}
− Technically speaking main( ) is a function. Every function has a pair of parentheses ( ) associated with it. We would discuss functions and their working in great detail in Chapter 5.
− Any variable used in the program must be declared before using it. For example,
int p, n ;
float r, si ;
− Any C statement always ends with a ;
For example,
float r, si ;
r = 8.5 ;
− In the statement,
si = p * n * r / 100 ;
* and / are the arithmetic operators. The arithmetic operators available in C are +, -, * and /. C is very rich in operators. There are about 45 operators available in C. Surprisingly there is no operator for exponentiation... a slip, which can be forgiven considering the fact that C has been developed by an individual, not by a committee.
− Once the value of si is calculated it needs to be displayed on the screen. Unlike other languages, C does not contain any instruction to display output on the screen. All output to screen is achieved using readymade library functions. One such function is printf( ). We have used it display on the screen the value contained in si.
The general form of printf( ) function is,
printf ( "
- ) ;
%f for printing real values
%d for printing integer values
%c for printing character values
In addition to format specifiers like %f, %d and %c the format string may also contain any other characters. These characters are printed as they are when the printf( ) is executed.
Following are some examples of usage of printf( ) function:
printf ( "%f", si ) ;
printf ( "%d %d %f %f", p, n, r, si ) ;
printf ( "Simple interest = Rs. %f", si ) ;
printf ( "Prin = %d \nRate = %f", p, r ) ;
The output of the last statement would look like this...
Prin = 1000
Rate = 8.5
What is ‘\n’ doing in this statement? It is called newline and it takes the cursor to the next line. Therefore, you get the output split over two lines. ‘\n’ is one of the several Escape Sequences available in C. These are discussed in detail in Chapter 11. Right now, all that we can say is ‘\n’ comes in handy when we want to format the output properly on separate lines.
printf( ) can not only print values of variables, it can also print the result of an expression. An expression is nothing but a valid combination of constants, variables and operators. Thus, 3, 3 + 2, c and a + b * c – d all are valid expressions. The results of these expressions can be printed as shown below:
printf ( "%d %d %d %d", 3, 3 + 2, c, a + b * c – d ) ;
Note that 3 and c also represent valid expressions.
Subscribe to:
Posts (Atom)