0% found this document useful (0 votes)
6 views

C UNIT2

Uploaded by

manasa rai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

C UNIT2

Uploaded by

manasa rai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

UNIT II

Operators and Expressions


Operators are the symbols that are used in programs to manipulate data
and variables. There are different categories of operators:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators
1. Arithmetic Operators:
C Supports the following arithmetic operators:
Operator Meaning Example
1. + Addition or unary plus Sum=num1 + num2
2. Subtraction or unary minus Amount= total – discount;
3. Multiplication Product = num1 * num2;
4. / Division Average=total/5;
5. % Modulo division Remainder=15 % 4;
When both the operands are integers, the expression is called as
integerexpression and the operation is called integer arithmetic.
Integer arithmetic always yields an integer output.
Integer division truncates any fractional part of the result.
Example 5:
#include<stdio.h>
main()
{
int a=9, result;
result=a/2;
printf(“%d”,result);
}
Output: 4
• An arithmetic operation involving only real operands is called real
arithmetic. The operator% cannot be used with real operators.
• When one of the operands is real and the other is integer, the expression is
called a mixed mode arithmetic expression.If either operand is of the real type,
then only the real operation is performed and the result is always a real number.
Example: 15/10.0 = 1.5 where as 15/10 = 1
2. Relational Operators:
Relational operators are used to compare two quantities. An expression
containing relational operator is called relational expression. The value of
a relational expression is either true or false. The value of relational
expression is 1 if the specified relation is true and 0 if the relation is false.
Operator Meaning Example
If x=5, y=10, z=20 then
< Less than x<y evaluates to True
> Greater than z>x evaluates to True
<= Less than or equal to z<=x+y evaluates to False
>= Greater than or equal to x+y>=z evaluates to False
== Equal to x==y evaluates to False
!= Not equal to x!=y evaluates to True
3. Logical Operators:
An expression which combines two or more relational expressions, is
termed as a logical expression or a compound relational expression. C has
three logical operators.
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
Logical AND will evaluate to true only if both the operands are true.
Similarly Logical OR will evaluate to true if either operand or both
operands are true. Logical NOT return true if the operand is false.

Examples: Suppose if x=2, y=3, z=4 and k=0 then


a. x>y && z>y evaluates to 0 (false) because x>y is false.
b. y>x && z>x evaluates true because both the operands are true.
c. x>y || z>y evaluates to true because z>y is true.
d. x>y || y>z evaluates to false because both the conditions are false.
e. !x=0 (false)
f. !k=1 (true)
4. Assignment Operators:
Assignment operators are used to assign result of an expression to a
variable.
Example: x=x+y+1;
C supports the following shorthand assignment operators
Operator Example
= x=y;
+= x+=y; => x=x+y
-= x-=y; => x=x-y
*= x*=y; => x = x*y
/= x/=y; => x=x/y
%= x%=y; => x=x%y
The use of shorthand assignment operators has three advantages:
1. What appears on the left-hand side need not be repeated and therefore
it becomes easier to write.
2. The statement is more concise and easier to read.
3. The statement is more efficient.

5. Increment and Decrement Operators:


The increment operator adds 1 to the operand and the decrement
operator subtracts 1 from the operand. Both are unary operators.
Operator Meaning
++ Increment
-- Decrement
There are two types increment and decrement operators—prefix and
postfix.
• A postfix ++ (or --) is used, the expression is evaluated first using the
Original value of the variable and then the variable is incremented (or
Decremented) by 1.

• When prefix ++ (or --) is used, the variable is incremented (or


decremented) first and then the expression is evaluated using the new
value of the variable.
Operation of prefix increment is as below:
k=15.
Num=++k;
Here, the value of k will be incremented first and then assigned to Num.
Thus, after the execution of the above statement, both k and Num will
contain the value 16.
Operation of postfix increment is as below:
k=15.
Num=k++;
Here, the value of k will assigned to Num first and then incremented.
Thus, after the execution of the above statement, Num=15 and k will
contain the value 16.
Operation of prefix decrement is as below:
k=15.
Num=--k;
Here, the value of k will be decremented first and then assigned to Num.
Thus, after the execution of the above statement, both k and Num will
contain the value 14.
Operation of postfix decrement is as below:
k=15.
Num=k--;
Here, the value of k will assigned to Num first and then decremented.
Thus, after the execution of the above statement, Num=15 and k will
contain the value 14.

