C language Unit-2 Notes
C language Unit-2 Notes
, II Semester
Unit – II
Syllabus
Introduction to C: Introduction – Structure of C Program – Writing the first C
Program –File used in C Program – Compiling and Executing C Programs – Using
Comments –Keywords – Identifiers – Basic Data Types in C – Variables – Constants –
I/O Statements in C- Operators in C- Programming Examples.
Decision Control and Looping Statements: Introduction to Decision Control
Statements– Conditional Branching Statements – Iterative Statements – Nested Loops
– Break and Continue Statement – Go to Statement
Introduction to C:
C is a general-purpose programming language that is extremely popular, simple and flexible. It is machine-
independent, structured programming language which is used extensively in various applications.
C was the basic language to write everything from operating systems (Windows and many others) to
complex programs like the Oracle database, Python interpreter and more.
C was developed in the year 1972 in AT-T bell laboratory in Cambridge University in USA It was invented
by “Dennis Ritchie”. It is an out growing of two early language called BCPL (basic combined programming
language) and B which were developed at bell laboratory. C is a general-purpose structured programming
language that is powerful, efficient and compact.
#include<stdio.h>: With this line of code we include a file called stdio.h. (Standard Input/Output header
file). commands for input or output which we can use in our program. it has commands for input like
reading from the keyboard and output commands like printing things on the screen.
main():Every program must have a main(). It is the starting point of every program.
{}: The two curly brackets (one in the beginning and one at the end) are used to group all commands
together. In this case all the commands between the two curly brackets belong to main(). The curly brackets
are often used in the C language to group commands together.
printf(“Hello World\n”); : The printf is used for printing things on the screen, The words Hello World are
inside inverted cotations, because they are what is called a string. (A single letter is called a character and a
series of characters is called a string). Strings must always be put between inverted commas. The \n is called
an escape sequence represents a newline character. If there is no \n then a next printf command will print
the string on the same line.
File Used in C Program
Source code file: This file includes the source code of the program. The extension for these kinds of files
are .c. It defines the main and many more functions written in C.
Header files: They have the extension .h. they contain the C function declarations and macro definitions
that are shared between various source files.
Executable file: This file is generated by the linker. Various object files are linked by the linker for
producing a binary file which will be executed directly. They have an .exe extension.
[The high-level language is first translated into the target computer’s machine language by the compiler.
The input to the compiler is the source file containing the text of a high-level language.
If the program is syntactically correct, the compiler saves in an object file, the machine language
instructions that carry out the program’s purpose. The object file format is binary. If the source file has
errors, the compiler lists these errors but does not create an object file. The user must correct the errors and
recompile the program
Linker program combines the chunks of code called functions that resides in other object files with the
current object file creating a complete machine language program that is ready to run. We call this as
executable file. The file .exe is just stored on disk.
To run this .exe file LOADER must copy all its instructions into memory and direct the CPU to begin
execution with first instruction.]
Compilation of C program:
Choose compile menu → Compile (or) shortcut for compilation is ‘Alt+C’ → compile (or) ‘Alt+F9’ for line
by line compilation. After compilation, the C file will exist of ‘filename.obj’.
Execution of C program:
1) After compilation we get the object file which consists of machine code of the program.
2) Choose ‘Run’ menu → execute, for execution of our program (or) shortcut key for execution of our
program is ‘Ctrl+F9’.
To see the output:
After the execution of our program we will see the output by pressing shortcut key ‘Alt+F5’.
Using Comments:
• In C program, we wish not to execute some of the statements of the program can be called as
comments.
• In C programming, comments can be written in 2 ways:
Single line comment: This way of commenting is only for single line source code of the program. The
symbol “//” before the line in the program.
Group of line comment: This way of commenting is used for group of line source code of the program.
The symbol is “/*” and it should be opening and closing.
/* ……………………………
……………………………
………………….............*/
C Tokens:
Keywords:
Keywords are reserved words which cannot be used as variables. There are almost 32
keywords seen in c language as follows,
explicitly applied to character data type.The range of character data type is -128 to +127,while unsigned
character is 0 to 255.
Example: char ch;
Variables:
A variable is a data name that may be used to store a data value. A variable may take different values at
different times during execution of the program. A variable name can be chosen by the programmer in a
meaningful way so as to reflect its function and nature in the program. Ex: sum, avg, total, value, x.
Department of Computer Science Page 7
St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester
Constants:
Constants refer to fixed values that the program may not alter during its execution. These fixed values are
also called literals. Constants can be of any of the basic data types like an integer constant, a
floating constant, a character constant, or a string literal.
1. Numeric Constants
2. Character Constants
3. String Constants
Numeric Constants:
Real Constants:-
Integer numbers are inadequate to represent quantities that vary continuously such as distance, heights,
temperatures etc. These quantities are represented by the numbers containing fractional parts like 17.548.
Such numbers are called real (or) floating point constants.
Eg:- 0.0083, -0.75, +247.6
A real number may also be expressed in exponential notation. For example, the value 215.65 may be written
as 2.1565e2 in exponential notation. Here ‘e2’ means multiply by 102.
Character Constants:
Any single character enclosed within single quotation marks is termed as a character constant.
Ex: 'A', 'x', 'y'.
String Constants:
A sequence of 0 or more characters surrounded by double quotation marks is termed as string
Constant. Ex: "Computer", "Sudha", "666".
Input/Output Statements In C:
ch = getchar();
printf("typed char is =");
putchar(ch);
}
❖ scanf():
The scanf() is used to read the formatted data items from the keyboard. The format is a userdefined
data item.
Operators in c:
✓ Arithmetic Operators:
'C' provides all the basic arithmetic operators. The operators +, -, /, *, % can operate on any built
in data type allowed in 'C'.
Operator Meaning
+ Addition
- Subtraction
/ Division
* Multiplication
% Module Division
The module division (%) operator will take the remainder value and (/) division operator will take
the quotient value.
Example
a + b 10 % 3 = 1
a – b 10 / 3 = 3
✓ Relational Operators:
Relational operators are used to compare the values to see if they are equal or if one of them is greater than
the other and so on. Relational operators in 'C' produce only a one or a zero result. These are often specified
as true or false respectively. 'C' supports six relational operators. They are: <. <=, >, >=, ==, !=
Operator Meaning
> greater than
< less than
>= greaterthan equal
<= lessthan equal
== equalto
!= not equalto
Example:
3 > 4 = false
10 >= 15 = false
10 > 5 = true
✓ Logical Operators:
'C' supports three logical operators. They are:
1. Logical AND (&&)
2. Logical OR (||)
3. Logical NOT (!)
The logical operators && and !! are sued when we want to test more than one condition and make
decision.
OP1 OP2 && ||
T T T T
T F F T
F T F T
F R R F
T = True; F = False
Example
Department of Computer Science Page 11
St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester
1. a = 4, b = 5, c = 6
(a < b) && (b > c)
(4 < 5) && (5 > 6)
T && T
T
2. (a < b) !! (b > c)
(4 < 5) !! (b > c)
(4 < 5) !! (5 > 6)
T !! F
T
✓ Increment and Decrement Operators:
'C' has two very useful operators not generally found in other languages. These are increment and decrement
operators, ++ and --. These operators are used to control the loops in an effective method.
The ++ operator adds one value to the operators while – operator subtracts one value. These operators are
also called unary operatory.
✓ Increment Operator-The ++ symbol is used for increment by 1 (one).
Example
++i equal to i = i + 1
i++ equal to i = i + 1
There are two types of increment operators.
(a) prefix(++i)
(b) postfix(i++)
In prefix increment operator, first increment the value and do the operation. On the other hand,
the postfix, first do the operation and then increment the value.
Example
i =7; x = ++i; x = i++; x = ?
x = ++7; x = 7++
x = i++ = i + 1 = 7 + 1 = 8
After execution the value of x = 8.
✓ Decrement Operators: The decrement operator is also similar to the increment operators. The –
symbol is used for decrementing by 1.
Example
--i equal to i = i – 1
i—equal to i = i – 1
Here also there are two types of decrements, prefix and postfix decrements.
i = 7; x = --i; x = i--
x = i-- = i = i – 1 = 7 – 1 = 6
After execution the value of x will be 6.
✓ Assignment Operators:
An assignment operator is used to assign a value to a variable. "=" is called an Assignment operator.
Example: a = 10
Operator Precedence
Operator Association Rank
( ), [ ] Left to right 1
++, -- size of Left to right 2
*, /, % Left to right 3
+, - Left to right 4
<, <=, >, >= Left to right 5
==, != Left to right 6
&& Left to right 7
|| Left to right 8
?: Right to left 9
= Right to left 10
, Left to right 11
I. A = 5; b = 6; c = 8
1. a + b * a – c
2. (a + b) * (a – c)
II. 10 + 5/2 * 3
III. i = j = k = 1; m = 2; n = 5; b = 3
(i + j) / k * n % m – 5 * b
Department of Computer Science Page 13
St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester
I. 1. a + b * a – c
5+6*5–8
5 + 30 – 8 = 35 – 8 = 27
2. (a + b) * (a – c)
(5 + 6) * (5 – 8)
11 * (-3) = -33
II. 10 + 5/2 * 3
10 + 2 * 3 = 10 + 6 = 16
III. i = j = k = 1; m = 2; n = 5; b = 3
(i + j) / k * n % m – 5 * b
2/1 * 5 % 2 – 5 * 3
2*5%2–5*3
10 % 2 – 5 * 3
0 – 15
-15.
✓ Bit-wise Operators:
Bit-wise Operators is used for manipulation of data at bit level. These operators are used for testing the bit
or shifting them right or left. Bit-wise Operators may not be applied to float or double datatype. 'C' supports
the following Bit-wise Operators.
1. Bit-wise AND (&)
2. Bit-wise OR (!)
3. Bit-wise Exclusive (^)
4. Bit-wise Complement (~)
5. Bit-wise Shift
(a) Left Shift (<<)
(b) Right Shift (>>)
❖ Bit-wise AND (&)
The Bit-wise AND Operator is represented by a single ampersand (&) and is surrounded on bothsides by
integer expression. The result of AND operation is one (1) if both bits have a value of one.Otherwise it is 0
(zero).
Example:
x = 5; y = 2
101010
x&y = 000
❖ Bit-wise OR (!):
The bit-wise OR is represented by the Exclamation symbol (!) and is surrounded by two integer operands.
The result of OR operation is 1 if at least one of the bits have a value of 1. Otherwise it is 0(zero).
Example
x = 5; y = 2
101010
x!y = 7 111
❖ Bit-wise Exclusive OR (^):
The bit-wise exclusive OR is represented by the Caret (^) symbol. The result of exclusive OR is
Example
x=1010 10 (Decimal value)
~x=0101 5 (Decimal value)
OP1 OP2 & ! ^ ~ OP1 ~ OP2
1 1 1 1 0 0 0
1 0 0 1 1 0 1
0 1 0 1 1 1 0
0 0 0 0 0 1 1
❖ Bit-wise Shift:
The shift operation take binary patterns and shift the bits to the left or right keeping the same number of
by dropping shifted bits on the end and fielding in with 0's from the other and 'C' provides two types of shift
operations. They are:
1. Left Shift (<<) 2. Right Shift (>>)
*Left Shift (<<):Syntax:
op << n;
where, 'op' is the expression and 'n' is the number of bits position to be shifted.
x = y << 1;
This statement shifts one bit to the left in 'y' and then the result is accessing to the 'x'.
Example
x = 10 << 2
1010 = 10
10 << 1 1010 * = 10 * 2
10 << 2 1010 **= 20 * 2 40
252423222120 = 8 + 0 + 32 = 40
*Right Shift (>>):
Syntax
op >> n;
where, 'op' is the integer expression. That is to be shifted and 'n' is the number of bit position to
beshifted.
x = y >> 1;
This statement shift 'y' value one bit to the right and assigns the result to 'x'.
Example:
x 10 >> 2
1010
10 >> 1 *1010 = 10/2 = 5
10 >> 2 **1010 = 5/1 = 2.
C programming examples:
We can add lab programs here
❖ INTRODUCTION TO DECISION CONTROL STATEMENTS:
A ‘C’ program is a set of statements which are normally executed sequentially in the order in which they
appear. This happens when no options or no repetitions of certain calculations are necessary. If we have
a number of situations where we may have to change the order of execution of statements based on
certain conditions until certain specified condition is satisfied. This involves a kind of decision making
to see whether a particular condition has occurred or not and then direct the computer to execute certain
statements accordingly.
‘C’ language possesses such decision-making by supporting the following statements:
1. if statement
2. switch statement
3. conditional operator statement
4. goto statement.
The above statements are known as decision-making statements. Since these statement control the
flow of execution, they are also known as control statements.
1. if statement:-
The if statement is a powerful decision-making statement and is used to control the flow of execution
of statements. It is basically a two-way decision statement and is used with an expression. It allows
the computer to evaluate the expression first and then depending on whether the value of expression
is true or false, it transfers the control to a particular statement.
The if statement is divided into four types. They are:
i. simple if statement
ii. if -------- else statement
iii. Nested if ------ else statement
iv. else if ladder
i. Simple if statement:-
The general form of a simple if statement is
if(test condition)
Statement-block;
Statement-x;
The “statement-block” may be single statement or a group of statements. If the test condition is true, the
“statement-block” will be executed. Otherwise, the “statement-block” will be skipped and the execution
will jump to the “statement-x”. When the condition is true, then the “statement-block” and “statement-x”
both are executed.
Eg:-
#include<stdio.h>
main()
{
int num;
printf(“enter a number”);
scanf(“%d”,&num);
if(num>=0)
printf(“%d is a positive number\n”,number);
}
Output:
enter a number 6
6 is a positive number
if -else statement: -
The if -else statement is an extension of the simple if statement. The general form is:
if(test expression)
{
True-block statements;
}
else
{
False-block statements;
}
Statement-x;
If the test expression is true, then the true, then the true-block statements are executed and the control is
transferred to the statement-x. If the test expression is false, then the false-block statements are executed
and the control is transferred to the statement-x;
Eg: -
#include<stdio.h>
#include<conio.h>
void main( )
{
int a,b;
clrscr( );
printf(“\nenter any two numbers”);
scanf(“%d%d”,&a,&b);
if(a>b)
printf(“\na=%d is biggest number”,a);
else
printf(“\nb=%d is biggest number”,b);
getch();
}
2. WAP to check a given number is even or odd
#include<stdio.h>
#include<conio.h>
void main( )
{
int num;
clrscr( );
printf(“\nenter any number”);
scanf(“%d”,&num);
if((num%2)==0)
printf(“\nThe given number %d is even”,num);
else
printf(“\nThe given number %d is odd”,num);
getch( );
}
ii. Nested if -else statement:-
When a series of decisions are involved, we may have to use more than one if -else statements in nested
form. The general form is:
if(test condition-1)
{
if(test condition-2)
{
Statement-1;
}
else
{
Statement-2;
}
}
else
{
Statement-3;
}
Statement-x;
If the condition-1 is false, then the statement-3 will be executed and the control transferred to the statement-
x. If the condition-1 is true, then it continues to perform the second test. If the condition-2 is true, then the
statement-1 will be evaluated and the control transferred to the statement-x. If the condition-2 is false, then
the statement-2 will be evaluated and the control is transferred to the statement-x.
Eg:-
#include<stdio.h>
#include<conio.h>
void main( )
{
int a,b,c;
printf(“\nenter any three numbers”);
scanf(“%d%d%d”,&a,&b,&c);
if(a>b)
{
if(a>c)
{
printf(“\na=%d is largest number”,a);
}
else
{
printf(“\nc=%d is largest number”,c);
}
}
else
{
if(c>b)
{
printf(“\nc=%d is largest number”,c);
}
else
{
printf(“\nb=%d is largest number”,b);
}
}
getch( );
}
2.WAP to calculate average of 3 subject marks and calculate the division as per the following conditions
avg division
>=60 first
>=50 second
>=35 third
<35 fail
#include<stdio.h>
#include<conio.h>
void main( )
{
int m1,m2,m3,avg;
clrscr( );
printf(“\nenter 3 subjects marks”);
scanf(“%d%d%d”,&m1,&m2,&m3);
avg=(m1+m2+m3)/3;
if(avg>=60)
printf(“\nFirst Division”);
else
{
if(avg>=50)
printf(“\nSecond Division”);
else
{
if(avg>=35)
printf(“\nThird Division”);
else
{
printf(“\nFail”);
}
}
getch( );
}
iii. The else if ladder:-
The way of putting ifs together when multipath decisions are involved. A multipath decision is
a chain of ifs in which the statement associated with each else is an if. The general form is:
if(condition-1)
statement-1;
else if(condition-2)
statement-2;
else if(condition-3)
statement-3;
: : : :
: : :
else if(condition-n)
statement-n;
else
default-statement;
statement-x;
The above construct is known as “else if ladder”.The conditions are evaluated from the top to
downwards.As soon as a true condition is found,the statement associated with it is executedand the control
is transfereed to the statement-x,skipping the rest of the ladder. When all the ‘n’ conditions become false,
then the final else containing the default-statement will be executed and the control is transferred to the
statement-x.
Eg:-
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
printf("Enter a Number: ");
scanf("%d",&a);
if(a > 0)
{
printf("Given Number is Positive");
}
else if(a == 0)
{
printf("Given Number is Zero");
}
else if(a < 0)
{
printf("Given Number is Negative");
}
getch();
}
2.WAP to accept student number, marks in 3 subjects. Calculate average and display result as per the
following conditions:
Average Result
>=75 Distinction
>=60 First
>=50 Second
>=35 Third
Otherwise Fail
#include<stdio.h>
#include<conio.h>
Department of Computer Science Page 21
St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester
void main( )
{
int sno,m1,m2,m3,tot,avg;
clrscr( );
printf(“\nenter student number, name and marks in three subjects”);
scanf(“%d%d%d%d”,&sno,&m1,&m2,&m3);
tot=m1+m2+m3;
avg=tot/3;
clrscr( );
printf(“\nNumber :%d”,sno);
printf(“\nM1:%d\tM2 :%d\t M3 :%d”,m1,m2,m3);
printf(“\nTotal : %d”,tot);
printf(“\nAverage :%d”,avg);
printf(“\nResult :”);
if(avg>=75)
printf(“Distinction”);
else if(avg>=60)
printf(“First class”);
else if(avg>=50)
printf(“Second class”);
else if(avg>=35)
printf(“Third class”);
else
printf(“Fail”);
getch( );
}
2.The Switch statement:-
When one of the many alternatives is to be selected, then we can use if statement to control the
selection. When the number of alternatives increases then the program will become difficult to read and
follow.
‘C’ has a built-in multiway decision statement known as a switch. The general form is as
follows:
switch(expression)
{
case value-1 : block-1;
break;
case value-2 : block-2;
break;
case value-3 : block-3;
break;
: : :
: : :
default : default-statements;
}
Statement-x;
When the switch is executed, the value of the expression is successfully compared against the values
value-1, value-2, ------- If a case is found whose value matches with the value of the expression, then the
block of statements that follow are executed.
The “break” statement at the end of each block signals the end of a particular case and causes an exit
from the switch statement, transferring the control to the statement-x.
The “default” is an optional case. It will be executed if the value of the expression does not match
with any of the case values and the control goes to the statement-x.
Eg:-
1. WAP to display the name of the day depending upon the number which is entered by the user using
switch statement.
#include<stdio.h>
#include<conio.h>
void main( )
{
int no;
clrscr( );
printf(“\n enter any number between 1 to 7”);
scanf(“%d”,&no);
switch(no)
{
case 1 : printf(“\nMonday”);
break;
case 2 : printf(“\nTuesday”);
break;
case 3 : printf(“\nWednesday”);
break;
case 4 : printf(“\nThursday”);
break;
case 5 : printf(“\nFriday”);
break;
case 6 : printf(“\nSaturday”);
break;
case 7 : printf(“\nSunday”);
break;
default: printf(“\n enter a correct number”);
}
getch( );
}
Department of Computer Science Page 23
St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester
#include,stdio.h>
#include<conio.h>
void main( )
{
char ch;
clrscr( );
printf(“\n enter any charcter”);
scanf(“%c”,&ch);
switch(ch)
{
case ‘A’:
case ‘a’: printf(“\n%c is a vowel”,ch);
break;
case ‘E’:
case ‘e’: printf(“\n%c is a vowel”,ch);
break;
case ‘I’:
case ‘i’: printf(“\n%c is a vowel”,ch);
break;
case ‘O’:
case ‘o’: printf(“\n%c is a vowel”,ch);
break;
case ‘U’:
case ‘u’: printf(“\n%c is a vowel”,ch);
break;
default : printf(“\n%c is not a vowel”,ch);
}
getch( );
}
3.Conditional Operator(?:) statement:-
The ‘C’ language has an unusual operator, useful for making two-way decisions. This operator is a
combination of “?” and “:” , and takes three operands. This operator is popularly known as the conditional
operator. The general form of the conditional operator is as follows:
The conditional expression is evaluated first. If the result is true, expression1 is evaluated and is returned
the value of the conditional expression. Otherwise, expression2 is evaluated and its value is returned. For
example,
if(x<0)
flag=0;
else
falg=1;
can be written as
flag=(x<0)?0:1;
Eg:-
#include<stdio.h>
void main( )
{
int isqrd,i;
printf(“\n enter a number”);
scanf(“%d”,&i);
isqrd=(i>0) ? i*i : -(i*i);
printf(“%d squared is %d,i,isqrd);
getch( );
}
4.The goto Statement:-
The goto statement is used to alter the normal sequence of program execution by transferring
control to some other part of the program unconditionally. The general form is as follows:
goto label;
where the label is an identifier that is used to label the target statement to which the control is transferred.
Control may be transferred to anywhere within the current function. The target statement must be labelled,
and a colon must follow the label.
label:
statement;
Each labelled statement within the function must have a unique label i.e., no two statements can have the
same label.
Eg:-
#include<stdio.h>
void main( )
{
int number;
printf(“\nwww.”);
goto x;
y:
printf(“expert”);
goto z;
Department of Computer Science Page 25
St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester
x:
printf(“C programming”);
goto y;
z:
printf(“.com”);
getch( );
}
❖ Iterative Statements
In looping, a sequence of statements is executed until some conditions for termination of
the loop are satisfied. A program loop 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.
while(test condition)
Statements-X;
The test condition is evaluated and if the condition is true, then the body of the loop is executed.
After execution of the body, the test condition is once again evaluated and if it true, then again the body
is executed once again. This process of repeated execution of the body continues until the test condition
becomes false and the control is transferred out of the loop.
Eg:-
#include<stdio.h>
main()
{
int count=1;
Department of Computer Science Page 26
St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester
while(count<=4)
{
printf(“%d”,count);
count++;
}
}
Output: 1 2 3 4
do
}while(test condition);
Statement-X;
The program proceeds to evaluate the body of the loop first. At the end of the loop, the test
condition in the while statement is evaluated. If the condition is true, then the program continues to
evaluate the body of the loop once again. This process continues as long as the condition is true. When
the condition becomes false, then the loop will be terminated and the control goes to the statement-X.
Eg:
#include<stdio.h>
#include<conio.h>
#include<stdio.h>
main()
{
int j=0;
do
{
printf(“value of a variable j is:%d \n”,j);
j++;
}while(j<=3);
}
Output: value of a variable j is 0
value of a variable j is 1
value of a variable j is 2
value of a variable j is 3
3. The for statement:-
The for loop is most commonly used looping statement in ‘C’. This loop consists of three
expressions. The first expression is used to initialize the index value, the second expression is used to
check whether or not the loop is to be continued again and the third expression is used to change the
index value for further iteration. The general form is as follows:
for(initialization;test condition;re-initialization)
Eg:-
#include<stdio.h>
main()
{
int i;
for(i=1;i<=10;i++)
{
printf(“%d”,i);
}
}
Output: 1 2 3 4 5 6 7 8 9 10
Nested Loops:
C supports nesting of loops in C. Nesting of loops is the feature in C that allows the looping of statements
inside another loop. Let's observe an example of nesting loops in C.
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.
Syntax:
1. Outer_loop
2. {
3. Inner_loop
4. {
5. // inner loop statements.
6. }
7. // outer loop statements.
8. }
Outer_loop and Inner_loop are the valid loops that can be a 'for' loop, 'while' loop or 'do-while'
loop.
Syntax:
Department of Computer Science Page 28
St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester
The nested for loop means any type of loop which is defined inside the 'for' loop.
Example:
#include <stdio.h>
int main()
{
int n;// variable declaration
printf("Enter the value of n :");
// Displaying the n tables.
for(int i=1;i<=n;i++) // outer loop
{
for(int j=1;j<=10;j++) // inner loop
{
printf("%d\t",(i*j)); // printing the value.
}
printf("\n");
}
❖ Break and Continue Statement: -
The break statement in C programming has the following two usages −
• When a break statement is encountered inside a loop, the loop is immediately terminated and the
program control resumes at the next statement following the loop.
• It can be used to terminate a case in the switch statement (covered in the next chapter).
If you are using nested loops, the break statement will stop the execution of the innermost loop and start
executing the next line of code after the block.
Syntax
The syntax for a break statement in C is as follows:
break;
Eg:
#include<stdio.h>
main()
{
int num=0;
while(num<=100)
{
printf(“value of variable num is %d\n”,num);
if(num==2)
{
break;
}
num++;
}
printf(“out of while loop”);
}
Continue statement: -
The continue statement in C programming works somewhat like the break statement. Instead of
forcing termination, it forces the next iteration of the loop to take place, skipping any code in between.
For the for loop, continue statement causes the conditional test and increment portions of the loop to
execute. For the while and do...while loops, continue statement causes the program control to pass to the
conditional tests.
Syntax
continue;
#include <stdio.h>
void main( )
{
int a = 10;
do
{
if( a == 15)
{
a = a + 1;
continue;
}
printf("value of a: %d\n", a);
a++;
} while( a < 20 );
}
Department of Computer Science Page 30
St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester
❖ Goto statement
A goto statement in C programming provides an unconditional jump from the 'goto' to a labeled
statement in the same function
Syntax
goto label;
..
label: statement;
Here label can be any plain text except C keyword and it can be set anywhere in the C program above or
below to goto statement.
Eg:
#include<stdio.h>
main()
{
int n,i=1;
printf(“Enter the number whose table you want to print?”);
scanf(“%d”,&n);
table:
printf(“%d x %d = %d \n”,n,i,num*i);
i++;
if(i<=10)
goto table;
}
Output:
Enter the number whose table you want to print? 10
10x1=10
10x2=20
10x3=30
10x4=40
10x5=50
10x6=60
10x7=70
10x8=80
10x9=90
10x10=100