Unit I Basics of C Programming Notes cs3251
Unit I Basics of C Programming Notes cs3251
CS3251 PROGRAMMING IN C L T P C
3 0 0 3
COURSE OBJECTIVES:
To understand the constructs of C Language.
To develop C Programs using basic programming constructs
To develop C programs using arrays and strings
To develop modular applications in C using functions
To develop applications in C using pointers and structures
To do input/output and file handling in C
CS3251 – PROGRAMMING IN C
Unit 1 Basics of C Programming
COURSE OUTCOMES:
Upon completion of the course, the students will be able to
CO1: Demonstrate knowledge on Programming constructs
CO2: Develop simple applications in C using basic constructs
CO3: Design and implement applications using arrays and strings
CO4: Develop and implement modular applications in C using functions.
CO5: Develop applications in C using structures and pointers.
CO6: Design applications using sequential and random access file processing.
TOTAL : 45 PERIODS
TEXT BOOKS:
REFERENCES:
1. Paul Deitel and Harvey Deitel, “C How to Program with an Introduction to C++”,
Eighth edition, Pearson Education, 2018.
2. Yashwant Kanetkar, Let us C, 17th Edition, BPB Publications, 2020.
3. Byron S. Gottfried, “Schaum’s Outline of Theory and Problems of
Programming with C”, McGraw-Hill Education, 1996.
4. Pradip Dey, Manas Ghosh, “Computer Fundamentals and Programming in C”, Second
5. Edition, Oxford University Press, 2013.
6. Anita Goel and Ajay Mittal, “Computer Fundamentals and Programming in C”,
1st Edition, Pearson Education, 2013.
2
D. Nagaraj, AP/CSE
CS3251 – PROGRAMMING IN C
Unit 1 Basics of C Programming
Paradigm can also be termed as method to solve some problem or do some task.
Programming paradigm is an approach to solve problem using some programming
language or also we can say it is a method to solve a problem using tools and techniques that
are available to us following some approach.
3
D. Nagaraj, AP/CSE
CS3251 – PROGRAMMING IN C
Unit 1 Basics of C Programming
Imperative programming is divided into three broad categories: Procedural, OOP and
parallel processing.
These paradigms are as follows:
Procedural programming paradigm – This paradigm emphasizes on procedure in
terms of under lying machine model. There is no difference in between procedural and
imperative approach. It has the ability to reuse the code and it was boon at that time
when it was in use because of its reusability.
Examples of Procedural programming paradigm:
C : developed by Dennis Ritchie and Ken Thompson
C++ : developed by Bjarne Stroustrup
Java : developed by James Gosling at Sun Microsystems
ColdFusion : developed by J J Allaire
Pascal : developed by Niklaus Wirth
4
D. Nagaraj, AP/CSE
CS3251 – PROGRAMMING IN C
Unit 1 Basics of C Programming
Real-World Applications of C
The use of the C programming language is not limited to the development of operating
systems and applications. It is also used in GUI development, IDE development etc. Some
uses of C language are:-
Operating Systems
Assemblers
Text Editors
Print Spoolers
Modern Programs
Databases
Utilities
1. Operating Systems:-
With the help of C, you can write your own operating system. Isn’t it cool? The C
programming language is used to develop windows and linux kernels and also the Apple OS
X kernel.
It stands for Graphical User Interface. Apart from creating operating systems, C is also used
to develop popular adobe softwares such as photoshop, premier pro, After Effects etc.
3. Embedded Systems:-
5
D. Nagaraj, AP/CSE
CS3251 – PROGRAMMING IN C
Unit 1 Basics of C Programming
In daily life, we use different embedded systems like coffee machines, microwaves, climate
control systems etc. C makes it easy to develop these systems.
4. Database:-
Popular database management software, MySQL was developed using the C programming
language.
5. Ease of Computation:-
6. Gaming:-
C programming is relatively faster than Java or Python. C language has been used in various
gaming applications and graphics. Many popular games like Tic-Tac-Toe, The Snake game,
Sudoku etc. are developed using the C language.
The C language is fast and easy to understand. So many programming languages like Java,
Python, PHP etc. get influenced by this. Even the libraries of Python are developed using C.
The syntax and control structures of PERL, PHP and C++ are based upon the C language.
8. Assemblers:-
Assemblers are mainly used to translate assembly level language to machine level language.
C also helped in developing GNU assembler.
9. Text Editors:-
C also helped in creating various text editors like Vim, Gedit etc.
10. Interpreters:-
You can also create language interpreters using the C programming langauge. C helped in
developing different programming language interpreters like Python and MATLAB
interpreters etc.
C also helped in designing several popular compilers like Clang C, MINGW, Apple C etc.
This is one of the most popular uses of C language.
6
D. Nagaraj, AP/CSE
CS3251 – PROGRAMMING IN C
Unit 1 Basics of C Programming
Preprocessor Directives: They are executed before the compiler compiles the source code.
E.g. #include, #define
Compile Program:
Compilation can be done by using compile option from Compile menu. Shortcut
key is Alt+F9.
After the compilation, errors & warnings are displayed. All the syntax errors are
removed from program during compilation.
The source program statements should be translated into object programs for
execution. If there is no error, now we can execute the program.
If there is any error, then the programmer should correct it.
Linking
Linking keeps all program files and functions required by the program together.
For example, if the programmer is using pow() function, then the object code of
this function should be brought from math.h library and linked to the main()
program.
Executing the Program:
After compilation, the executable object code will be loaded in the computer’s
main memory and the program is executed.
In case of logic or data errors in the program, the source program is altered and
all the earlier initiated steps such as compilation, linking and execution are
repeated.
Execution can be done by going to Run menu and invoking run option.
Shortcut key is Ctrl+F9
7
D. Nagaraj, AP/CSE
CS3251 – PROGRAMMING IN C
Unit 1 Basics of C Programming
Pre-processor
Syntax error
Linking Process
Execution of C program
8
D. Nagaraj, AP/CSE
CS3251 – PROGRAMMING IN C
Unit 1 Basics of C Programming
STRUCTURE OF A C PROGRAM
In general, a C program is composed of the following sections:
Section 1: Pre-processor directives
Section 2: Global declarations
Section 3: Functions
Section 1 and 2 are optional, Section 3 is compulsory.
Documentation Section
Pre-processor directives
void main()
{
Structure of a
Declaration part
C
ProgramExecutable part
}
Comments:
Comments are used to convey a message and used to increase the readability of a
program.
They are not processed by the compiler.
There are two types of comments:
1. Single line comment
2. Multi line comment
Single line comment
A single line comment starts with two forward slashes (//) and is automatically
terminated with the end of the line.
E.g. //First C program
Multi-line comment
A multi-line comment starts with /* and terminates with */.A multi-line comment is
used when multiple lines of text are to be commented.
E.g. /* This program is used to find
Area of the Circle */
Section 1.Preprocessor Directive section
The preprocessor directive section is optional.
9
D. Nagaraj, AP/CSE
CS3251 – PROGRAMMING IN C
Unit 1 Basics of C Programming
The pre-processor statement begins with # symbol and is also called the pre-
processor directive.
These statements instruct the compiler to include C preprocessors such as header
files and symbolic constants before compiling the C program.
The preprocessor directive is terminated with a new line character and not with a
semicolon.
They are executed before the compiler compiles the source code.
Some of the pre-processor statements are listed below:
(i)Header files
#include<stdio.h> - to be included to use standard I/O functions : prinf(),scanf()
#include<math.h> -to be included to use mathematical functions :eg)sqrt()
(ii)Symbolic constants
#define PI 3.1412
#define TRUE 1
10
D. Nagaraj, AP/CSE
CS3251 – PROGRAMMING IN C
Unit 1 Basics of C Programming
E.g. C Program
Line1 is a comment; Line 2 is a preprocessor directive. Line3 is a header of the function main.
Line 4, 5, 6 form the body of main function.
Example Program:
/*Addition of two numbers*/ Documentation Section
#include<stdio.h> Pre-processor directives
#define A 10 Definition Section
int c; Global declarations
int sum(int,int);
main() Main() functions
{
int b;
printf(“Emter the value for B:”);
scanf(“%d”,&b); Execution Part
c=sum(b);
printf(“\n Answer=%d”,c);
getch();
}
int sum(int y)
{
c=A+Y; Sub Program
return(c);
}
PROGRAMMING RULES
1. All statements should be written in lower case letters. Upper case letters are only used
for symbolic constants.
2. Blank spaces cannot be used while declaring a variable, keyword, constant and
function.
3. The programmer can write the statement anywhere between the two braces following
the declaration part.
4. The user can also write one or more statements in one line by separating
semicolon (;).Ex:
a=b+c;
d=b*c;
or
11
D. Nagaraj, AP/CSE
CS3251 – PROGRAMMING IN C
Unit 1 Basics of C Programming
a=b+c; d=b*c;
5. The opening and closing braces should be balanced. For example, if opening braces are
four, then closing braces should also be four.
1.3CONSTANTS
A constant is an entity whose value can’t be changed during the execution of a program.
Constants are classified as:
1. Literal constants
2. Qualified constants
3. Symbolic constants
1.3.1 Literal constants
Literal constant or just literal denotes a fixed value, which may be an integer, floating
point number, character or a string.
Literal constants are of the following types.
1. Integer Literal constant
2. Floating point Literal constant
3. Character Literal constant
4. String Literal constant
The rules for writing Floating point Literal constants in an exponential form:
A Floating point Literal constants in an exponential form has two parts: the
mantissa part and the exponent part. Both are separated by e or E.
The mantissa part can be either positive or negative. The default sign is
positive.
The mantissa part should have at least one digit.
The mantissa part can have a decimal point.
The exponent part should have at least one digit
12
D. Nagaraj, AP/CSE
CS3251 – PROGRAMMING IN C
Unit 1 Basics of C Programming
13
D. Nagaraj, AP/CSE
CS3251 – PROGRAMMING IN C
Unit 1 Basics of C Programming
Symbolic constants are created with the help of the define preprocessor directive. For ex
#define PI= 3.14 defines PI as a symbolic constant with the value 3.14. Each symbolic constant
is replaced by its actual value during the pre-processing stage.
1.4 VARIABLES
Definition:
A variable is an entity whose value can change during the execution of a program. A
variable is the name given to the memory location.
Eg: 1) Average
2) Height
Declaration of Variables
Every identifier must be declared before it is used.
To declare an identifier declaration statement is used.
The declaration statement is used to introduce the name of an identifier with its data
type to the compiler. It also reserves memory
Example:
int age;
char m;
int a, b, c;
Initializing Variables
Variables declared can be assigned or initialized using an assignment operator ‘=’. The
declaration and initialization can also be done in the same line.
Syntax: variable_name = constant
or
data_type variable_name = constant
14
D. Nagaraj, AP/CSE
CS3251 – PROGRAMMING IN C
Unit 1 Basics of C Programming
15
D. Nagaraj, AP/CSE
CS3251 – PROGRAMMING IN C
Unit 1 Basics of C Programming
These data types are derived from the basic data types. Derived data types available in
C are:
1. Array type eg. Char[ ], int [ ]
2. Pointer type eg. Char*, int*
3. Function type eg. int (int,int), float(int)
1.5.1.1.1Type qualifier
A type qualifier is used to indicate the special properties of data within an object. It
never affects the range of values & the arithmetic properties of the declared object.
Two type qualifiers available in C are:
Const qualifier: Object value will not be changed during the execution of a
program
Volatile qualifier
1.5.1.2 Type Modifiers
A type modifier modifies the base type to yield a new type. It modifies the range and the
arithmetic properties of the base type.
Type modifiers and the corresponding keywords available in C are:
Signed (signed)
Unsigned (unsigned)
Short (short)
Long (long)
Operands
An operand specifies an entity on which an operation is to be performed. It can be a
variable name, a constant, a function call.
E.g: a=2+3 Here a, 2 & 3 are operands
Operator
16
D. Nagaraj, AP/CSE
CS3251 – PROGRAMMING IN C
Unit 1 Basics of C Programming
Precedence of operators
The precedence rule is used to determine the order of application of operators in
evaluating sub expressions.
Each operator in C has a precedence associated with it.
The operator with the highest precedence is operated first.
Associativity of operators
The associativity rule is applied when two or more operators are having same
precedence in the sub expression.
An operator can be left-to-right associative or right-to-left associative.
17
D. Nagaraj, AP/CSE
CS3251 – PROGRAMMING IN C
Unit 1 Basics of C Programming
• The associability rule is applied when two or more operators are having same
precedence in the sub expression.
Operator Meaning
- Minus
++ Increment
-- Decrement
& Address- of operator
sizeof sizeof operator
2. Binary Operator: A binary operator operates on two operands. Some of the binary
operators are,
Operator Meaning
+ Addition
- Subtraction
* Multiplication
18
D. Nagaraj, AP/CSE
CS3251 – PROGRAMMING IN C
Unit 1 Basics of C Programming
/ Division
% Modular
Division
&& Logical AND
3. Ternary Operator
A ternary operator operates on 3 operands. Conditional o`perator (i.e. ?:) is the
ternary operator.
Increment operator
The operator ++ adds one to its operand.
++a or a++ is equivalent to a=a+1
Prefix increment (++a) operator will increment the variable BEFORE the
expression is evaluated.
Postfix increment operator (a++) will increment AFTER the expression
evaluation.
E.g.
19
D. Nagaraj, AP/CSE
CS3251 – PROGRAMMING IN C
Unit 1 Basics of C Programming
1. c=++a. Assume a=2 so c=3 because the value of a is incremented and then it
is assigned to c.
2. d=b++ Assume b=2 so d=2 because the value of b is assigned to d before it is
incremented.
Decrement operator
The operator – subtracts one from its operand.
--a or a-- is equivalent to a=a+1
Prefix decrement (--a) operator will decrement the variable BEFORE the
expression is evaluated.
Postfix decrement operator (a--) will decrement AFTER the expression
evaluation.
E.g.
1. c=--a. Assume a=2 so c=1 because the value of a is decremented and then
it is assigned to c.
2. d=b-- Assume b=2 so d=2 because the value of b is assigned to d before it
is decremented.
2. Relational Operators
Relational operators are used to compare two operands. There are 6 relational
operators in C, they are
5==3 returns
== Equal to false (0)
5>3 returns true
> Greater than (1)
5<3 returns false
< Less than (0)
5!=3 returns
!= Not equal to true(1)
Greater than or 5>=3 returns true
>= equal to (1)
Less than or equal 5<=3 return false
<= to (0)
20
D. Nagaraj, AP/CSE
CS3251 – PROGRAMMING IN C
Unit 1 Basics of C Programming
Logical operators are used to logically relate the sub-expressions. There are 3
logical operators in C, they are
If the relation is true, it returns value 1 and if the relation is false, it
returns value 0 .
Meaning of
Operator Operator Example Description
4. Bitwise Operators
C language provides 6 operators for bit manipulation. Bitwise operator operates on the
individual bits of the operands. They are used for bit manipulation.
Truth tables
21
D. Nagaraj, AP/CSE
CS3251 – PROGRAMMING IN C
Unit 1 Basics of C Programming
5. Assignment Operators
To assign a value to the variable assignment operator is used.
Operators Example Explanation
Simple assignment operator = sum=10 10 is assigned to variable sum
+= sum+=10 This is same as sum=sum+10
-= sum-=10 sum = sum-10
Compound assignment operators *= sum*=10 sum = sum*10
Or /+ sum/=10 sum = sum/10
Shorthand assignment operators %= sum%=10 sum = sum%10
&=sum&=10 sum = sum&10
^= sum^=10 sum = sum^10
E.g.
var=5 //5 is assigned to var
a=c; //value of c is assigned to a
22
D. Nagaraj, AP/CSE
CS3251 – PROGRAMMING IN C
Unit 1 Basics of C Programming
6. Miscellaneous Operators
Other operators available in C are
a. Function Call Operator(i.e. ( ) )
b. Array subscript Operator(i.e [ ])
c. Member Select Operator
i. Direct member access operator (i.e. . dot operator)
ii. Indirect member access operator (i.e. -> arrow operator)
d. Conditional operator (?:)
e. Comma operator (,)
f. sizeof operator
g. Address-of operator (&)
a) Comma operator
It is used to join multiple expressions together.
E.g.
int i , j;
i=(j=10,j+20);
In the above declaration, right hand side consists of two expressions separated by
comma. The first expression is j=10 and second is j+20. These expressions are evaluated from
left to right. ie first the value 10 is assigned to j and then expression j+20 is evaluated so the
final value of i will be 30.
b) sizeof Operator
The sizeof operator returns the size of its operand in bytes.
Example : size of (char) will give us 1.
sizeof(a), where a is integer, will return 2.
c) Conditional Operator
It is the only ternary operator available in C.
Conditional operator takes three operands and consists of two symbols ? and : .
Conditional operators are used for decision making in C.
Syntax :
(Condition? true_value: false_value);
For example:
c=(c>0)?10:-10;
If c is greater than 0, value of c will be 10 but, if c is less than 0, value of c will
be -10.
d) Address-of Operator
It is used to find the address of a data object.
Syntax
&operand
E.g.
&a will give address of a.
23
D. Nagaraj, AP/CSE
CS3251 – PROGRAMMING IN C
Unit 1 Basics of C Programming
printf() getch()
getche()
scanf() getchar()
gets()
putch()
putchar()
puts()
1.7.1 Unformatted Functions:
They are used when I/P & O/P is not required in a specific format.
C has 3 types I/O functions.
a) Character I/O
b) String I/O
c) File I/O
a) Character I/O:
1. getchar() This function reads a single character data from the standard input.
(E.g. Keyboard)
Syntax :
variable_name=getchar();
eg:
char c;
c=getchar();
CS3251 – PROGRAMMING IN C
Unit 1 Basics of C Programming
char ch;
ch = getchar();
putchar(ch);
}
Output:
A
A
3. getch() and getche() : getch() accepts only a single character from keyboard. The character
entered through getch() is not displayed in the screen (monitor).
Syntax
variable_name = getch();
Like getch(), getche() also accepts only single character, but getche() displays the entered
character in the screen.
Syntax
variable_name = getche();
4 putch(): putch displays any alphanumeric characters to the standard output device. It
displays only one character at a time.
Syntax
putch(variable_name);
b) String I/O
1.gets() – This function is used for accepting any string through stdin (keyboard) until enter
key is pressed.
Syntax
gets(variable_name);
Example Program
void main()
{
char ch[30];
clrscr();
25
D. Nagaraj, AP/CSE
CS3251 – PROGRAMMING IN C
Unit 1 Basics of C Programming
Width Modifier: It specifies the total number of characters used to display the value.
Precision: It specifies the number of characters used after the decimal point.
E.g: printf(“ Number=%7.2\n”,5.4321);
Width=7
Precesion=2
Output: Number = 5.43(3 spaces added in front of 5)
Flag: It is used to specify one or more print modifications.
Flag Meaning
- Left justify the display
+ Display +Ve or –Ve sign of value
Space Display space if there is no sign
0 Pad with leading 0s
E.g: printf(“Number=%07.2\n”,5.4321)
26
D. Nagaraj, AP/CSE
CS3251 – PROGRAMMING IN C
Unit 1 Basics of C Programming
Output: Number=0005.43
#include <stdio.h>
void main( )
{
int num1, num2, sum;
printf("Enter two integers: ");
scanf("%d %d",&num1,&num2);
sum=num1+num2;
printf("Sum: %d",sum);
}
27
D. Nagaraj, AP/CSE
CS3251 – PROGRAMMING IN C
Unit 1 Basics of C Programming
Output
Enter two integers: 12 11
Sum: 23
1.Branching
Jump-unconditional Branching
2.Iteration statements
Branching statements
Branching statements are used to transfer program control from one point to another.
2 types
a) Conditional Branching:- Program control is transferred from one point to another
based on the result of some condition
Eg) if, if-else, switch
b) Unconditional Branching:- Pprogram control is transferred from one point to
another without checking any condition
Eg) goto, break, continue, return
a) Conditional Branching : Selection statements
Statements available in c are
The if statement
The if-else statement
The switch case statement
(i)The if statement
C uses the keyword if to execute a statement or set of statements when the logical
condition is true.
Syntax:
if (test expression)
Statement; Test F
expr
essio
T n
Statement
28
D. Nagaraj, AP/CSE
CS3251 – PROGRAMMING IN C
Unit 1 Basics of C Programming
Example:
#include <stdio.h>
void main()
{
int n;
clrscr();
printf(“enter the number:”);
scanf(“%d”,&n);
if(n>0)
printf(“the number is positive”);
getch();
}
Output:
enter the number:50
the number is positive
29
D. Nagaraj, AP/CSE
CS3251 – PROGRAMMING IN C
Unit 1 Basics of C Programming
if (test expression1)
{
…..
if (test expression2)
{
….
if (test expression3)
{
…. 30
if (test expression n) D. Nagaraj, AP/CSE
}}}
Downloaded by Shantha Balaji (shanthabalaji2013@gmail.com)
lOMoARcPSD|51092703
CS3251 – PROGRAMMING IN C
Unit 1 Basics of C Programming
}
else
{
if(b>c)
{
printf(“b is greatest”);
}
else
{
31
D. Nagaraj, AP/CSE
CS3251 – PROGRAMMING IN C
Unit 1 Basics of C Programming
printf(“C is greatest”);
}
}
}
Output
Enter three numbers 2 4 6
C is greatest
v) Switch statement
It is a multi way branch statement.
It provides an easy & organized way to select among multiple operations depending
upon some condition.
Execution
1. Switch expression is evaluated.
2. The result is compared with all the cases.
3. If one of the cases is matched, then all the statements after that matched case gets
executed.
4. If no match occurs, then all the statements after the default statement get executed.
Switch ,case, break and default are keywords
Break statement is used to exit from the current case structure
Flowchart
switch(expression)
case: break
statement
constant 0
case : break
constant statement
1
default
statement break
End of switch
32
D. Nagaraj, AP/CSE
CS3251 – PROGRAMMING IN C
Unit 1 Basics of C Programming
Syntax
switch(expression)
{
case value 1:
program statement;
program statement;
……
break;
case value 2:
program statement;
Program statement;
……
break;
…
case value n:
program statement;
program statement;
……
break;
default:
program statement;
program statement;
}
Example1
void main()
{
char ch;
printf(“Enter a character\n”);
scanf(“%c”,&ch);
switch(ch)
{
case ‘A’:
printf(“you entered an A\n”);
break;
case ‘B’:
printf(“you entered a B\n”);
break;
default:
printf(“Illegal entry”);
break;
}
getch();
}
Output
Enter a character
A
33
D. Nagaraj, AP/CSE
CS3251 – PROGRAMMING IN C
Unit 1 Basics of C Programming
You entered an A
Example2
void main()
{
int n;
printf(“Enter a number\n”);
scanf(“%d”,&n);
switch(n%2)
{
case 0:printf(“EVEN\n”);
break;
case 1:printf(“ODD\n”);
break;
}
getch();
}
Output:
Enter a number
5
ODD
34
D. Nagaraj, AP/CSE
CS3251 – PROGRAMMING IN C
Unit 1 Basics of C Programming
z:
printf(“.com”);
getch();
}
Output : www.yahoomail.com
b)break statement
A break statement can appear only inside a body of , a switch or a loop
A break statement terminates the execution of the nearest enclosing loop or
switch.
Syntax
break;
break;
Example:1
#include<stdio.h>
void main()
{
int c=1;
while(c<=5)
{
if (c==3)
break;
printf(“\t %d”,c);
c++;
}
}
Output : 1 2
Example :2
#include<stdio.h>
void main()
{
int i;
for(i=0;i<=10;i++)
{
if (i==5)
break;
printf(“ %d”,i);
}
}
Output :1 2 3 4
iii) continue statement
A continue statement can appear only inside a loop.
A continue statement terminates the current iteration of the nearest enclosing
loop.
Syntax:
35
D. Nagaraj, AP/CSE
CS3251 – PROGRAMMING IN C
Unit 1 Basics of C Programming
continue;
Example :1
#include<stdio.h>
void main()
{
int c=1;
while(c<=5)
{
if (c==3)
continue;
printf(“\t %d”,c);
c++;
}
}
Output : 1 2 4 5
Example :2
#include<stdio.h>
main()
{
int i;
for(i=0;i<=10;i++)
{
if (i==5)
continue;
printf(“ %d”,i);
}
}
Output :1 2 3 4 6 7 8 9 10
return;
(or)
return expression;
CS3251 – PROGRAMMING IN C
Unit 1 Basics of C Programming
3. do while
Loops are classified as
Counter controlled loops
Sentinel controlled loops
Counter controlled loops
The number of iterations is known in advance. They use a control variable called loop
counter.
Also called as definite repetitions loop.
E.g: for
Sentinel controlled loops
The number of iterations is not known in advance. The execution or termination of the loop
depends upon a special value called sentinel value.
Also called as indefinite repetitions loop.
E.g: while
1. for loop
It is the most popular looping statement.
Syntax:
for(initialization;condition2;incrementing/updating)
{
Statements;
}
37
D. Nagaraj, AP/CSE
CS3251 – PROGRAMMING IN C
Unit 1 Basics of C Programming
1 2 3 4 5 6 7 8 9 10
Ex2: To find the sum of n natural number. 1+2+3…+n
void main()
{
int n, i, sum=0;
clrscr();
printf(“Enter the value for n”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
sum=sum+i;
}
printf(“Sum=%d”, sum);
getch();
}
Output:
Enter the value for n
4
sum=10
2. while statement
They are also known as Entry controlled loops because here the condition is checked before the
execution of loop body.
Syntax:
while (expression)
{
statements;
}
38
D. Nagaraj, AP/CSE
CS3251 – PROGRAMMING IN C
Unit 1 Basics of C Programming
Output:
1 2 3 4 5 6 7 8 9 10
3. do while statement
They are also known as Exit controlled loops because here the condition is checked after the
execution of loop body.
Syntax:
do
{
statements;
}
while(expression);
The body of do-while is executed once, even when the condition is initially false.
39
D. Nagaraj, AP/CSE
CS3251 – PROGRAMMING IN C
Unit 1 Basics of C Programming
i=i+1;
} while (num<=10);
getch();
}
Output:
1 2 3 4 5 6 7 8 9 10
Nested loops
If the body of a loop contains another iteration statement, then we say that the loops are nested.
Loops within a loop are known as nested loop.
Syntax
while(condition)
{
while(condition)
{
Statements;
}
Statements;
}
40
D. Nagaraj, AP/CSE