Program to illustrate pre increment and pre decrement


operator
#include<stdio.h>
void main()
{
int x = 12, y = 1;
printf("Initial value of x = %d\n", x);
printf("Initial value of y = %d\n\n", y);
y = ++x;
printf("After incrementing by 1: x = %d\n", x);
printf("y = %d\n\n", y);
y = --x;
printf("After decrementing by 1: x = %d\n", x);
printf("y = %d\n\n", y);
}
Output:
After incrementing by 1: x=13
y=13
After decrementing by 1: x=12
y=12
Program to illustrate post increment and post decrement
operator
#include<stdio.h>
void main()
{
int x = 12, y = 1;
printf("Initial value of x = %d\n", x);
printf("Initial value of y = %d\n\n", y);
y = x++;
printf("After incrementing by 1: x = %d\n", x);
printf("y = %d\n\n", y);
y = x--;
printf("After decrementing by 1: x = %d\n", x);
printf("y = %d\n\n", y);
}
Output:
Initial value of x = 12
Initial value of y = 1
After incrementing by 1: x = 13
y = 12
After decrementing by 1: x = 12
y = 13
6. Conditional Operators:
Conditional operator is also called ternary operator because it uses three
expressions. Ternary operator acts like a shorthand version of if…else
construct.
Syntax: Expression1 ?Expression2 : Expression3;
The general usage is
Variable = Expression1? Expression2: Expression3;
Here Expression1 is evaluated first. If it is true (non-zero), Expression2 is
evaluated and the result is assigned to the variable. If Expression1 is
false,Expression3 is evaluated and its result is assigned to the variable.
Example:
m=5;
n=10;
big=(m>n)? m : n;
In this case, big will be assigned value 10. This is because, m>n is false,
hence the value of n is assigned to big.
7. Bitwise Operators:
Bitwise operator are used for manipulation of data at bit level. These
operators may not be applied to float or double. The various bitwise
operators available in C are listed below.
& - Bitwise AND
| - Bitwise OR
^ - Bitwise XOR Binary operators
<< Left shift
>> Right shift
~ Complement unary operator
Bitwise AND (&)
The output of bitwise AND is 1 if the corresponding bits of two operands is
1.
If either bit of an operand is 0, the result of corresponding bit is evaluated
to 0.
Let us consider 2 integer variables,
x = 13 = 0000 0000 0000 1101
y = 25 = 0000 0000 0001 1001
If we execute the statement z = x & y, the result would be
z = 9 = 0000 0000 0000 1001
Bitwise OR (|)
The output of bitwise OR is 1 if at least one corresponding bit of two
operandsis 1. In C Programming, bitwise OR operator is denoted by |.
Let us consider 2 integer variables,
x = 13 = 0000 0000 0000 1101
y = 25 = 0000 0000 0001 1001
z = x|y = 29 = 0000 0000 0001 1101
Bitwise XOR (^)
The result of bitwise XOR operator is 1 if the corresponding bits of two
operands are different. It is denoted by ^.
Let us consider 2 integer variables,
x = 13 = 0000 0000 0000 1101
y = 25 = 0000 0000 0001 1001
z = x^y = 20 = 0000 0000 0001 0100
Right Shift Operator >>
This operator shifts each bit of the first operand to the right. The number
ofplaces the bits are shifted depends on the second operand. The bit
positions that have been vacated by the right shift operator are filled with
0.
Example:
x is an unsigned integer with bit pattern
x=0100 1001 1100 1011.
The statement x>>3 yields
x = 0000 1001 0011 1001
suppose y =5 =0000 0000 0000 0101
y>>1 yields 2 =0000 0000 0000 0010
Left Shift Operator <<
This operator shifts each bit of the first operand to the left. The number of
places the bits are shifted depends on the second operand. The bit
positions that have been vacated by the left shift operator are filled with
0.
Example:
let x = 0100 1001 1100 1011
x <<3 yields 0100 1110 0101 1000
Suppose y =5 =(0101)
y<<1 yields 10=(1010)
Complement Operator (~)
This is an unary operator which finds 1’s complement of the operand. i.e.,
it inverts all the 1’s to 0’s and vice versa.
Example: x = 1001 0110 1100 1011
~x = 0110 1001 0011 0100
Program to illustrate bitwise operators
#include <stdio.h>
void main()
{
int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
int c = 0;
c = a & b; /* 12 = 0000 1100 */
printf("Line 1 - Value of c is %d\n", c );
c = a | b; /* 61 = 0011 1101 */
printf("Line 2 - Value of c is %d\n", c );
c = a ^ b; /* 49 = 0011 0001 */
printf("Line 3 - Value of c is %d\n", c );
c = ~a; /*-61 = 1100 0011 */
printf("Line 4 - Value of c is %d\n", c );
c = a << 2; /* 240 = 1111 0000 */
printf("Line 5 - Value of c is %d\n", c );
c = a >> 2; /* 15 = 0000 1111 */
printf("Line 6 - Value of c is %d\n", c );
}
Output:
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15
Program to illustrate bitwise operators
#include <stdio.h>
void main()
{
int a = 5, b = 9;
clrscr();
printf("a = %d, b = %d\n", a, b);
printf("a&b = %d\n", a & b);
printf("a|b = %d\n", a | b);
printf("a^b = %d\n", a ^ b);
printf("~a = %d\n", a = ~a);
printf("b<<1 = %d\n", b << 1);
printf("b>>1 = %d\n", b >> 1);
}
Output:
a = 5, b = 9
a&b = 1
a|b = 13
a^b = 12
~a = 250
b<<1 = 18
b>>1 = 4
8. Special Operators:
C supports some special operators such as comma operator, sizeof
operator,pointer operators (& and *) and member selection operators (.
and ->).
1. Comma operator:
A comma operator can be used to link the related expressions together. A
list containing comma is evaluated from left to right and value of right
most expression is value of combined expression.
Example1: The statement v = (x = 10,y = 20, x+y);
First assigns value 10 to x, then assigns 20 to y, finally calculates x+y
(=30) and assigns to variable v.
2. sizeof() operator:
This operator returns the number of bytes necessary to store a variable
which is specified as its operand. The operand may be a variable, constant
or a data type qualifier. It is also used to allocate memory space
dynamically to variables during execution of a program.
Variable declaration Expression Value returned in bytes
int a; sizeof(a); 2
long b; sizeof(b); 4
float c; sizeof(c); 4
double z; sizeof(z); 8
charch; sizeof(ch); 1
Arithmetic Expressions
An arithmetic expression is a combination of variables, constants and
operators arranged as per the syntax of the language. C can handle any
complex mathematical expressions. Some of the examples of C
expressions are shown below:
Algebraic Expressions C expression
a×b− c a *b − c
(m + n)(x + y) (m + n)*(x + y)
(ab/c) a*b/c
3x2+2x+1 3* x* x + 2* x +1
Precedence of Arithmetic Operators
An arithmetic expression without parentheses will be evaluated from left
to right using the rule of precedence of operators. There are two distinct
priority levels of arithmetic operators in C:
High priority * / %
Low priority + -
The basic evaluation procedure includes 'two' left-to-right passes through
the expression. During the first pass, the high priority operators (if any)
are applied as they are encountered. During second pass, the low priority
operators (if any) are applied as they are encountered.
Example 6:
void main ( )
{
float a, b, c, x, y, z;
a =9;
b =12;
c =3;
x = a – b / 3 +c * 2 – 1;
y = a – b / (3 +c) * (2 – 1);
z = a – (b / (3 +c) * 2) – 1;
printf (“x = %f\n”, x);
printf (“y = %f\n”, y);
printf (“z = %f\n”, z);
}
Consider the statement,
x = a – b / 3 +c * 2 – 1
When a = 9, b = 12, and c= 3, the statement becomes,
x = 9 – 12 / 3 + 3 * 2 – 1 and is evaluated as follows
First pass
Step1: x = 9 – 4 + 3 * 2 – 1
Step2: x = 9 – 4 + 6 – 1
Second pass
Step3: x = 5 + 6 – 1
Step4: x = 11 – 1
Step5: x = 10
Output
x = 10.000000
y = 7.000000
z = 4.000000
The order of evaluation can be changed by introducing parentheses into
an expression.
Consider the same expression with parentheses as shown below:
9 – 12 / (3+3) * (2-1)
Whenever parentheses are used, the expressions within parentheses
assume highest priority. If two or more sets of parentheses appear one
after another as shown above, the expression contained in the leftmost
set is evaluated first and the right-most in the last. Given below are the
new steps.
First pass
Step1: 9 – 12 / 6 * (2-1)
Step2: 9 – 12 / 6 *1
Second pass
Step3: 9 – 2 * 1
Step4: 9 – 2
Third pass
Step5: 7
This time, the procedure consists of three left-to-right passes. However,
the number of evaluation steps remains the same i.e.5 (i.e equal to the
number of arithmetic operators).
Parentheses may be nested, and in such cases, evaluation of the
expression will proceed outward from the innermost set of parentheses.
Just make sure that every opening parenthesis has a matching closing
parenthesis.
For example
9 - (12 / (3+3) * 2) - 1 = 4
whereas
9 - ( (12 / 3) + 3 * 2) - 1 = -2
While parentheses allow us to change the order of priority, we may also
use them to improve understand ability of the program. When in doubt,
we can always add an extra pair just to make sure that the priority
assumed is the one we require.
Type Conversions in Expressions
Implicit Type Conversion
This conversion is done by the compiler. When more than one data type of
variables is used in an expression, the compiler converts data types to
avoid loss of data. This automatic conversion is known as implicit type
conversion.
If the operands are of different types, the 'lower' type is automatically
converted to the 'higher' type before the operation proceeds.
Given below is the sequence of rules that are applied while evaluating
expressions.
Operands Conversion Result
float , double Converts float to double double

