POP-Module2 (1) Updated
POP-Module2 (1) Updated
Module – 2
2.1.Datatypes
In computer science and computer programming, a data type or simply type is an attribute of data
whichtells the compiler or interpreter how the programmer intends to use the data. Most programming languages
support common data types of real, integer and boolean.
In the C programming language, data types are declarations for memory locations or variables that determine the
characteristics of the data that may be stored and the methods (operations) of processing that are permitted
involving them. Data types in C are shown in Fig 1.1.
MEMORY FORMA
DATA TYPE (BYTES) RANGE T
SPECIFIER
short int 2 -32,768 to 32,767 %hd
Dept of CSEu/nIsSigE
ne,dRshort int 2 0 to 65,535 %hu
unsigned int 4 0 to 4,294,967,295 %u
int 4 -2,147,483,648 to %d
2,147,483,647
long int 4 -2,147,483,648 to %ld
2,147,483,647
unsigned long int 4 0 to 4,294,967,295 %lu
long long int 8 -(2^63) to (2^63)-1 %lld
unsigned long 0 to
8 %llu
long int 18,446,744,073,709,551,615
signed char 1 -128 to 127 %c
unsigned char 1 0 to 255 %c
float 4 %f
double 8 %lf
I & II-Selomnegstdeoru, bPleroblem Solving Th1r2ough Pro gramming(21PSP13/23) P a g e%1L|f54
2.1.1 C tokens
It is the basic building block of a C-Program. A C program consists of various tokens and a tokenis either
a keyword, an identifier, a constant, a variable.
Keywords – it a word which has pre-defined meaning. The following list shows the reserved wordsin C.
These reserved words may not be used as constant or variable or any other identifier names.
auto else long switch
break enum register typedef
case extern return union
RVITM do
double
int struct _Packed
2.1.2. Identifiers - A C identifier is a name used to identify a variable, function, or any other user-
defined item. An identifier starts with a letter A to Z or a to z or an underscore _ followed by zeroor more
letters, underscores, and digits (0 to 9).
C does not allow punctuation characters such as @, $, and % within identifiers. C is a case
sensitive programming language. Thus, Manpower and manpower are two different identifiers in
A. Here are some examples of acceptable identifiers:
⮚ Derived data types: Derived data types are nothing but primary data-types but a little twisted or
Dept of CSE/ISE,
grouped together like array, structure, union and pointer.
RVITM
C supports a rich set of operators. Operators are used in programs to manipulate data and
variables. Operators can be classified into a number of categories. They are:
● Arithmetic operators
● Relational operators
● Logical operators
● Assignment operators
● Increment and Decrement operators
● Conditional operators
Dept of CSE ●
●
Bit wise operators
Special operators
Arithmetic operators
C provides all the basic arithmetic operators. The operators R +,V
- ,*IaTnM
d / all work the same way as they
do in other languages. These can operate on any built-in data type allowed in C. The unary minus
operator, in effect, multiplies its single operand by -1. Therefore, a number preceded by a
minus sign changes its sign.
Operator Meaning
+ Addition or Unary plus
- Subtraction or Unary minus
* Multiplication
/ Division
% Modulo division
Integer division truncates any fractional part. The Modulo division operator produces the
remainder of an integer division. Examples or use of arithmetic operators are:
a-b a+b
a*b a/b
a%b -a*b
Here a and b are variables and are known as operands. The modulo divison operator % cannot be
used on floating point data.
Relational operators
We often compare two quantities and depending on their relation, to take certain decisions. For
Dept of CSE
Example, we may compare the age of two persons, or the price of two items, and so on. These
comparisons can be done with the help of relational operators. The value of relational expression is
either one or zero. It is one if the specified relation is true and zero if the relation is false.
For example,
10 < 20 is true
20 < 10 is false
C supports six relational operators in all.
Table 2.2: Relational Operators
<=
Less Than
-35>= 0 FALSE
10<7+5 TRUE
a+b == c+d TRUE only if the sum of values of a and b is equal to the
sum of values of c and d.
When arithmetic expressions are used on either side of a relational operator, the arithmetic
expressions will be evaluated first and then the results compared. That is, arithmetic operators havea
higher priority over relational operators.
Relational expressions are used in decision statements such as, if and while to decide the course of
action of a running program.
Logical operators
&&(AND), ||(OR), ^(EX-OR) and !(NOT) are different logical operators shown in Table 1.6.
Table 2.3: Logical Operators
Operato r pM
t eoafniC
ng
SE,
De
&& Logical AND
|| Logical OR
! Logical NOT
^ Logical XOR
RVIT
The logical operators && and || are used when we want to test more than one condition and make
decisions.
For example,
a > b && x == 10
This is true only if a > b is true and x == 10 is true. If either of them false, the expression is false.
Table 2.4 to 2.7 shows the truth tables of &&(AND), ||(OR), !(NOT) and ^(EX-OR)
respectively
. Table 2.4: Truth table for AND (&&) Table 2.5 : Truth table for OR (||)
A B A && B A B A || B
0 0 0 0 0 0
0 1 0 0 1 1
1 0 0 1 0 1
1 1 1 1 1 1
0 1 0 0 0
De /ISE0, 1 1
1 0
pt of CSE 1 0 1
1 1 0
Assignment operators
RVITM
I & II Semester, Principles of Programming using C (BPOPS103/203)
RV Institute of Technology & Management®
The form is v
=exp;
where v is a variable, exp is an expression. For example,
x=10; x=x+3; x=x+a*b;
Operator Meaning
= Assignment
In addition to the usual assignment operator ‘=’ C has a set of assignment operators called
shorthand operators.
Some of the shorthand operators are listed below:
Increment operator ++
The operator ++ adds 1 to the operand. Two types of increment operators are:
Prefix Increment operator(++op)
This first adds 1 to the operand and then the result is assigned to the variable on left.
For example,
m=5;
++m;
This statement increases the value of m by 1. that is m is 6.
Postfix Increment operator (op++)
Postfix operator first assigns the value to the variable on left and then increments the operand.
For example,
I & II Semester, Principles of Programming using C (BPOPS103/203)
RV Institute of Technology & Management®
m=5;
m++;
This statement increases the value of m by 1. That is m is 6.
While ++m and m++ mean the same thing when they form statements independently. They behave
differently when they are used in expressions on the right hand side of assignment statements.
For example,
m=5;
Y=++m;
RVITM
In this case, the value of y and m would be 6. Suppose, if we rewrite the above statements as
m=5;
y=m++;
here, the value of y would be 5 and m would be 6.
Conditional operator (? :)
This is also called as a ternary operator. The general form is:
Here, exp1 is evaluated first. If it is nonzero (true), then the expression exp2 is evaluated and
becomes the values of the expression. If exp1 is false, exp3 is evaluated and its value becomes the
values of the expression. Note that only one of the expressions either exp2 or exp3 is evaluated.
For example,
a=10;
b=34;
max=(a > b) ? a: b;
In this example, max will be assigned the value of b because the condition is false. So, exp3 (b)
is evaluated and its value is assigned to max.
Bitwise operators
These operators are used for testing the bits, or shifting them left or right. These Operators may not be
applied to float or double. Bitwise operators are shown in Table 2.7
I & II Semester, Principles of Programming using C (BPOPS103/203)
RV Institute of Technology & Management®
Meaning
& bitwise AND
bitwise OR
^ bitwise XOR
<< shift left
>> shift right
Bitwise OR
The result of bitwise OR operator is 1 if atleast one of the bits has a value of 1; otherwise it is 0.
For example,
if x=13 and y=25 then
z= x | y;
if we execute this statement,
x=0000 0000 0000 1101
y=0000 0000 0001 1001
the result would be:
z=0000 0000 001 1101
Dept of CSE/ISE,
The result of bitwise XOR operator is 1 if only one of the bits is 1; otherwise it is 0. For
example,
if x=13 and y=25 then
z= x ^y;
RVITM
if we execute this statement,
x=0000 0000 0000 1101
y=0000 0000 0001 1001
the result would be:
z=0000 0000 000 0100
The shift operators are used to move bit patterns either to the left or to the right. The shift
operators are represented by the symbols << and >>.
Left shift
op << n
x is an unsigned integer that has the value 11. Then bit pattern
of x is: 0000 1011
Dept of CSE/ISE,
x << 1 is,
0001 0110 that is 22.
This is equal to the value of x will be multiplied by 2.
Right shift
op >> n
The right shift operation shifts all the bits in the operand op to be shifted to the right by n positions. The rightmost n bits
in the original bit pattern will be lost and leftmost n bitsthatare vacated will be filled with 0s if the op is an unsigned integer. If
the variable to beshiftedis signed, then the operation is machine dependent.
For example,
x is an unsigned integer that has the value 11. Then bit pattern of x is: 0000 1011 x
>> 1 is,
0000 0101 that is 5.
This is equal to the value of x will be divided by 2.
Special Operators
sizeof operator
The sizeof is a compile time operator and when used with an operand, it returns the number of
bytes the operand occupies. The operand may be a variable, a constant or a data type qualifier.
For example,
int n;
m=sizeof(n);
Dept of CSE,
Will return 4. That is m is assigned a value 4, because int occupies 4 bytes.
Comma Operator
C has some special operators. The comma operator is one among them. This operator can be usedto
RVITM
link the related expressions together. A comma-linked list of expressions are evaluated left to right
and the value of right-most expression is the value of the combined expression.
For example, the statement
First assigns the value 2 to a, then assigns 6 to b, and finally assigns 8(i.e 2+6) to value. The comma
operator has the lowest precedence of all operators,hence the parentheses are necessary.
Some examples are given below:
In for loops: for(a=1, b=10;a<=b; a++, b++)In
while loops: while(c=getchar(), C!=’10’)
Exchanging values: t=x, x=y, y=t;
int number=34.78;
printf(“%d”,number);
Here, we are assigning the double value 34.78 to the integer variable number. In this case, the double value is
automatically converted to integer value 34.
This type of conversion is known as implicit type conversion. In C, there are two types of type conversion:
1. Implicit Conversion
2. Explicit Conversion
In implicit type conversion, the value of one type is automatically converted to the value of another type.
Example 1:
double value=4150.12;
printf(“Double value :%.21f\n”,value);
The above example has a double variable with a value 4150.12. Notice that we have assigned the double value to an
integer variable.
Here, the C compiler automatically converts the double value 4150.12 to integer value 4150.
Since the conversion is happening automatically, this type of conversion is called implicit type conversion.
Example2:
// character variable
char alphabet = 'a';
printf("Character Value: %c\n", alphabet);
The code above has created a character variable alphabet with the value 'a'. Notice that we are assigning alphabet to
an integer variable.
Here, the C compiler automatically converts the character 'a' to integer 97. This is because, in C programming,
characters are internally stored as integer values known as ASCII Values.
ASCII defines a set of characters for encoding text in computers. In ASCII code, the character 'a' has integer
value 97, that's why the character 'a' is automatically converted to integer 97.
In explicit type conversion, we manually convert values of one data type to another type.
Example1:
int number = 35;
printf("Integer Value: %d\n", number);
We have created an integer variable named number with the value 35 in the above program. Notice the code,
Example2:
We have created a variable number with the value 97 in the code above. Notice that we are converting this integer to
character.
In our earlier examples, when we converted a double type value to an integer type, the data after decimal was lost.
Example1:
Here, the data 4150.12 is converted to 4150. In this conversion, data after the decimal, .12 is lost.
This is because double is a larger data type (8 bytes) than int (4 bytes), and when we convert data from larger type
to smaller, there will be data loss.
Similarly, there is a hierarchy of data types in C programming. Based on the hierarchy, if a higher data type is
converted to lower type, data is lost, and if lower data type is converted to higher type, no data is lost.
Here,
data loss - if long double type is converted to double type
no data loss - if char is converted to int
Typecasting allows us to convert one data type into other. In C language, we use cast operator for typecasting which
is denoted by (type).
Syntax:
(type)value;
Example1:
1. int f= 9/4;
2. printf("f : %d\n", f );
output is 2.
With Type Casting:
Example1:
1. float f=(float) 9/4;
2. printf("f : %f\n", f );
output is 2.250000
if statement
switch statement
conditional operator statement (? : operator)
goto statement
Simple if statement
if... else statement
Nested if. .. else statement
Using else if statement
Simple if statement
The general form of a simple if statement is,
if(expression)
{
statement inside;
}
statement outside;
If the expression returns true, then the statement-inside will be executed, otherwise statement-
inside is skipped and only the statement-outside is executed.
Example:
#include <stdio.h>
void main( )
{
int x =15, y=13;
if (x > y )
{
printf("x is greater than y");
}
}
x is greater than y
if...else statement
The general form of a simple if...else statement is,
if(expression)
{
statement block1;
}
else
{
statement block2;
}
and statement-block2 is executed. Flow chart of if else ish shown in Fig 2.2.
Example:
#include <stdio.h>
void main( )
{
int x, y;
x = 15;
y = 18;
if (x > y )
{
printf("x is greater than y");
}
else
{
printf("y is greater than x");
}
}
y is greater than x
if( expression )
{
if( expression1 )
{
v
I & II Semester, Principles of Programming using C (BPOPS103/203)
RV Institute of Technology & Management®
statement block1;
}
else
{
statement block2;
}
}
else
{
statement block3;
}
if expression is false then statement-block3 will be executed, otherwise the execution continues
and enters inside the first if to perform the check for the next if block, where if expression 1 is true
the statement-block1 is executed otherwise statement-block2 is executed. Flow chart of nested if
else is shown in Fig 2.2.
if(a > c)
{
printf("a is the greatest");
}
else
{
printf("c is the greatest");
}
}
else
{
if(b > c)
v
{
printf("b is the greatest");
}
else
{
printf("c is the greatest");
}
}
}
else if ladder
The general form of else-if ladder is,
if(expression1)
{
statement block1;
}
else if(expression2)
{
statement block2;
}
else if(expression3 )
{
statement block3;
}
else
default statement;
The expression is tested from the top(of the ladder) downwards. As soon as a true condition is
found, the statement associated with it is executed. Flow chart of else if ladder is shown in Fig 2.3.
Example :
#include <stdio.h>
void main( )
{
int a;
printf("Enter a number...");
scanf("%d", &a);
if(a%5 == 0 && a%8 == 0)
{
printf("Divisible by both 5 and 8");
}
else if(a%8 == 0)
{
printf("Divisible by 8");
}
else if(a%5 == 0)
{
printf("Divisible by 5");
}
else
{
printf("Divisible by none");
}
}
Points to Remember
1. In if statement, a single statement can be included without enclosing it into curly braces { ... }
int a = 5;
if(a > 4)
printf("success");
No curly braces are required in the above case, but if we have more than one statement inside if
condition, then we must enclose them inside curly braces.
2. = = must be used for comparison in the expression of if condition, if you use = the expression will
always return true, because it performs assignment not comparison.
3. Other than 0(zero), all other values are considered as true.
if (27)
printf("hello");
Switch statement in C
When you want to solve multiple option type problems, for example: Menu like program, where
one value is associated with each option and you need to choose only one at a time, then, switch
statement is used.
Switch statement is a control statement that allows us to choose only one choice among the many
given choices. The expression in switch evaluates to return an integral value, which is then compared
to the values present in different cases. It executes that block of code which matches the case value.
If there is no match, then default block is executed (if present). The general formof switch
statement is,
switch(expression)
{
case 1:
block 1;
break;
case 2:
block 2;
break;
case 3:
block 3;
break;
case 4:
block 4;
break;
default:
default block;
break;
}
1. The expression (after switch keyword) must yield an integer value i.e the expression should be
an integer or a variable or an expression that evaluates to an integer.
2. The case label values must be unique.
3. The case label must end with a colon(:)
4. The next line, after the case statement, can be any valid C statement.
Points to Remember
1. We don't use those expressions to evaluate switch case, which may return floating point values
or strings or characters.
2. break statements are used to exit the switch block. It isn't necessary to use break after each
block, but if you do not use it, then all the consecutive blocks of code will get executed after the
matching block.
int i = 1;
switch(i)
{
case 1:
printf("A"); // No break
case 2:
printf("B"); // No break
case 3:
printf("C");
break;
}
The output was supposed to be only A because only the first case matches, but as there is
no break statement after that block, the next blocks are executed too, until it a break statement in
encountered or the execution reaches the end of the switch block.
3. default case is executed when none of the mentioned case matches the switch expression. The
default case can be placed anywhere in the switch case. Even if we don't include the default case,
switch statement works.
4. Nesting of switch statements are allowed, which means you can have switch statements inside
another switch block. However, nested switch statements should be avoided as it makes the program
more complex and less readable.
{
case 1:
printf("Enter 2 numbers");
scanf("%d%d", &a, &b);
c = a + b;
printf("%d", c);
break;
case 2:
printf("Enter 2 numbers");
scanf("%d%d", &a, &b);
c = a - b;
printf("%d", c);
break;
default:
printf("you have passed a wrong key");
printf("\n press any key to continue");
}
}
}
if statements can evaluate float conditions. switch statements cannot evaluate float conditions.
if statement can evaluate relational operators. switch statement cannot evaluate relational
operators i.e they are not allowed in switch statement.
You may encounter situations, when a block of code needs to be executed several numbers of times.
In general, statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on. Fig 2.4 shows the flow chart of general loop.
Programming languages provide various control structures that allow for more complicated execution
paths. A loop statement allows us to execute a statement or group of statements multiple times. Given
below is the general form of a loop statement in most of the programming languages −
for loop: Executes a sequence of statements multiple times and abbreviates the
2
code that manages the loop variable.
do...while loop: It is more like a while statement, except that it tests the
3
condition at the end of the loop body.
nested loops: You can use one or more loops inside any other while, for, or
4
do..while loop.
}
Fig 2.5 shows the flow chart of for loop.
But if the test expression is true (nonzero), codes inside the body of for loop is executed and
the update expression is updated.
4. The for loop is commonly used when the number of iterations is known.
For-loop Flowchart
#include <stdio.h>
int main()
{
int num, count, sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &num);
// for loop terminates when n is less than count
for(count = 1; count <= num; ++count)
{
sum += count;
}
printf("Sum = %d", sum);
return 0;
}
Output
Sum = 55
The value entered by the user is stored in variable num, suppose, the user entered 10.
The count is initialized to 1 and the test expression is evaluated. Since, the test expression
count <= num (1 less than or equal to 10) is true, the body of for loop is executed andthe value of
sum will equal to 1.
Then, the update statement ++count is executed and count will equal to 2. Again, the test
expression is evaluated. Since, 2 is also less than 10, the test expression is evaluated to true and the
body of for loop is executed. Now, the sum will equal 3.
This process goes on and the sum is calculated until the count reaches 11.
When the count is 11, the test expression is evaluated to 0 (false) as 11 is not less than or equal
to 10. Therefore, the loop terminates and next, the total sum is printed.
Output
Enter an integer: 10
Factorial of 10 = 3628800
#include <stdio.h>
int main()
{
int n1, n2, i, gcd;
printf("Enter two integers: ");
scanf("%d %d", &n1, &n2);
for(i=1; i <= n1 && i <= n2; ++i)
{
// Checks if i is factor of both integers
if(n1%i==0 && n2%i==0)
gcd = i;
}
printf("G.C.D of %d and %d is %d", n1, n2, gcd);
return 0;
}
In this program, two integers entered by the user are stored in variable n1 and n2.Then, for loop
is iterated until (i) is less than n1 and n2.
In each iteration, if both n1 and n2 are exactly divisible by (i), the value of (i) is assigned to gcd.
When the for loop is completed, the greatest common divisor of two numbers is stored in
variable gcd.
While loop
While loop can be addressed as an entry control loop. It is completed in 3 steps.
Variable initialization.(e.g int x = 0;)
Syntax:
variable initialization;
while(condition)
statements;
variable increment or decrement;
#include<stdio.h>
void main( )
{
int x;
x = 1;
while(x <= 10)
{
printf("%d\t", x);
/* below statement means, do x = x+1, increment x by 1*/
x++;
}
}
Program Output: 1 2 3 4 5 6 7 8 9 10
do while loop
In some situations it is necessary to execute body of the loop before testing the condition. Such
situations can be handled with the help of do-while loop. do statement evaluates the body of the
loop first and at the end, the condition is checked using while statement. It means that the body of the
loop will be executed at least once, even though the starting condition inside while is initialized to be
false. General syntax is,
do
{
.....
.....
}
while(condition)
#include<stdio.h>
void main()
{
int a =5, i=1;
do
{
printf("%d\t", a*i);
i++;
}
while(i <= 10);
}
C supports nesting of loops in C. Nesting of loops is the feature in C that allows the looping of statements
inside another loop.
Any number of loops can be defined inside another loop, i.e., there is no restriction for defining any number of
loops. The nesting level can be defined at n times. You can define any type of loop inside another loop; for example,
you can define 'while' loop inside a 'for' loop.
Outer_loop
{
Inner_loop
{
// inner loop statements.
}
// outer loop statements.
}
Outer_loop and Inner_loop are the valid loops that can be a 'for' loop, 'while' loop or 'do-while' loop.
o First, the 'i' variable is initialized to 1 and then program control passes to the i<=n.
o The program control checks whether the condition 'i<=n' is true or not.
o If the condition is true, then the program control passes to the inner loop.
o The inner loop will get executed until the condition is true.
o After the execution of the inner loop, the control moves back to the update of the outer loop, i.e., i++.
o After incrementing the value of the loop counter, the condition is checked again, i.e., i<=n.
o If the condition is true, then the inner loop will be executed again.
o This process will continue until the condition of the outer loop is true
while(condition)
{
while(condition)
{
// inner loop statements.
}
// outer loop statements.
}
Example of nested while loop
The nested do..while loop means any type of loop which is defined inside the 'do..while' loop.
do
{
do
{
// inner loop statements.
}while(condition);
// outer loop statements.
}while(condition);
int i=1;
do // outer loop
{
int j=1;
do // inner loop
{
printf("*");
j++;
}while(j<=8);
printf("\n");
i++;
}while(i<=4);
}
#include <stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float a, b, c, root1, root2, r_part, i_part, disc;
clrscr ();
printf ("Enter the 3 non-zero coefficients\n");
scanf ("%f%f%f",&a,&b,&c);
disc=(b*b)-(4*a*c);
if(disc==0)
{
printf("Roots are equal\n");
root1=-b/(2*a);
root2=root1;
printf("root1=root2=%f",root1);
}
else if(disc>0)
{
printf("Roots are real and distinct\n");
root1=(-b+sqrt(disc))/(2*a);
root2=(-b-sqrt(disc))/(2*a);
printf("root1 = %f \t root2 = %f\n",root1,root2);
}
else
{
printf("Roots are complex\n");
r_part=-b/(2*a);
i_part=(sqrt(-disc))/(2*a);
printf("root1 = %f+i%f \n root2 = %f-i%f\n",r_part,i_part,r_part,i_part);
}
getch();
}
else
coef = coef*(i-j+1)/j;
printf("%4d", coef);
}
printf("\n");
}
return 0;
}
1
11
121
1331
#include<stdio.h>
#define MAX 10
int main()
{
int n, a, bi_nom;
print ("Mx ");
for (n=0; n<=10; ++n)
printf("%d ", n);
printf("\n \n");
n=0;
do
a = 0, bi_nom = 1;
printf("%2d", n);
while(a<=n)
{
if(n==0 || a==0)
printf("%4d", bi_nom);
else
{
bi_nom=bi_nom* (n-a+1)/a;
printf("%4d", bi_nom);
}
a=a+1;
}
printf("\n");
n=n+1;
}while(n<=MAX);
printf(" ");
}
Pictorial Presentation:
Programming Examples:
Example 1
y = xn
when n is a non-negative integer, is given in Example 1
The variable y is initialized to 1 and then multiplied by x, n times using the while loop. The loop
control variable, count is initialized outside the loop and incremented inside the loop. When the
value of count becomes greater than n, the control exists the loop.
Program
main()
{
int count, n; float x, y;
printf("Enter the values of x and n : ");
scanf("%f %d", &x, &n);
y = 1.0;
count = 1; /* Initialisation */
/* LOOP BEGINs */
while ( count <= n) /* Testing */
{
y = y*x;
count++; /* Incrementing */
}
/* END OF LOOP */
printf("\nx = %f; n = %d; x to power n = %f\n",x,n,y);
}
Output
Example 2
This program contains two do.... while loops in nested form. The outer loop is controlled by the
variable row and executed 12 times. The inner loop is controlled by the variable column and is
executed 10 times, each time the outer loop is executed. That is, the inner loop is executed a total
of 120 times, each time printing a value in the table.
1 2 3 4 … 10
2 4 6 8 … 20
12 24 36 48 … 120
Program:
#define COLMAX 10
#define ROWMAX 12
main()
{
int row,column, y;
row = 1;
printf(" MULTIPLICATION TABLE \n");
printf(" \n");
column = 1;
y = row * column;
printf("%4d", y);
column = column + 1;
printf(" \n");
Output
MULTIPLICATION TABLE
1 2 3 4 … 10
2 4 6 8 … 20
12 24 36 48 … 120
Example 3
The program in Example 3 uses a for loop to print the "Powers of 2" table for the power 0 to
20, both positive and negative.
1
q = 2-n = ----
p
1 break statement
Terminates the loop or switch statement and transfers execution to the
statement immediately following the loop or switch.
2 continue statement
Causes the loop to skip the remainder of its body and immediately retest
its condition prior to reiterating.
3 goto statement
Transfers control to the labeled statement.
Break Statement
In any loop break is used to jump out of loop skipping the code below it without caring about the test condition.
It interrupts the flow of the program by breaking the loop and continues the execution of code which is outside the
loop.
The common use of break statement is in switch case where it is used to skip remaining part of the code.
In while loop
while (test_condition)
{
statement1;
if (condition )
break;
statement2;
}
In do…while loop
do
{
statement1;
if (condition)
break;
statement2;
}while (test_condition);
In for loop
Now in above structure, if test_condition is true then the statement1 will be executed and again if the condition
is true then the program will encounter break statement which will cause the flow of execution to jump out of
loop and statement2 below if statement will be skipped.
Example: C program to take input from the user until he/she enters zero.
#include <stdio.h>
int main ()
{
int a;
while (1)
{
printf("enter the number:");
scanf("%d", &a);
if ( a == 0 )
break;
}
return 0;
}
Explanation
In above program, while is an infinite loop which will be repeated forever and there is no exit from the loop.
So the program will ask for input repeatedly until the user will input 0.
When the user enters zero, the if condition will be true and the compiler will encounter the break statement
which will cause the flow of execution to jump out of the loop.
continue statement in C
Like a break statement, continue statement is also used with if condition inside the loop to alter the flow of
control.
When used in while, for or do...while loop, it skips the remaining statements in the body of that loop and
performs the next iteration of the loop.
Unlike break statement, continue statement when encountered doesn’t terminate the loop, rather interrupts a
particular iteration
In while loop
while (test_condition)
{
statement1;
if (condition )
continue;
statement2;
}
In do…while loop
do
{
statement1;
if (condition)
continue;
statement2;
}while (test_condition);
In for loop
Explanation
In above structures, if test_condition is true then the continue statement will interrupt the flow of control and
block of statement2 will be skipped, however, iteration of the loop will be continued.
#include <stdio.h>
int main ()
{
int a,sum = 0;
for (a = 0; a < 10; a++)
{
if ( a % 2 == 0 )
continue;
sum = sum + a;
}
printf("sum = %d",sum);
return 0;
}
goto statements:
The goto statement is known as jump statement in C. As the name suggests, goto is used to transfer the program
control to a predefined label. The goto statment can be used to repeat some part of the code for a particular
condition. It can also be used to break the multiple loops which can't be done by using a single break statement.
However, using goto is avoided these days since it makes the program less readable and complicated.
Syntax:
label:
//some part of the code;
goto label;
goto example
Let's see a simple example to use goto statement in C language.
#include <stdio.h>
int main()
{
int num,i=1;
printf("Enter the number whose table you want to print?");
scanf("%d",&num);
printf("%d x %d = %d\n",num,i,num*i);
i++;
if(i<=10)
goto table;
}
#include <stdio.h>
int main () {
for( ; ; ) {
return 0;
When the conditional expression is absent, it is assumed to be true. You may have an initialization
and increment expression, but C programmers more commonly use the for(;;) construct to signify
an infinite loop.
NOTE − You can terminate an infinite loop by pressing Ctrl + C keys
The for loop in C has several capabilities that are not found in other loop constructs. For
example, more than one variable can be initialized at a time in the for statement.
The statements
p = 1;
for (n=0; n<17; ++n)
can be rewritten as
Output -----------------------
2 to power n n 2 to power -n
1 0 1.000000000000
2 1 0.500000000000
4 2 0.250000000000
8 3 0.125000000000
16 4 0.062500000000
32 5 0.031250000000
64 6 0.015625000000
128 7 0.007812500000
256 8 0.003906250000
512 9 0.001953125000
1024 10 0.000976562500
2048 11 0.000488281250
4096 12 0.000244140625
8192 13 0.000122070313
16384 14 0.000061035156
32768 15 0.000030517578
65536 16 0.000015258789
131072 17 0.000007629395
262144 18 0.000003814697
524288 19 0.000001907349
1048576 20 0.000000953674
Example 4
A class of n students take an annual examination in m subjects. A program to read the marks
obtained by each student in various subjects and to compute and print the total marks obtained
by each of them is given in Example 4.
The program uses two for loops, one for controlling the number of students and the other for
controlling the number of subjects. Since both the number of students and the number ofsubjects
are requested by the program, the program may be used for a class of any size and any number of
subjects.
2.10.2 inner loop, where the marks are read and totaled for each student, and
Program:
int n, m, i, j,
scanf("%d", &marks);
total = total + marks;
}
Output
E 3 6
n Enter roll_number : 8701
t
e
r
n
u
m
b
e
r
o
f
s
t
u
d
e
n
t
s
a
n
d
s
u
b
j
e
c
t
Example 5
The program in Example 5 illustrates the use of the break statement in a C program.
The program reads a list of positive values and calculates their average. The for loop is written
to read 1000 values. However, if we want the program to calculate the average of any set of values
less than 1000, then we must enter a 'negative' number after the last value in the list, to mark the
end of input.
Program
main()
int m;
scanf("%f", &x);
if (x < 0)
break;
sum += x ;
average = sum/(float)(m-1);
printf("\n");
Output
Number of values = 6
Sum = 138.000000
Average = 23.000000
Example 6
------ = 1 + x + x2 + x3 + ........ + xn
1-x
for -1 < x < 1 with 0.01 per cent accuracy is given in Example 6. The goto statement is used
to exit the loop on achieving the desired accuracy.
We have used the for statement to perform the repeated addition of each of the terms in the series.
Since it is an infinite series, the evaluation of the function is terminated when the term x n reaches
the desired accuracy. The value of n that decides the number of loop operations is not known and
therefore we have decided arbitrarily a value of 100, which may or may not result in the desired
level of accuracy.
Program
main()
int n;
sum = 0 ;
sum += term ;
goto end;
output:
Output
Example 7
The program evaluates the square root of a series of numbers and prints the results. The
process stops when the number 9999 is typed in.
In case, the series contains any negative numbers, the process of evaluation of square root should
be bypassed for such numbers because the square root of a negative number is not defined. The
continue statement is used to achieve this. The program also prints a message saying that the
The final output includes the number of positive values evaluated and the number of negative
items encountered.
Program:
#include <math.h>
main()
{
int count, negative;
double number, sqroot;
printf("Enter 9999 to STOP\n");
count = 0 ;negative = 0 ;
while (count <= 100)
{
printf("Enter a number : ");
scanf("%lf", &number);
if (number == 9999)
break; /* EXIT FROM THE LOOP */
if (number < 0)
{
printf("Number is negative\n\n"); negative++ ;
continue; /* SKIP REST OF THE LOOP */
}
sqroot = sqrt(number);
printf("Number = %lf\n Square root = %lf\n\n", number, sqroot);
count++ ;
}
printf("Number of items done = %d\n", count);
Output
END OF MODULE 2