UNIT II Www.anuupdates.org
UNIT II Www.anuupdates.org
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.
……………………………………………………………………………………………………………………………..
C Language Introduction
C is a procedural programming language. It was initially developed by Dennis Ritchie between 1969 and
1973. It was mainly developed as a system programming language to write operating system.
In 1988, the American National Standards Institute (ANSI) had formalized the C language.
C was invented to write UNIX operating system.
C is a successor of 'Basic Combined Programming Language' (BCPL) called B language.
Linux OS, PHP, and MySQL are written in C.
C has been written in assembly language.
Database Systems
Language Interpreters
Compilers and Assemblers
Operating Systems
Network Drivers
Word Processors
C is highly portable; programs once written in C can be run on other machines with minor or no
modification.
C is a collection of C library functions; we can also create our function and add it to the C library.
C is easily extensible.
20 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Advantages of C
C is the building block for many other programming languages.
Several standard functions are there (like in-built) that can be used to develop programs.
C programs are collections of C library functions, and it's also easy to add own functions to the C
library.
The modular structure makes code debugging, maintenance and testing easier.
Disadvantages of C
C does not provide Object Oriented Programming (OOP) concepts.
C allows a lot of freedom in writing code, and that is why you can put an empty line or white space
anywhere in the program. And because there is no fixed place to start or end the line, so it is difficult
to read and understand the program.
C compilers can only identify errors and are incapable of handling exceptions (run-time errors).
It does not provide strict data type checking (for example an integer value can be passed for floating
data type)
21 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Q) Structure of C Program
A c program is collection of different modules / Functions. Each module performs their own individual task.
The output of all modules are put together to generate final output. The basic structure of C program ANSI
C follow is given below
Documentation section:-
This is the section where the programmer gives the details of the program.
Generally it includes the name of the program, the author of the program and other details like date
when the program wrote.
C supports two type of comments 1. Single line comments 2. Documents line comments.
Example:
22 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
2. Document / multiple line comments
/**
* File Name: first.c
* Author: anuupdates
* Date: 09/08/2020
* Description: a program to display sum of tow matrix
* give proper input.
*/
Link section
The link section provides instructions to the compiler to link functions from system library.
This can be done by including header files like #include<stdio.h>
Defination section
Here one can define all symbolic constants used in C program using define keyword, like
#define PI 3.148
The main is an independent module which performs some operations on data to accomplish a task with in a
C program. The main section contains two parts.
1. Declaration part: It is the place where all variable declarations are done.
2. Execution part:
It contain instructions to the computer that cause it do some operations on data. Every C program
executable statement is terminated with semicolon.
The execution part begins with the curly brackets and ends with the curly close bracket. Both the
declaration and execution part are inside the curly braces.
Sub-Program Section
23 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Q) Writing the first C Program
Before starting the abcd of C language, you need to learn how to write, compile and run the first c program.
To write the first c program, open the C console and write the following code:
1. #include <stdio.h>
2. int main()
3. {
4. printf("Hello C Language");
5. return 0;
6. }
Line-1: #include <stdio.h> includes the standard input output library functions. The printf() function is
defined in stdio.h .
Line-2: int main() The main() function is the entry point of every program in c language.
Line-4: printf() The printf() function is used to print data on the console.
Line-5: return 0 The return 0 statement, returns execution status to the OS. The 0 value is used for successful
execution and 1 for unsuccessful execution.
Line-3&6: In C language, a pair of curly brackets define a scope and mainly used in functions and control
statements like if, else, loops. All functions must start and end with curly brackets.
What is a compilation?
The compilation is a process of converting the source code into object code. It is done with the help of the
compiler. The compiler checks the source code for the syntactical or structural errors, and if the source code
is error-free, then it generates the object code.
The following are the phases through which our program passes before being transformed into an executable
form:
Pre-processor
Compiler
Assembler
Linker
24 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
1. Pre-processor:
2. Compiler
3. Assembler
The assembly code is converted into object code by using an assembler. The name of the object file
generated by the assembler is the same as the source file. The extension of the object file in DOS is '.obj,' If
the name of the source file is 'hello.c', then the name of the object file would be 'hello.obj'.
4. Linker
Mainly, all the programs written in C use library functions. These library functions are pre-compiled, and the
object code of these library files is stored with '.lib' (or '.a') extension. The main working of the linker is to
combine the object code of library files with the object code of our program.
25 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Source Code File
The extension for these kind of files is '.c'. It defines the main and many more functions written in C.
main() is the starting point of the program. It may also contain other source code files.
Header Files
They have an extension '.h'. They contain the C function declarations and macro definitions that are shared
between various source files. C provides us with some standard header files which are available easily.
The header files are added at the start of the source code so that they can be used by more than one
function of the same file.
Object files
They are the files that are generated by the compiler as the source code file is processed.
These files generally contain the binary code of the function definitions.
The object file is used by the linker for producing an executable file for combining the object files
together. It has a '.o' extension.
Executable file
Various object files are linked by the linker for producing a binary file which will be executed directly.
26 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Q) Using Comments in C
Comments in C language are used to provide information about lines of code. It is widely used for
documenting code. There are 2 types of comments in the C language.
2. Multi-Line Comments
Single line comments are represented by double slash \\. Let's see an example of a single line comment in C.
#include<stdio.h>
int main(){
//printing information
printf("Hello C");
return 0;
}
Even you can place the comment after the statement. For example:
Multi-Line comments are represented by slash asterisk \* ... *\. It can occupy many lines of code, but it can't
be nested.
Syntax:
/*
code
to be commented
*/
#include<stdio.h>
int main(){
/*printing information
Multi-Line Comment*/
printf("Hello C");
return 0;
27 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Q) Keywords in C
A keyword is a reserved word. You cannot use it as a variable name, constant name, etc. There are only 32
reserved words (keywords) in the C language. A list of 32 keywords in the c language is given below:
Q) C Identifiers
C identifiers represent the name in the C program, for example, variables, functions, arrays, structures,
unions, labels, etc.
The first character of an identifier should be either an alphabet or an underscore, and then it can be
followed by any of the character, digit, or underscore.
In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can say that identifiers
are case sensitive.
Identifiers should be written in such a way that it is meaningful, short, and easy to read.
28 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Q) Basic Data Types:
Each variable in C has an associated data type. Each data type requires different amounts of memory and has
some specific operations which can be performed over it.
A data type defines a set of values and the operations on that can be performed on them. Moreover a data
type tells to the compiler
29 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
b) Character Data type
The characters are used to form words, numbers and expressions depending upon the computer on which
the program runs. There are two types of character types.
Signed characters which occupies one byte in memory and range from -128 to 127
Unsigned characters which occupies one byte in memory and range from 0 to 255
An integer is a number without fractional part. C supports 4 different types of integer types.
Derived Data types are derived from the basic data types.
C allows us to define our own data types such as structures and unions. These are called user defined data
types because the programmer or user creates them according to their needs.
30 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Q) Variables in C
A variable is a name of the memory location. It is used to store data. Its value can be changed, and it can be
reused many times.
It is a way to represent memory location through symbol so that it can be easily identified.
Each and every variable must be created before using in your c program. The basic syntax is
Example:
int a;
float b;
char c;
Here, a, b, c are variables. The int, float, char are the data types.
We can also provide values while declaring the variables as given below:
float f=20.8;
char c='A';
A variable name can start with the alphabet, and underscore only. It can't start with a digit.
A variable name must not be any reserved word or keyword, e.g. int, floats, etc.
A variable must be initialized before it can be used in your C program. Initialization is nothing but storing
values in variable. A variable can be initialized in two ways:
i) Static initialization:
We can initialize the variable at the time same time of declaration using assignment operator (=).
float f=20.8;
In some programs the value of a variable is known when the program in execution or after execution. This
type of initialization is known as dynamic initialization.
31 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Ex: C=a+b;
Types of Variables in C
a) Local variable
A variable that is declared inside the function or block is called a local variable.
b) Global variable
A variable that is declared outside the function or block is called a global variable. Any function can
change the value of the global variable. It is available to all the functions.
c) Static variable
d) Automatic variable
e) External variable
Q) Constant in C
A constant is a value or variable that can't be changed in the program, for example: 10, 20, 'a', 3.4, "c
programming" etc.
List of Constants in C
Constant Example
1. const keyword
2. #define preprocessor
32 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
1) C const keyword
Example:
#include<stdio.h>
int main(){
return 0;
2) C #define preprocessor
The #define preprocessor is also used to define constant. We will learn about #define preprocessor directive
later.
Example:
#include <stdio.h>
#define PI 3.14
main() {
printf("%f",PI);
Q) Operators in C
An operator is a symbol that tells the compiler to perform certain mathematical or logical operations.
C is a rich set of operators it include all high level language operators as well as low level language operators
such as bitwise operators.
There are following types of operators to perform different types of operations in C language.
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
6. Bitwise Operators
7. Assignment Operator
33 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
8. Special Operator
1. Arithmetic Operators
C provides all the basic arithmetic operators. They are shown in below table. The operators +, -,* and /all
work the same way as they do in other languages. These can operate on any built- in data type allowed in
C.
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
i) Integer Arithmetic: when both the operands in a single arithmetic expression such as a+b are integers, the
expression is called an integer expression and the operation is called integer arithmetic. Integer arithmetic
always yields an integer value.
In the below examples, if a and b are integers, then for a=14 and b= 4 we have the following results:
A-b =10
A+b= 14
A*b= 56
Real Arithmetic: An arithmetic operation involving only real operands is called real arithmetic; a real
operand may assume values either in decimal (or) exponential notation
Y= 1.0/3.0 = 0.333
Mixed – Mode Arithmetic: 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 results are
always a real number. Thus 15/10.0 = 1.5 where as 15/10 = 1.
34 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
2. Relational Operators:
The operators which are used to distinguish two values depending on their relationships. This operator
provides the relationship between two expressions. If the relationship is true it returns 1 otherwise 0.
3. Logical operators
Logical operators are used to combine expressions containing relational operators. The logical operators are
i) Logical AND (&&): The logical and operator produces true value when both expressions are true.
A B A&&B
0 0 0
0 1 0
1 0 0
1 1 1
ii) Logical OR: The logical operator produces TRUE value when one the of expression is true otherwise zero.
A B A&&B
0 0 0
0 1 1
1 0 1
1 1 1
iii) Logical NOT: The logical not operator takes a single expression and produces opposite value.
A !A
0 1
1 0
4. Assignment Operator
Assignment operators are used to assign the result of an expression to a variable, the general format of
assignment statement is:
a=10;
35 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
V OP = exp;
Where V is a variable, exp is an expression and OP is a C binary arithmetic operator. The operator
Some of the commonly used shorthand assignment operators are shown below.
a=a+1 a+=1
a=a-1 a-=1
a=a*(n+1) a*=n+1
a=a/(n+1) a/=n+1
a=a%b a%=b
1. What appears on the left hand side need not be repeated and therefore it becomes easier to write.
C allows two very useful operators not generally found in other languages. These are the increment and
decrement operators:
++ and - -
The operator ++ adds 1 to the operand, While – subtracts 1. Both are unary operators and takes the
following form:
++m; or m++;
--m ; or m - -;
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 an assignment statement. Consider
the following:
m = 5;
y = ++m;
In the case, the value of y and m would be 6. Suppose, if we rewrite the above statement as
m = 5;
y = m++;
36 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
then, the value of y would be 5 and m would be 6. A prefix operator first adds 1 to the operand and then
the result is assigned to the variable on left. On the hand, a postfix operator first assigns the value to the
variable on left and then increments the operand.
6. Conditional operator
A ternary operator pair “?:” is available in C to construct conditional expressions of the form.
exp1 is evaluated first. If it is nonzero (true), then the expression exp2 is evaluated and becomes the
value of the expression.
If exp1 is false, exp 3 is evaluated and its value becomes the value of the expression.
Note that only one of the expressions (either exp2 or exp3) is evaluated.
a = 10;
b = 15;
x = (a>b)? a : b;
7. Bitwise operators
C has a distinction of supporting special operators known as bitwise operators for manipulation of data at bit
level. These operators are used for testing the bits, or Lists the bitwise operators and their meanings.
Operator Meaning
! Bitwise OR
8. Special Operators:
These are used for special purpose in C language these operators are used in pointers, structures and unions
etc. Some types special operators as
I ) unary operator
37 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
I) Unary Operator: Those that operators on a single operand. The unary operators are ++, - -,
(underscore), & (address operand),* (indirection operator), size of operator and so on.
II) Comma Operator: When a no. of statement occurred in a C program having a relationship between
expressions. Then we can write all expression are statements in a single expression using comma
(,) operator. The comma operator are also used in variable declaration statement.
Ex: int a, b ;
Iv) Member selection Operator: These operators are used in structures, unions and pointers.
38 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Q) I/O Statements in C
Reading the data from the input devices and displaying the result on the screen are two major task of
program. To perform these operations user-friendly, C has a number of input-output functions.
1. Printf(): The printf() function prints all type of data values on output console. The general form is
2. Scanf(): The scanf() function is used for input. It reads the input data from the console.
#include<stdio.h>
int main(){
int number;
printf("enter a number:");
scanf("%d",&number);
return 0;
The unformatted I/O functions can be classified into three types: 1) String I/O 2) Character I/O 3) File I/O
1) String I/O: These functions are used to read and print strings.
a) gets(): This function is used to read a string from the input console.
2) Character I/O: These functions are used to read and print characters.
a) getchar(): This function reads character type data from the standard input device. It reads one character at
a time.
b) putchar(): This function print one character at a time on the output console.
c) getch(). getche(): These functions read any alpha numeric characters from the standard input devices.
d) putchar(): This function prints any alpha numeric value on output console.
39 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Q) Type conversion / Type casting
Type conversion or type casting of variables refers to converting a variable value of one data type to
another. Type conversion is done implicitly where as type casting is done explicitly by programmer.
Type conversion:
Type conversion is done when the expression has different data types. To evaluate the expression, the data
type is promoted from a lower type to a higher level. The hierarchy is shown below.
Type conversion:
float y=7.35;
double z=x+y;
In the above expression the ‘x’ is converted to float then addition is will take place.
Type casting:
Type casting is also known as forced conversion. It can be done by using cast operator.
Example:
40 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Without Type Casting:
int f= 9/4;
41 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Chapter-II
……………………………………………………………………………………………………………………………..
The conditional branching statements help to jump from one part of the program to another depending on
weather a particular condition is true or false. C provides three types of conditional branching statements.
1. If statement
2. Switch statement
3. Conditional operator.
1) If statements: The if statement many be implemented on different forms depending upon the complexity
of condition tested.
a) Simple if statement
b) If-else statement
c) Nested-if statement
Syntax:
If(test condition)
Statement block;
Statement-x
The statement block is executed only if the condition is true and them followed by rest of the program
(statement-x) will be executed.
If the condition is false, the statement block is skipped and rest of the program is executed.
Example: Write a C program to check whether the given number is even or not.
42 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
#include<stdio.h>
int main()
int number=0;
printf("Enter a number:");
scanf("%d",&number);
if(number%2==0){
return 0;
b) If-else statement
Syntax:
If(test-condition)
else
Statement-x
If test condition is true both true block statements and statement-x are executed.
If test condition is false both the else block statements and statement-x are executed.
In any case both true block and else block are not executed at a time.
Example: Write a C program to find biggest of two numbers using if-else statement.
#include<stdio.h>
void main()
int a, b, c;
43 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
scanf(“%d %d”, &a, &b);
if(a>b)
printf(“a is big”);
else
printf(“ b is big”);
getch();
c) Nested-if statement:
C language supports if-else-if statement to test additional conditions a part from the initial condition. The
general form is
if(test condition-1)
{
if(test condition-2)
{
statement-2
}
else
{
statement-3
}
}
else
{
statement-1
}
statement-x
44 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Example: write a c program to find biggest of three numbers using nested-if statement.
#include<stdio.h>
void main()
{
int a,b,c;
printf (“ enter a, b, c values”);
scanf(“ %d %d %d”, &a, &b, &c);
if(a>b)
{
if(a>c)
{
printf(“ a is big”);
}
else
{
printf(“ c is big”);
}
}
else
{
if(c>b)
{
printf(“ c is big”);
}
else
{
printf(“ b is big”);
}
}
getch();
}
d) else-if ladder:
There is another way of putting ifs together when multipath decisions are involved. A multipath decision is
chain of ifs in which the statement associated with each else is an if. It takes the following general form:
45 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
if(condition-1)
Statement-1;
else if(Statement-2)
Statement-2;
else if(condition-3)
Statement-3;
……………..
else if(condition-n)
Statement-n;
else
default statement;
Statement-x
46 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Example: program on to display the examination result.
#include <stdio.h>
#include<conio.h>
void main ()
int marks;
if (marks>=75)
else
getch();
47 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
2. Switch Statement
C has a built in multi way decision statement known as a switch. The switch statement tests the value of a
given variable (or expression) against a list of case values and when a match is found, a block of statements
associated with that case is executed.
switch (variable)
{
case value1:
Statement block 1;
Break;
case Value 2:
Statement block2;
Break;
…………………..
case value N :
Statement block N;
Break;
Default:
}
Statement X ;
In the syntax of the switch case statement, the break statement must be used at the end of each case because
if it were not used, then all the cases from the one met will be executed.
To summarize the switch case construct, let us go through the following rules:
The control expression that follows the keyword switch must be of integral type ( i.e., either
be an integer or any value that can be converted to an integer).
The default label is optional and is executed only when the value of the expression does not
match with any labeled constant expression.
48 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Example : program on to determine whether an entered character is vowel or not.
#include<stdio.h>
#include<conio.h>
void man ( )
{
char ch;
printf(“/n Enter any character:”);
Scanf (“%c”, &ch);
switch (ch)
{
case ‘ a ‘
printf (“/n %%c is a VOWEL”, ch);
break;
case ‘e’
printf(“/n %c is a VOWEL”, ch);
break;
case ‘ I ‘:
Printf (“/n % c is a VOWEL “,ch);
case ‘o’
printf( “/n %c is a VOWEL”, ch);
break;
case ‘ u ‘
printf (“/n%c is a VOWEL”,ch);
break;
default : printf (“%c is not a VOWEL”, ch);
}
getch( );
}
3. Conditional operator
The operator pair (?, :) is called ternary operator and it takes the following form
Expression1 is evaluated first if it is true expression2 is evaluated and becomes the value of the value.
Otherwise expression3 is evaluated and becomes the value of the expression.
#include<stdio.h>
void main()
{
int a,b,results;
printf(“ enter a, b values”);
scanf(“ %d %d”. &a, &b);
results=a>b?a:b;
printf(“ results=%d”, results);
getch();
}
49 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Looping / Iterative statements in C
. When a single statement or a group of statements will be executed again and again in a program then such
type processing is called Loop (or iteration). The C programming language contains 3 different programming
statements for program looping.
1. for Loop
2. While Loop
3. Do while Loop
1. for Loop
The for loop in C language is used to iterate the statements or a part of the program several times. It is
frequently used to traverse the data structures like the array and linked list.
Syntax:
for(intitilization;condition;update statements)
Example:
#include<stdio.h>
void main ()
{
int i;
for(i=0;i<10;i++)
{
int i = 20;
printf("%d ",i);
}
}
The braces {} are used to define the scope of the loop. However, if the loop contains only one statement,
then we don't need to use braces. A loop without a body is possible. The braces work as a block separator,
i.e., the value variable declared inside for loop is valid only for that block and not outside.
50 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Infinitive for loop in C
To make a for loop infinite, we need not give any expression in the syntax. Instead of that, we need to
provide two semicolons to validate the syntax of the for loop. This will work as an infinite for loop.
#include<stdio.h>
void main ()
{
for(;;)
{
printf("welcome to infinite loop");
}
}
2. While loop:
While loop is also known as a pre-tested loop. In general, a while loop allows a part of the code to be
executed multiple times depending upon a given boolean condition. It can be viewed as a repeating if
statement. The while loop is mostly used in the case where the number of iterations is not known in
advance.
Syntax:
while(test expression)
{
body of the loop
}
Example:
#include<stdio.h>
int main(){
int i=1;
while(i<=10){
printf("%d \n",i);
i++;
}
return 0;
51 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
3. do-while
The do while loop is a post tested loop. Using the do-while loop, we can repeat the execution of several
parts of the statements. The do-while loop is mainly used in the case where we need to execute the loop at
least once. The do-while loop is mostly used in menu-driven programs where the termination condition
depends upon the end user.
Syntax:
do
{
body of the loop
}while(test condition);
Example:
#include<stdio.h>
int main(){
int i=1;
do{
printf("%d \n",i);
i++;
}while(i<=10);
return 0;
}
A) There are many differences between while loop and do-while loop. Some important and basic differences
between them is as follows:
While loop:
1. In while loop the condition is tested first and then the statement are executed, if the condition turns
out to be true.
2. It is entry-controlled loop
3. Never execute loop if condition is false
4. There is no semicolon at the end of while statement
5. Syntax:
while(condition)
{
i. Statements;
}
Do-While loop:
1. In do while the statements are executed for the first time and then the conditions are tested. If the
condition turns out to be true then the statements are executed again.
2. It is exit-controlled loop.
52 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
3. A do while is used for a block of code that must be executed at least once.
4. There is semicolon at the end od while statement.
5. Syntax:
do
{
Statements;
} while (condition);
Q) Nested loops
A loop within another loop is called nested loop. Consider a loop where the outer loop runs ‘n’ time and
consists of another loop inside it. The inner loop runs ‘m’ times. Then the total number of times the inner
loop runs during program execution is m*n times.
*
**
***
****
*****
#include<stdio.h>
void main()
{
int I, j;
for(i=0;i<=5;i++)
{
printf(“\n”);
for(j=1;j<=I;j++)
{
printf(“*”);
}
}
getch();
}
53 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Q) Break and continue
In various scenarios, you need to either exit the loop or skip an iteration of loop when certain condition is
met. So, in those scenarios are known as jumping out of the loop. There are two ways in which you can
achieve the same.
break statement
When break statement is encountered inside a loop, the loop is immediately exited and the program
continues with the statement immediately following the loop.
In case of nested loop, if the break statement is encountered in the inner loop then inner loop is exited.
#include <stdio.h>
int main()
{
int counter;
for (counter=1; counter<=10; counter++)
{
if(counter==5)
{
break;
}
printf("%dn", counter);
}
return 0;
}
Output: 1 2 3 4
54 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Continue statement
Continue Statement sends the control directly to the test-condition and then continue the loop process.
On encountering continue keyword, execution flow leaves the current iteration of loop, and starts with the
next iteration.
#include <stdio.h>
int main()
{
int counter;
for (counter =1; counter<=10; counter++)
{
if(counter%2==1)
{
continue;
}
printf("%dn", counter);
}
return 0;
}
Output:
2 4 6 8 10
55 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Q) goto statement
A goto statement has two uses
1. A goto statement can transfer the control to any place in a program; it is useful to provide branching
within the loop.
2. A goto statement is used to exit from deeply nested loops when a error occurs.
The goto statement is used to jump from one line to another line in the program.
Using goto statement we can jump from top to bottom or bottom to top.
To jump from one line to another line, the goto statement requires a label.
When we use a goto statement in the program, the execution control directly jumps to the line with
the specified label.
#include<stdio.h>
#include<conio.h>
void main(){
clrscr() ;
printf("We are at first printf statement!!!\n") ;
goto last ;
printf("We are at second printf statement!!!\n") ;
printf("We are at third printf statement!!!\n") ;
last: printf("We are at last printf statement!!!\n") ;
getch() ;
}
56 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d