float, int Converts int to float float

char or short, int Both are converted to int int

int , long Converts int to long long

unsigned, int Converts int to unsigned unsigned


Note that some versions of C automatically convert all floating-point
operands to double precision.
The final result of an expression is converted to the type of the variable on
the left of the assignment sign before assigning the value to it. However,
the following changes are introduced during the, final assignment.
1. float to int causes truncation of the fractional part.
2. double to float causes rounding of digits.
3. long to int causes dropping of the excess higher order bits.
Explicit Conversion
This conversion is done by user. This is also known as typecasting. Data
type is converted into another data type forcefully by the user.
Syntax: (datatype) expression;
Where data type is any allowed data type like int, char, float or double
and the expression includes constants, variables or expressions.
Type casting is a unary operator. It does not change the value of the
Operand permanently. The operand acquires the type within the
parentheses only for the current calculation. The explicit conversion of an
operand to a specific type is called type casting.
Example: int sum, count;
float average;
average=(float)sum/count;
Here, the variable sum is explicitly converted into float before the division.
Operator Precedence and Associativity
While evaluating expressions involving more than one operator, a
problem arises as to which operator needs to be applied first and which
one needs to be applied later. Such a problem can be solved by
associating the precedence with each operator. The operator with highest
precedence is evaluated first and the next lower precedence operator
later. Within the same hierarchy, operators of the same precedence

