Problem Solving Through C Programming - Chapter 2: January 2013
Problem Solving Through C Programming - Chapter 2: January 2013
net/publication/276202732
CITATIONS READS
0 41,596
1 author:
Rama M A
Maharani Lakshmi Ammanni College for Women
11 PUBLICATIONS 59 CITATIONS
SEE PROFILE
All content following this page was uploaded by Rama M A on 12 May 2015.
2.3 APPLICATIONS OF C
C has been used to develop system software and application software such as:
Compilers
Loaders
Linkers
Interpreters
Operating Systems
Data Base Management Systems (DBMS)
Word Processors
Spread sheets
Graphics packages
CAD/CAM applications
Scientific and Engineering Applications
To write a sequence of instructions in any programming language the following must
be known :
1. The character set or alphabets of the language.
2. Using the character set, forming meaningful words called tokens.
3. Writing instructions using tokens.
4. Writing a program using these instructions.
Digits 0 to 9
2.5 C TOKENS
A token is the basic and the smallest unit of a program. There are six types of
tokens in C which are listed in Fig. 2.2. Each token can be formed using one or more C
characters.
Token Usage
1. Keywords Include do, int, for etc
2. Identifiers Include variable names such as total, area, sum
3. Constants Include numbers such as 250, 25.5, –200 etc
4. Strings Include “college”, “2+3” etc
5. Operators Include +, –, *, ++ etc
6. Special symbols Include !, #, [ ], { } etc
Trigraph Characters
Some of the characters shown in Figure 2.1 are not supported by non-english
keyboards. In such cases C has introduced the concept of trigraph sequences, providing a
way for the user to enter the characters not available on the keyboard. Every non-
available character is represented by 3 characters - two question marks followed by
another character. For example, the left and the right braces { } can be keyed in using the
trigraphs ??< and ??>.
2.6 C KEYWORDS
There are some reserved words in C, called keywords. All the keywords have
standard pre-defined meanings and can be used only for the purpose intended. All
keywords must be written in lowercase. They cannot be used as user-defined identifiers.
The standard keywords are listed as in Fig. 2.3.
2.7 IDENTIFIERS
Identifiers refer to the names of program elements such as variables, functions
and arrays.
Identifiers are sequence of characters chosen from the set A–Z, a–z, 0–9,
and _ (underscore).
C is a case sensitive language so that ALFA and Alfa are different.
The underscore symbol _ is generally in the middle of an identifier (embedded).
Identifiers may be of reasonable length of 8–10 characters though certain
computers allow up to 32 characters.
Identifier names must start with an alphabet or underscore followed by letters,
digit or a combination of both.
C has a list of keywords that cannot be used anywhere other than that
predefined in the language i.e., you can’t have a variable named int. Also one
must follow the practice of choosing names for variables which indicate the roles
of those variables in the program.
Example 2.1
valid identifiers are :
sum,avg_ht, x1,y1,PINCODE,Total
invalid identifiers are:
10th,S.I., total amount, Std-no
2.8 A C PROGRAM
The best way to learn C or any programming language is to begin writing programs
in it. Consider the following program.
/*Program to print a message*/
#include<stdio.h>
main()
{
printf(“Programming in C is fun!!\n”);
return;
}
Example 2.2
/*Comments may extend over many lines,
but as a rule they should be short*/
Subroutine Section U|
f1
f2
|V User-defined functions
: ||
fn W
Fig. 2.4 : Structure of a C Program
Symbolic Constants are included using # define. For example to define the value of
PI, the statement is:
# define PI 3.14159
(v) Braces
All C programs incorporate a set of curly braces { }. Execution of the program begins
at the opening brace { of the main( ) function and ends at its closing brace }.
(vi) Declaration Part
This part is used to declare all the variables, arrays functions etc. used in the C
program. Initialization along with declaration can also be done here.
(vii) Executable Part
This part of the program consists of a set of executable statements such as Input/
Output statements, arithmetic statements, control statements etc. It can also include
comment statements which are ignored by the compiler (non-executable). The declaration
part and the executable part must be within opening and closing braces.
Every statement in the declaration part and executable part ends with a semicolon.
Example 2.3
/*Program to find the area of a square*/
#include <stdio.h>
main()
{
float side, area ;
side=5;
area=side*side;
printf(“\nArea of a square=%f’,area);
}
Output:
Area of a square = 25.0
The first line of Example 2.3 refers to the documentation section. It consists of a set
of comment lines giving the name and other details of the program.
The second line is the preprocessor statement # include <stdio.h> providing the link
to the system library.
The third line refers to the main ( ) function. All C programs must have only one
main ( ) function.
The fourth line contains the declaration part where the variables side and area are
declared.
The rest of the program contains the executable statements. The declaration part
and the executable part are within opening & closing braces.
44 PROBLEM SOLVING TECHNIQUES USING C
Every statement in the declaration part and executable part ends with a semicolon.
Execution of the program begins at the opening brace of the main( ) function and
ends at its closing brace.
However for better readability, the statements can be written in separate lines.
2.12 CONSTANTS
Any fixed value that does not change during the execution of a program is known as
a constant. C consists of several types of constants, as shown in fig. 2.5.
Types of C constants
C constants can be divided into two categories :
Primary Constants
Secondary Constants
These constants can further be divided as follows :
or
derived
type
Function
Array
pointer
structure
union
enumerated
In most of the personal computers the maximum integer value is 32767 (decimal
system), 77777 in octal or 7fff in hexadecimal which is 215 – 1.
Large integer constants can be stored by using qualifiers, such as U,L and UL which
are appended to the end of the constant. For example :
12345678U or 12345678u
456789L or 4567891
2345789UL or 2345789ul
Example 2.4
The exponential (or scientific) form of representation of real constant is used when
the value is either too small or too large. In this form the real constant is represented in
two parts. The part appearing before ‘e’ is called Mantissa, and the part following ‘e’ is
called Exponent. For example, consider the value 516.55. This can be written as 5.1655 E2
in exponential form.
E2 means multiply by 102.
The rules for expressing real constants in exponential form are :
(a) The mantissa part and the exponential part must be separated by the letter e(or
E).
(b) The mantissa may be positive or negative.
(c) The exponent must have at least one digit, which must be a positive or negative
integer.
(d) Range of real constants in exponential form is 3.4e+38 to 3.4e+38.
Example 2.5
Real numbers are referred to as floating point numbers since the exponent causes
the decimal point to float.
Example 2.6
Note that the character constant ‘2’ is not the same as the number 2. Every
character has an equivalent integer value known as the ASCII code. Some character
constant & their equivalent ASCII values are as below :
‘A’ 65
‘B’ 66
‘Z’ 90
‘a’ 97
‘z’ 122
‘0’ 48
‘1’ 49
‘’ 32
Example 2.7
Note that ‘A’ is not equal to “A” since a string constant containing a single character
does not have a corresponding integer value. In fact it contains two characters, the
specified character followed by a null character represents by \0.
The defined constants make the program easily modifiable and enhance the
understandability of the program.
Memory Constants: use a c type qualifier called const, to indicate that the data
specified is a constant and that it cannot be changed. Its general format is :
const Datatype identifier = value ;
For example :
const float pi = 3.14159 ;
Example 2.8
main ( )
{
printf(“ This\n string\n will\n be\n
printed\n in\n 8\n lines.”);
}
Output
This
string
will
be
printed
in
8
lines.
50 PROBLEM SOLVING TECHNIQUES USING C
To include double quotes within a string use the escape sequence \”.
Similarly \\ is used to print \ and \’ to print single quote.
To continue a long string into the next line, insert a backslash (\) followed by a <cr>,
where you wish to break the string.
All escape sequences begin with a backslash.
Other escape sequences available in C are :
2.14 VARIABLES
A variable is an identifier used to store a single data item. This data could be a
numerical quantity or a character constant. During execution of the program, data must
be assigned to the variable. Therefore a variable can take different values at different
times during the execution of the program. The data stored in the variable can be accessed
any time, by referring to the variable name.
OVERVIEW OF C LANGUAGE 51
Example 2.9
From the above example it is clear that a variable can be assigned different data at
different times within the program.
The rules for naming a variable are the same as those for an identifier.
They are :
1. Variable names generally begin with a letter followed by letters, digits
underscore or a combination of all.
2. No special character except the underscore symbol ( _ ) is allowed. Underscore is
generally embedded in a variable name to make it more readable.
3. Maximum length of a variable name should not exceed 32 characters. Normally
the length must not exceed 8 characters since many compilers treat the first 8
characters as significant.
4. C variables are case sensitive, so that Counter, counter and COUNTER are 3
different variables.
5. C keywords cannot be used as variable names.
6. White spaces are not allowed in a variable name.
7. Appropriate variable names must be chosen to indicate their role in the
program.
Example 2.10
v) Unsigned long int : Unsigned long removes the sign bit and doubles the
storage space of long int for positive integers.
The qualifier signed is not used since the default declaration assumes a signed
number. Fig. 2.8 gives data type, size and range of modifiers.
data_type a1,a2,......an;
where a1,a2,......an are variable names and data_type is a basic date type such as int, float,
etc. Declaration of more than one variable must be separated by commas.
Example 2.11
int x, y, z ;
float avg, sum ;
char ans ;
double amount;
Here x,y and z are declared as integer variables, avg and sum as float variables, ans
is a character type of variable and amount is of double type.
The above declarations can be also be written as :
int x ;
int y ;
int z ;
float avg ;
float sum;
char ans ;
Variable_name=constant/Variable/expression;
This statement causes the value 0, on the right hand side of the equal (=) sign, to be
assigned to the variable total on the left.
The right hand side of statement can be a constant, variable or an expression
containing one or both. For example, in the statement
sum = marks1 + marks2;
The expression on RHS is evaluated first and the resultant value in stored in sum
i.e., marks1 and marks2 are added and the result is stored in sum. Similarly
count = count +1;
Increments the old value of count by 1 and stores it in count. If the old value of
count was 10, the new value becomes 11.
Example 2.12
/*Assigning value to variables in the declaration part*/
.
.
.
.
int x=1,y=2,z=3;
float avg=0.0,pi;
char opt=’y’;
C also allows multiple assignments in one statement. Some valid statement are :
a=b=c=0;
x1=x2=large;
Note : The left hand side of an assignment statement must always contain only one
variable name.
56 PROBLEM SOLVING TECHNIQUES USING C
Example 2.13
/*Program to find circumference of a circle*/
#include<stdio.h>
main()
{
/*Declaration and assignment*/
float pi=3.14159,radius=10,circum;
circum=2*pi*radius;
printf(“\nCircumference=%f’’,circum);
return;
}
Output
Circumference=62.831802
Example 2.14
/*Program to find total and average of marks obtained in 4 subjects*/
#include<stdio.h>
main()
{
int m1,m2,m3,m4;
float total,avg;
/* assignment in executable part*/
m1=50;m2=70;m3=75;m4=67;
total=m1+m2+m3+m4;
avg=total/4;
printf(“\nThe average marks=%f’’,avg);
return;
}
Output
The average marks = 65.500000
Example 2.15
/*Program to compute area of a circle*/
#include<stdio.h>
main()
{
/*Declarations*/
float pi, r, area;
/*Assignments*/
pi=3.14159;
OVERVIEW OF C LANGUAGE 57
r=5;
/*calculation and printing*/
area=pi*r*r;
printf(“\nArea of circle=%f”,area);
return;
}
Output
Area of circle=78.539749
Another way of assigning values to the variables is to read data through keyboard
using the scanf( )function. It is similar to printf( )function used to print the output.
Example 2.16
Example 2.17
Output
Enter the circumference of the circle : 8
The radius of the given circle is : 1.27
2.20 OPERATORS IN C
C provides several operators for elementary arithmetic operations like addition,
subtraction, multiplication, division, residue-modulo (the operation that gives the
remainder after division of one integer by another) and logical manipulations.
An operator is a symbol used for certain type of manipulations, logical or
mathematical. The data on which the operators act are called operands. An expression is
a valid combination of operators and operands that results in a value. For example in the
expression :
12*5
* is the multiplication operator,
12 and 5 are the operands.
OVERVIEW OF C LANGUAGE 59
Operator Purpose
+ Addition
– Subtraction or (unary)
* Multiplication
/ Division
% Remainder after integer division
Expression Result
+16 16
–5 –5
a+b 19
a–b 13
a*b 48
a/b 5(decimal part is truncated)
a%b 1(remainder of division)
C1 = 80, C2 = 84.
Expression Result
C1+C2 164
C1+C2+5 169
C1+’1' 129
In integer division, if one of the number is negative, the result will be truncated
depending on the machine. For example :
5/6=0 and –5/–6=0
but –5/6 may be zero or –1. In turbo C it is 0. Further, in modulo division the sign of
the remainder is the sign of the first operand. For example :
–20 % 6 = –2
–20 % –6 = –2
20 % –6 = 2
15/2.0 = 7.5
However 15/2 = 7
are called relational expressions whose value can be either true or false i.e., 50<200 is
false; when x = 10 and y = 5, x > y is true. There are 6 relational operators in C. They are
as shown in Fig. 2.10.
62 PROBLEM SOLVING TECHNIQUES USING C
Operator Meaning
> greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
== Equal to
!= Not equal to
Example 2.19
In the 4th and 5th example given above the expressions contain arithmetic
expression. Thus in the relational expression (i+j)>=k, the arithmetic expression i+j will be
evaluated and then the result is compared with k. These arithmetic operators have higher
priority over relational operators. The relational operators are used to compare two
quantities in decision statements.
Example 2.20
Output
Value of 10.5 <= 12 : 1
Value of i == 2 : 0
Value of 5 < 4 : 0
Value of i+j >= k : 0
Value of j+k+1 > i+5 : 1
Value of k != 7 : 0
Operator Meaning
! logical NOT
&& logical AND
|| logical OR
The result of a logical AND is true only if both operands are true. The result is
false if either operand is false.
The result of a logical OR is false only if both operands are false. The result is
true if either operand is true.
C also consists of the unary operator ! (not) that negates the value of a logical
expression i.e., it causes true expression to become false and vice-versa. This
operator is known as logical NOT operator. Further like relational operators, a
logical expression results in zero or non-zero value depending on whether it is
false or true.
64 PROBLEM SOLVING TECHNIQUES USING C
Example 2.21
variable=variable/constant/expression;
For example :
x = 10; /*x is assigned a value 10 * /
Example 2.22
/*Program to print sum of 4 numbers*/
#include<stdio.h>
main( )
{
int a, b, c, d,sum;
printf(“\nEnter 4 numbers:”);
scanf(“%d%d%d%d”,&a,&b,&c,&d);
sum=a+b+c+d ; /*assignment statement*/
printf(“\nSum=%d”,sum);
return;
}
Output
Enter 4 numbers : 50 15 22 40
Sum=127
Where += is the abbreviated or compound operator. In the above case + = means add
5 to n. The different shorthand assignment operators are as shown in Fig. 2.13.
The priority of the above operators + =, –=, *=, /= and % = is the same as the
assignment operator.
66 PROBLEM SOLVING TECHNIQUES USING C
where assignments are done from right to left. For example, the assignment
statement.
x = y = z = 10;
means x = (y = (z = 10));
Assignment will be done from right to left i.e., First 10 is assigned to z.
Next the value of z (which is 10) is assigned to y and so on.
The final values of x, y and z will be 10.
Example 2.23
Consider the following statements :
int x, y;
:
x = 10;
y = ++x;
The behavior of post and pre–increment or decrement operators are the same when
used with a single operand. However, they behave differently when the operand is
embedded in an expression.
The value of n is first assigned to m and then it is decremented i.e., n becomes 1, but
value of m is 2.
In subscripted variables.
a[j++]=5;
is equivalent to a[j]=5;
j++;
Similarly, a[++i]=5;
is equivalent to i = i+1;
a[i] = 5;
Example 2.24
/* Program to show usage of increment and decrement operators */
#include<stdio.h>
main()
{
int x=1,y=2,z=3,p;
clrscr();
p=(x++) + (++y);
printf(“\n P=%d X=%d Y=%d”,p,x,y);
p=(++x) + (––z);
printf(“\n P=%d X=%d Z=%d”,p,x,z);
p=(++x) + (y––)– (z––);
printf(“\n P=%d X=%d Y=%d Z=%d”,p,x,y,z);
}
Output
P=4 X=2 Y=3
P=5 X=3 Z=2
P=5 X=4 Y=2 Z=1
Example 2.25
Here n > m is evaluated first giving the result ‘false’. Since the expression is false
the value of m is assigned to big. Thus big = 10. The same can be written in the form of
if else statement as follows :
if(n > m)
big = n;
else
big = m;
Example 2.26
/*Program to find largest of 2 numbers*/
#include<stdio.h>
main()
{
int n,m,big;
clrscr();
printf(“\n Enter two integer numbers :”);
scanf(“%d %d”,&n,&m);
big=(n>m)?n:m;
printf(“\n The largest of %d and %d is : %d”,n,m,big);
}
Output
Enter two integer numbers :10 70
The largest of 10 and 70 is : 70
70 PROBLEM SOLVING TECHNIQUES USING C
Example 2.27
/* Program to find whether a number is even or odd */
#include<stdio.h>
main()
{
int x;
clrscr();
printf(“\n Enter a number :”);
scanf(“%d”,&x);
(x % 2 == 0) ? printf(“\n %d is even”,x):printf(“\n %d is odd”,x);
}
Output
Enter a number :17
17 is odd
Enter a number :40
40 is even
Program 2.28
/* Program to find the highest marks of a student in 4 Exams */
#include <stdio.h>
#include <conio.h>
main()
{
int m1, m2, m3, m4, highest;
clrscr();
printf("\n Enter the marks in 4 papers :\n");
scanf("%d %d %d %d", &m1, &m2, &m3, &m4);
highest = m1 > m2 ? m1 : m2 ;
highest = highest > m3 ? highest : m3 ;
highest = highest > m4 ? highest : m4;
printf("\n Highest marks in 4 papers = %d",highest);
return;
}
Output
Enter the marks in 4 papers :
56 74 66 60
Highest marks in 4 papers = 74
OVERVIEW OF C LANGUAGE 71
Operator Description
, Comma operator
sizeof size in bytes
& address of operand UV used for po int er data type
* accessing value at that address W
. dot operator UV used for member selection
arrow operator W
Fig. 2.15 : Special Operators
(vii) It can also be used in while loops to separate more than one expression. For
example:
while(textchar=getchar( ),textchar ! = ‘\n’)
putchar(textchar);
72 PROBLEM SOLVING TECHNIQUES USING C
In this example, the end condition for input is checked first and then it waits
for input of a character. The program terminates as soon as the enter key is
pressed.
(viii) A block of code within braces can be written in one line by using the
comma operator. For example, the program segment :
{
temp=n;
n=m;
m=temp;
}
may be replace by
temp = n, n = m, m = temp;
Example 2.29
#include<stdio.h>
main()
{
int i,j;
clrscr( );
printf(“\n Odd Even”);
for(i=1 , j=2; j<=10 ; i+=2 , j+=2)
printf(“\n %d %d”,i , j);
}
Output
Odd Even
1 2
3 4
5 6
7 8
9 10
sizeof(n)
Example 2.30
/* Program to show usage of sizeof operator */
#define STRING “Usage of sizeof Operator”
#include <stdio.h>
main()
{
char a = ‘p’;
clrscr();
getch();
Output
Operator Description
(i) Bitwise operators cannot be applied to float or double. They can be applied to
integers only.
(ii) All except ~ operator are used in binary operations. Tilde (~) is a unary
operator.
(iii) Bitwise operators perform bitwise logical AND, bitwise logical OR, bitwise
exclusive OR, bitwise shift left and shift right.
(iv) Bitwise operators work on their operands bit by bit starting from the least
significant bit. The truth table for logical bitwise operations is as shown in
Fig. 2.17 True is taken to be 1 and false as zero.
Example 2.31
4 & 5 results in 4
i.e., binary value of 4 is 0100
binary value of 5 is 0101
Bitwise & operator is used to check whether a particular bit is 0 or 1. Consider the
number 21. Its bit pattern is represented by
0001 0101
To check whether the fourth bit is 0 or 1, AND operation must be done with
another operand whose value must be 24 i.e., 16, which can be represented as
00010000.
result shows that 4th bit is 1 since the resultant value is 16.
Example 2.32
/*Program to test whether a given number is even or odd using bitwise & operator */
#include<stdio.h>
main()
{
int n;
clrscr();
printf(“\n Enter a number :”);
scanf(“%d”,&n);
if(n&1) /*ANDing with LSB*/
printf(“\n Number is odd “);
else
printf(“\n Number is Even “);
return;
}
Output
Enter a number :8
Number is Even
Enter a number :9
Number is odd
76 PROBLEM SOLVING TECHNIQUES USING C
Example 2.33
Consider x = 4, y = 9
x is 0000 0100 4
y is 0000 1001 9
x|y is 0000 1101 i.e., 13
Example 2.34
Consider the values x = 4, y = 9.
x is 0000 0100 4
y is 0000 1001 9
x^y is 0000 1101 i.e., 13
Example 2.35
Consider x = 4
x is 00000100
~x is 11111011
expression>>n
where n is the number of bit positions to be shifted. However the rightmost n bits
are lost. Further the left most n bits which are vacant will be filled with zero. For example
x>>4 shifts all bits by 4 places to the right.
Example 2.36
Vacant Positions
Vacant Positions
expression<<n
where n is the number of bit positions to be shifted. The left most n bits are lost and
the rightmost n bits are vacated and filled with zeros.
Example 2.37
Vacant positions
Shift operators are used for multiplication and division by 2. For example, the
statement.
x = y << 2;
78 PROBLEM SOLVING TECHNIQUES USING C
shifts two bit to the left in y. Further the value of x is equal to y multiplied by 2 2.
Similarly, the statement
x = y >> 2;
shifts the bits in y to the right by 2. Also the value of x is equal to y divided by 22.
Example 2.38
/* Program to show usage of bitwise operations */
#include<stdio.h>
main()
{
int x,y , w=–1;
clrscr();
printf(“\n Enter the two integers:”);
scanf(“%d %d”,&x,&y); // x = 24
printf(“\n w= %d One’s Compliment= ~w = %d \n” ,w,~w);
printf(“\n x & y = %d \n” ,x & y);
printf(“\n x | y = %d \n” ,x | y);
printf(“\n x ^ y = %d \n” ,x ^ y);
printf(“\n x << 2 = %d \n” ,x<<2); // x * 2 2 = 24 4 = 96
printf(“\n x >> 2 = %d \n” ,x>>2); // x/22 = 24/4 = 6
getch();
return;
}
Output
Enter the two integers:24 9
w= –1 One’s Compliment= ~w = 0
x&y=8
x | y = 25
x ^ y = 17
x << 2 = 96
x >> 2 = 6
2.29 EXPRESSIONS
Valid expressions are a combination of operators, constants and variables.
They may also include function calls which return values. There are 6 types of expressions
which are :
Constant
Arithmetic
Relational
Logical
OVERVIEW OF C LANGUAGE 79
Pointer and
Bitwise expressions
Expressions which are a combination of the above type of expression are known as
compound expressions.
Constant Expressions contain only constant values.
Arithmetic Expressions consist of a valid combination of variables, constants and
arithmetic operators.
Relational Expressions contain a valid combination of variables, constants,
relational operators and arithmetic expressions. They generally return results of type true
or false.
Logical Expressions are a valid combinations of two or more relational
expressions using logical operators. They return either true or false.
Pointer Expressions return address values.
Bitwise Expressions are used for bitwise manipulation of data using the bitwise
operators.
2.30 STATEMENTS
In general a statement is a part of the program that can be executed.
It specifies an action.
Statements are the smallest executable unit of a program.
All statements must be terminated with a semicolon.
Block statements are blocks of code enclosed within a pair of braces { }.
C divides the statements into the following groups :
(i) Selection
(ii) Iteration
(iii) Jump
(iv) Label
(v) Expression and
(vi) Block statements
Selection statements include if ( ) and switch.
Iteration statements consist of while, do-while and for. They are also known as
looping statements.
Jump statements are break, continue, goto and return.
Label statements consist of case, default and goto labels.
Expressions statements are composed of a valid expression.
80 PROBLEM SOLVING TECHNIQUES USING C
1. ab + cd a*b + c*d
2. (a+b) (a–b) (a+b)*(a–b)
a
3. d (a/b) + d
b
2x 2 3x 1
4. (2*x*x + 3*x – 1)/10
10
b b2 4ac
5. root root=(–b+sqrt(b*b–4*a*c))/(2*a)
2a
b
6. a2 c2 a*a – b/2 + c * c
2
Example 2.39
b b2 4ac
x1
2a
given a = 1, b = 4, c = 4
The equivalent expression in C is :
x1 = (–b + sqrt (b*b – 4*a*c))/(2*a)
= ((–4) + sqrt(4*4 – 4*1*4))/(2*1) //Substitution
= (–4 + sqrt (4*4 – 4*1*4))/(2*1) //Evaluates inner most parentheses
= (–4 + sqrt (16 – 4*4))/(2*1)
= (–4 + sqrt (16 – 16))/(2*1)
= (–4 + sqrt(0))/(2*1) //Evaluates function
= (–4 + 0)/(2*1) //Outer parentheses
= –4/(2*1)
= –4/2
x1= –2
82 PROBLEM SOLVING TECHNIQUES USING C
Example 2.40
Whenever more than one set of parentheses appear next to each other (not
nested) then the order of evaluation is from left to right i.e., the left most set is
evaluated first and the right most set of parentheses is evaluated last.
Parentheses can be used whenever in doubt about the precedence of operators. It
also improves the understandability of the program.
OVERVIEW OF C LANGUAGE 83
Example 2.41
Consider the expression :
++x – y++ where x = 6, y = 2
++x – 2 [unary operators (from R to L) :
First y = 2, next y = 3 (post increment)]
7 –2 [Unary operators :
First x = 6, x = 7 (pre–increment)]
5 [Subtraction]
where a = 20, b = 1.
The order of evaluation will be as follows.
(i) Since + operator has the highest priority in the expression, addition is computed
first :
a < 10 && 21 > 15
(ii) Both the relational operators have higher priority compared to the logical operator
&&. Here the associativity of relational operators has to be considered which is left
to right. Thus :
20 <10 && 21 > 15
False && True
The above rules of conversion are applied while evaluating an arithmetic expression
on the right hand side of an assignment statement.
The following conversions can occur (Fig. 2.22) when the resultant value on the right
hand side and the variable on the left hand side are of different types.
86 PROBLEM SOLVING TECHNIQUES USING C
int = long int drops the extra higher order bits long x = 12345678;
which is wrong int y; y = x;
The value of y is 24910
can be used where x = 42.7. The resultant amount would be 42.7 + 0.5 = 43.2 and int (43.2)
gives 43. Further if x = 42.3 then resulting amount would be 42.3 + 0.5 = 42.8 = 42.
Example 2.42
/* Program to find the summation of the series
S=1+1/2+1/3+----+1/n using cast operator */
#include<stdio.h>
main()
{
float s=0;
int n,i;
clrscr();
printf("\n Enter the value of n :");
scanf("%d",&n);
for(i=1;i<=n;i++)
s=s+1/(float)i;
printf("\n Sum of series : %6.3f " , s);
}
Output
Enter the value of n :3
Sum of Series : 1.833
88 PROBLEM SOLVING TECHNIQUES USING C
To use mathematical functions shown in the above table, math.h header file must
be included.
Example 2.43
/*Program to show usage of Library functions using math.h */
#include <stdio.h>
#include <math.h>
main( )
{
int d=60;
double x , y;
clrscr();
Output
x in Degrees = 60
x in radians = 1.047197
sin(x) = 0.866025 cos(x) = 0.500001 tan(x) = 1.732047
x in radians = 1.00
asin(x) = 1.570796 acos(x) = 0.000000 atan(x) = 0.785398
sinh(x) = 1.175201 cosh(x) = 1.543081 tanh(x) = 0.761594
e raised to 2.5 = 12.182494
Natural log(3.0) = 1.098612 common log10(3.0) = 0.477121
pow(3,4) 3 raised to 4 = 81.000000
square root of 3.0 = 1.732051
fabs(–3.14) absolute float value = 3.140000
ceil(2.339) rounded upto nearest integer = 3.000000
ceil(–3.339) rounded upto nearest integer = –3.000000
floor(2.339) rounded down to nearest integer = 2.000000
floor(–3.339)rounded down to nearest integer = –4.000000
REVIEW QUESTIONS
17. What is the difference between an integer constant and a float constant.
18. How do you represent an octal number and a hexadecimal number in C ?
19. What is the difference between ‘A’ and “A” ?
20. What is a keyword ? Mention the important keywords in C.
21. What is the difference between a character constant and a string constant ?
22. What are modifiers used for ? Explain.
23. Give the purpose of Escape sequence characters.
24. How do variables and symbolic constants differ ?
25. What is an operand and an operator?
26. What is an expression?
27. What are unary operators?
28. Give examples of unary operators.
29. What are arithmetic binary operations? (2011)
30. What is the difference between unary and binary operators?
31. Which operator is used both as a binary operator and unary operator?
32. What is the numerical equivalent to true and false in “C”?
33. What is the difference between prefix and postfix increment operators?
34. What is the difference between = and = = operators? (2011)
35. Convert the following mathematical expressions into C arithmetic expression.
(a) y = |(a + b) / (c – d)|1/a
(b) x = 3
sin a a b
36. What do you mean by type casting?
37. What is associativity?
38. What is the difference between the operators / and %?
39. What is operator precedence?
40. What are the precedence levels of arithmetic operators?
41. What is an expression? What are its components?
42. Why are parentheses used within an expression?
43. How can you determine the number of bytes allocated to each data type in C?
44. Discuss the equality operators and their usage.
45. What are library functions and how are they useful?
46. What is the difference between pre-increment and post-increment operations?
47. What is the function of sizeof operator? Mention any one application of the sizeof
operator.
92 PROBLEM SOLVING TECHNIQUES USING C
16. How can you write multiple assignment and what is the order of their evaluation ?
Illustrate with an example.
17. What is the difference between ternary operator and if-else statement?
18. Discuss the function of size of operator with an example.
19. Explain the left shift and right shift operators.
20. What are coding constants ? Explain.
Programming Assignment
1. Determine which of the following are invalid identifiers. Justify your answer.
(a) $sum (b) return (c) Total marks (d) 123–45
2. Determine which of the following are invalid integer constants and why?
(a) 0.56 (b) 25,356 (c) 8*3e–12
(d) 75E+2 (e) “12345” (f) 4*5
3. Find errors if any in the following:
(a) int a; (b) float VALUE; (c) exponent alpha;
(d) char = p, q;(e) short charm; (f) long int x; counter;
(g) long float fact;
4. Find which of the following are valid character constants:
(a) ‘b’ (b) ‘*’ (c) ‘\t’ (d) ‘/n’ (e) ‘tab’
(f) ‘\\’ (g) ‘\0’ (h) ‘123’ (i) ‘\v’
5. Find which of the following are valid string constants:
(a) ‘9:30 A.M.’ (b) “AGE:” (c) “x*y = z;”
(d) “10.5E + 20” (e) “Good bye, Bangalore”
(f) “The teacher said, “Class dismissed.”
6. Write declaration for each variable:
(a) integer variables: p, q
(b) floating point variables: sum1, sum2
(c) character variables: yes, no, why
(d) long integer variable: Kounter
(e) short integer variable: flag
(f) double precision: root
(g) unsigned integer: books
7. Write variable declaration and assign the given values for the following:
(a) floating point variables: x = 4.5, y = 5.20056
(b) double precision variables: x1 = 1.5*10–20, y1 = – 4.2*10+5
(c) character precision variables: C1 = ‘A’, C2 = ‘*’
(d) integer variables: n1 = 621 (octal), m2 = fff1 (hexadecimal)
(e) long integer variables: maxi = 123456789
94 PROBLEM SOLVING TECHNIQUES USING C
L (a b) OP 1
tan 1
i) y= M ii) x= 3
MN PQ ab
10. Find the value of each arithmetic expression given three integer variables. a = 2,
b = 4, c = 6.
(a) 12 * b + 2 * (a + c) (b) b * (a % c)
(c) a * (b/c) (d) a % b + c % b (e) – 12 % b
11. Determine the value of each expression given 3 character type variables.
c1 = ‘A’, c2 = ‘1’, c3 = ‘ ‘ (use ASCII character set)
(a) c1 + c2 + c3 (b) c2 % c1
(c) ‘4’ + c2 (d) ‘2’ + ‘4’ (e) c3 + ‘#’
b b2 4ac
(c) tri-area = s( s a )( s b)( s c ) (d) x1 =
2a
(e) side = a 2 b2 2ab cos ( x )
z = 8/2/3 * 4 * 5 % 6 % 7 % 2;
printf (“\n %d”, z);
}
___________