Operator Description Associativity


()
[]
. ->
++ --
Function call
Array subscript
Member access operator
Postfix increment or decrement operator
L to R
++ --
+-
!~
(type)
*
&
sizeof
Prefix Increment or decrement operator
Unary plus/minus
Logical negation, Bitwise complement
cast
Deference
Address
Size in bytes
R to L
*/ % Multiplication, Division , modulus L to R
+ - Addition ,Subtractin L to R
Different Mathematical Functions
Mathematical functions that are part of C standard library are contained in
a header file math.h. In order to use mathematical functions we must
write the statement #include<math.h>.
Function Description Example
sqrt(x) square root of x sqrt(4.0) is 2.0
sqrt(10.0) is 3.162278
exp(x) exponential (e ) exp(1.0) is 2.718282
x

exp(4.0) is 54.598150
abs(x) Absolute value of a number
abs(5)=5
abs(-8)=8
log(x) natural logarithm of x (base e) log(2.0) is 0.693147
log(4.0) is 1.386294
log10(x) logarithm of x (base 10) log10(10.0) is 1.0
log10(100.0) is 2.0
fabs(x) absolute value of x fabs(2.0) is 2.0
fabs(-2.0) is 2.0
ceil(x) rounds x to smallest integer not less
than x
ceil(9.2) is 10.0
ceil(-9.2) is -9.0
floor(x) rounds x to largest integer not greater
than x
floor(9.2) is 9.0
floor(-9.2) is -10.0
pow(x,y) x raised to power y (x ) pow(2,2) is 4.0
y

fmod(x) remainder of x/y as floating-point


number
fmod(13.657, 2.333) is
1.992
sin(x) sine of x (x in radian) sin(0.0) is 0.0
cos(x) cosine of x (x in radian) cos(0.0) is 1.0
tan(x) tangent of x (x in radian) tan(0.0) is 0.0
Example to illustrate mathematical funtions
#include<stdio.h>
#include <math.h>
void main()
{
printf("\n%f",ceil(3.6));
printf("\n%f",ceil(3.3));
printf("\n%f",floor(3.6));
printf("\n%f",floor(3.2));
printf("\n%f",sqrt(16));
printf("\n%f",sqrt(7));
printf("\n%f",pow(2,4));
printf("\n%f",pow(3,3));
printf("\n%d",abs(-12));
}
Output:
4.000000
4.000000
3.000000
3.000000
4.000000
2.645751
16.000000
27.000000
12

Decision Making and Branching


C supports decision making (control) statements such as
1. if statement
2. switch statement
3. conditional operator
4. goto statement
Flow of control is normally sequential. That is, when one statement is
finished executing, control passes to the next statement in the program.

Control Statement: A statement used to alter the sequential flow of


a
program. C provides two types of control statements:
1. Selection 2. Iteration (loop)
Selection: Using selection statements can be executed conditionally. That
is, it executes a set of statements based on a condition.
Iteration: Using iteration, a set of statements to be performed repeatedly
until a certain condition is fulfilled. The iteration statements are also
called as loops or looping statements.
Selection statements
Selection Statements: The selection statements allow to choose the set of
instructions for execution depending upon an expression’s truth value.
Different types of conditional control structures available in 'C' are
1. if - statement
2. if else statement
3. else –if ladder
4. Nested if statement
5. switch statement
Simple if() Statement
The general form of simple if ( ) statement is
if (test expression)
{
Statement block;
}
statement – x;
Flowchart:
The 'statement-block' may be a single statement or a group of
statements. If the test expression is true, the statement- block will be
executed; otherwise the statement - block will be skipped and the control
will jump to the statement-x. If the condition is true then both the
statement - block and the statement- x are executed in sequence.
Example: C program to find the larger of two numbers.
#include <stdio.h>
main()
{
inta,b,big;
printf(" Enter two numbers\n");
scanf("%d %d", &a,&b);
big=a;
if(big<b)
big=b;
printf(" Largest of %d and %d is %d”,a,b,big);
}
If-Else Statement
The if-else statement is used to express decisions. Formally, the syntax is
if (test expression)
{
true-block statements;
}
else
{
false-block statement;
}
statement-x;
If the test expression is true, then the true-block statements i.e.,
statements within if block are executed and the control will be transferred
to statement-x, which is outside of if -else block otherwise the false-block
statements i,e. within else block are executed. In either case, only one
block either statements in true block or statements in false-block will be
executed but not both.
Example:
/* program to check if the given two numbers are equal or not */
#include <stdio.h>
main
{
int num1 , num2;
printf(" Enter the values for Num1 and Num2\n");
scanf("%d %d", &Num1,&Num2);
if(num1 = = num2)
printf("Entered numbers are equal\n");
else
printf("Entered numbers are not equal\n");
}
If – Else if - Else Statement
When multiple decisions are involved, we can make use of if - elseif – else
statements. Its general form is given below:
if( test expression -1)
{
statement block -1;
}
else if (test expression-2)
{
statement block-2;
}
else if (test expression-n)
{
statement block-n;
}
else
{
statement block;
}
statement-x;
The statements are evaluated from the top to downwards. As soon as a
true test
expression is found, the statement block associated with that test
expression will be executed and the control will be transferred to the
statement -x, which is an immediate statement outside if -else if -else
construct. If all the n-conditions become false, then the final else
containing default- statement will be executed.
Example:
#include <stdio.h>
void main()
{
int marks;
printf(" Enter Marks \n”);
scanf("%d “,&marks);
if((marks<=100) && (marks >=70)) printf(“Distinction);
else
if(marks >=60) printf(“ First Class”);
else
if(marks >=50) printf(“Second Class”);
else
if (marks >=40) printf (“Pass Class \n”);
elseprintf(“Fails”);
}
Nesting If - Else Statements
Nested if- else statements are useful when there are multiple conditions
and different statements are to be executed for each condition,
if (test expression 1)
{
if (test expression 2)
{
statement block-1;
}
else
{
statement block-2;
}
}
else if (test expression 3)
{
statement block-3;
}
else
{
statement block-4;
}
statement-x;

Example /* program to find the largest among three numbers*/


#include <stdio.h>
void main()
{
inta,b,c;
printf(" Enter the values for A,B,C\n”');
scanf("%d %d %d", &a,&b,&c);
if( a > b )
{
if ( a > c)
printf(" A is the largest\n");
else
printf("C is the largest\n");
}
else
{
if ( b> c)
printf(" B is the largest\n");
else
printf("C is the largest\n");
}
}
THE switch STATEMENT
The switch statement is useful where control flow within a program must
be directed to one of several possible execution paths. if - elses may be
used in this sort of situation. But if - elses become cumbersome when the
number of alternatives exceeds three or four then the switch statement is
appropriate.
In the switch statement, a discrete variable or expression is enclosed in
parentheses following the keyword switch, and the cases each governed
by one or more distinct values of the switch variable are listed in a set of
curly braces as below:
switch (expression)
{
case value_1 : Statements;
break;
case value_2 : Statements;
break;
case value_3 : Statements;
break;
……..
………
casevalue_n : Statements;
break;
default : Statements;
}
When the switch is entered, depending upon the value of expression, the
corresponding set of statements (following the keyword case) are
executed. But ifthe switch variable has a value, different from those listed
with any of the cases, the statements corresponding to the keyword
default are executed. The default case is optional. If it does not occur in
the switch statement, and if the value obtained by the switch variable
does not correspond to any listed in the cases, the statement is skipped in
its entirety and control goes to the statement - x.
The break statement, the last statement of every case including the
default,is necessary: if it were absent, control would fall through to
execute the next case.
Example: Program to accept day number and display corresponding week
day.
#include <stdio.h>
void main()
{
int dayno;
printf(" Enter Daynumber \n”);
scanf("%d “,&dayno);
switch(dayno)
{
case 1: printf(“Sunday”);
break;

case 2: printf(“Monday”);
break;
case 3: printf(“Tues day”);
break;
case 4: printf(“Wednesday”);
break;
case 5: printf(“Thursday”);
break;
case 6: printf(“Fri day”);
break;
case 7: printf(“Saturday”);
break;
default: printf(“ Invalid Day number”);
}
}
The (Ternary) (?: ) Operator
The ternary operator has three operands, the first of which is Boolean
expression,and the second and third are expressions that compute to a
value:

( Expression1) ? Expression2: Expression3


The three expressions are separated by a question mark and a colon as
indicated.
First expression1 is evaluated. If Expression1 is true then it returns the
value of expression2, else it returns the value of expression3.
Value = First _expression? Second _expression: Third _expression;
equivalent to: if (First expression)
Value = Second_expression;
else
Value = Third _expression;
Example: Program display maximum of two numbers using ternary
operators
#include <stdio.h>
void main()
{
int a,b;
printf(“Enter two numbers \n”);
scanf(“%d %d”, &a,&b);
a>=b ?printf(“A is big”) : printf(“B is big”);
}
33
The goto statement
C supports goto statement to branch unconditionally from one point to
another in program. The goto require a label in order to identify the place
where the branch is to be made. A label is any valid variable name , and it
must be followed by colon. Label is placed immediately before the
statement where the control is to be transferred. The general form of goto
and label statements are shown below.
The label can be anywhere in program either before or after goto label;
statement.
#include<stdio.h>
void main()
{ int n,i=1;
printf(“Enter a number”);
scanf(“%d”,&n);
LOOP :printf(“%d \t”,i++);
if(i<=n) goto LOOP;
}

Looping
Loops in 'C' cause a set of statements in a program to be executed
repeatedly whilean expression is true(Repeated execution of set of
statements in a program is called looping). When the expression becomes
false, the loop terminates and the control passes to the statement
following the loop. A loop in a program therefore consists of two
segments, one known as the body of the loop and the other known as the
control statement. The control statement tests certain conditions and then
directs the repeated execution of the statements contained in the body of
the loop. There are three kinds of loops in 'C'
i) while
ii) do - while
iii) for
while statement
This is called “pre-tested” looping structure. For this statement, two
different things must be specified, the statements to be repeated and the
terminating condition. In this structure, the checking of condition is done
at the beginning. The condition must be satisfied before the execution of
the statements. The set of statements in the block is executed again and
again until the test condition is true.
If the test condition becomes false, the control is transferred out of the
block.
Syntax: while(test condition)
{
statements;

}
The execution of this statement works as follows:
1. The test condition if first evaluated.
2. If the test condition is false, while statement is terminated and the
control goes out of the structure.
3. If test condition is true, then the statements in the structure will be
executed and the control returns to the test condition.

Example: Program to display first 10 natural numbers.


#include<stdio.h>
void main()
{ inti=0;
while(i<=10)
{ printf(“%d”, i);
i++;
}
}

THE do - while() Loop


In the while loop test condition is evaluated before executing any of the
statements within the loop. Therefore, the body of the loop may not be
executed at all if the condition is not satisfied at the very beginning of the
loop where as in do -while loop construct, test condition is evaluated after
the execution of the statements in its construct. This loop is called “post-
tested” loop.
The general format of do - while loop construct is
do
{ body of the loop
} while (test expression);
The execution of this statement works as follows:
1. The set of statements in the block is first executed once.
2. The test condition is then evaluated.
3. The value of the test condition is false, then the do… while statement is
terminated and the control goes out of the structure.
4. If the value of the test condition is tru, then control goes back to the
beginning of the structure and the statements in the structure are
executed again.
Example: Program to display first 10 natural numbers.
#include<stdio.h>
void main()
{ inti=0;
do
{
printf(“%d”, i);
i++;
} while (i<=10);
}

for statement
for statement is also called the fixed execution looping structure. This
structure is used when we know exactly how many times a particular set
of statements is to be repeated.
Syntax: for(Expression1; Expression 2; Expression 3)
{
statements;
}
Where
1. Expression 1 represents the initialization expression
2. Expression 2 represents the final condition
3. Expression 3 represents the increment or decrement expression.
The execution of for loop is as follows:
1. Expression 1 is evaluated and the counter variable is assigned initial
value.
2. Expression 2 is then executed, i.e, the value of the counter variable is
checked to see whether it has exceeded the final value, if not the
statements in the structure are executed once.
3. Control is sent back to the beginning of the structure and Expression 3
is evaluated, i.e., the value of the counter variable is either increased or
decreased depending on the statement used.
4. Step 2 is repeated again and again until the counter variable exceeds
the final value.
Example: Program to display the numbers from 0 to 10 */
#include <stdio.h>
37
void main( )
{ inti;
for (i=0;i <=10;i++)
printf ("%d\n",i);
}
Nested Loops
If one looping statement is enclosed in another looping statement, then
such a sequence of statements is called as nested loops. Whenever
nested loops are used,the inner loop must be completely enclosed by the
outer loop.
Example:
for(row=1;row<=4;row++)
{
for(col=1;col<=row;col++)
printf(“ * ”);
printf(“\n”);
}
OUTPUT: *
**
***
****
Infinite Loops
If we do not use any expressions in a for statement, then the loop will run
for an infinite amount of time. The loops which do not terminate are called
as infinite loops.
Example:
for(; ;)
printf(“C Programming ”);
break Statement
The break statement is used to terminate loops. It can be used within a
while loop do while loop or for loop. When a break is encountered within a
loop, control automatically passes to the first statement after the loop.
Example:
void main()
{
int i;
for(i=0;i<=10;i++)
{
if(i==5)
break;
printf(“%d ”,i);}

}
}
Output will be 0 1 2 3 4
continue Statement
When a continue is encountered inside any loop, control automatically
passes to the beginning of the loop, by skipping rest of the looping
statements.
Example:
void main()
{ int i;
for(i=0;i<=10;i++)
{
if(i==5 || i==7)
continue;
printf(“%d ”,i);
}
}
Output will be 0 1 2 3 4 6 8 9 10
exit() Statement
• exit() is a standard library function that is used to immediately
terminate the program.
• When exit() is encountered in the program, the program is immediately
terminated and the control is transferred back to the operating system.
• The general form of an exit() function is,exit(int return_code);
where return_code is optional.
• Generally zero is used as return_code to indicate normal program
termination.
• Other nonzero value for return_code indicates the occurrence of an error
within the programs.
• The use of exit() function requires the inclusion of the header file
<stdlib.h>
*******************END OF UNIT II *******************

You might also like