CP Unit 2
CP Unit 2
UNIT -2
INTRODUCTION to C PROGRAMMING
1. History of C:
Today C is one of the most popular computers programming language, because it is a
structured, high level, machine independent.
✓ The root of all modern languages is ALGOL, introduced in the early 1960’s by
international group. ALGOL was first computer language to use a block structure & it
was used in 2nd generation computers.
✓ IN 1967, Martin Richards develop a language BCPL (Basic combined programming
language) primarily for writing system software.
✓ In 1970, Ken Thompson created a language using many features of BCPL and it is
called as B. Both BCPL & B are ‘type less’ system programming language (no concept
of data types).
✓ ‘C’ was evolved by ALGOL, BCPL and B by Dennis Ritchie at bell laboratories in
1972, added the concept of Data types.
• Since, it was developed along with the ‘Unix’ operating system. C was called
as “Traditional C".
✓ C – language become popular after publication of the book, the ‘C-programming
language’ by’ kerninghan and denies ritchie’ in 1978.
✓ In 1983, American National Standard Institute appointed a technical team to define a
standard for C.
✓ The committee approved a version of C in 1989 which is known as ANSI C. It was then
approved by the International Standard Organization (ISO) in 1990. It came to known
as ISO C.
✓ C can named as C95 in 1995 then C99 in 1999.
The following flowchart shows the history of ANSI C.
1
UNIT –II COMPUTER PROGRAMMING
2. Importance of C
1. It is a robust language whose rich set of built in functions and operators can be used
to write any complex program. The C compiler combines the capabilities of an
assembly language with the features of a higher level language and therefore it is
well suited for both system software and business packages.
2. It is very efficient and fast.
3. Well suited for structured programming – program can be a set of function modules
those are collected properly to make program easier..
4. Ability to extend itself – we can add our own functions to C library.
5. Highly portable – C programs written in one computer can be run on another with
no modification.
Why Use c?
1. Powerful and flexible
C is a powerful and flexible language. The language itself places no constraints on you.
C is used for projects as diverse as operating systems, Word Processors, graphics,
spreadsheets, and even compilers for other languages.
2. Popular
C is a popular language preferred by professional programmers. As a result, a wide
variety of C compilers and helpful accessories are available for use by programmers.
3. Portable
C is a portable language. Portable means that a C program written for one computer
system (say an IBM PC) can be compiled and run on another system (say a DEC VAX
system) with little or no modification. Portability is enhanced by the ANSI standard for
C, the set of rules for C compilers.
4. Modular
C is a modular. C code can (and should) be written in routines called functions. These
functions can be reused in other applications or programs. By passing pieces of
information to the functions, you can create useful, reusable code.
Structure of a C Program
C program is a collection of one or more functions. Every function is collection of
statements, performs a specific task. The structure of a basic C program is:
2
UNIT –II COMPUTER PROGRAMMING
i. Documentation section
The documentation section consists of a set of comment lines giving the name of the
program, the author and other details, which the programmer would like to use later. There are
two types of comment lines.
1. Block comment lines /* */ and
2. Single line comment lines. //
#include directive
The #include directive instructs the compiler to include the contents of the file "stdio.h"
(standard input output header file) enclosed within angular brackets.
These two parts must appear between the opening and closing braces. The program
execution begins at the opening brace and ends at the closing brace. The closing brace of the
main function is the logical end of the program. All statements in the declaration and
executable part end with a semicolon.
#include<stdio.h>
int main( )
{
printf(“Welcome to C Programming\n”);
return 0;
}
Output
Welcome to C Programming
3
UNIT –II COMPUTER PROGRAMMING
Key words
✓ These are also called as reserved words.
✓ All Keywords have fixed meaning and these meanings cannot be changed.
✓ There are 32 keywords in C.
✓ All keywords must be written in lowercase only.
4
UNIT –II COMPUTER PROGRAMMING
Variables/Identifiers
Identifiers refers to names of variables, variable is a data name which stores a data
value.
Syntax: variable = expression;
- Expression can be a constant, variable, or any arithmetic equation.
Ex: a = 3, a = b, a = a+b
Rules for naming a Variable/Identifier
1. They must start with an alphabet or an underscore ( _ ).
2. It can not include any special characters or punctuation marks (like #, $, ^,?, ., etc.)
except underscore ( _ ).
3. They can be of any reasonable length. They should not contain more than 31 characters.
But it is preferable to use 8 characters.
4. There cannot be two successive underscores.
5. Reserved words/keywords cannot be identifiers.
6. Lower case or uppercase letters are permitted.
7. White spaces are not allowed
Ex: Which of the following are valid
• Ram (valid)
• ram (valid)
• ram sita (not valid)
• ramasita (valid)
• Int (not valid)
• _81ram (valid)
• Ram @sita (not valid)
• 84r (not valid)
Constants
Constant can be defined as a value that can be stored in memory and cannot be changed
during execution of the program. C has four basic types of constants. They are:
5
UNIT –II COMPUTER PROGRAMMING
i. Integer Constant
An integer constant must have at least one digit and should not have a decimal point. It can
be either positive or negative.
Ex: 1, 9, 234, 999
There are three types of integers namely –
✓ Decimal integer: It consists of set of digits 0 to 9 preceded by an optional – or + sign.
Ex: 123, -321, 0, 65431, +78.
✓ Octal integer: It consists of any combination of digits from the set 0 to 7, with
leading
0.
Ex: 04676, 0, 005
✓ Hexa decimal integers: A sequence of digits preceded by 0x (or) 0X is considered as
hexa decimal integer. They may also include alphabets from A to F.
Ex: 0x2, 0X9F
ii. Floating point Constant/ Real
A floating point constant is decimal number that contains either a decimal point or an
exponent. In the other words, they can be written in 2 forms: fractional and exponential.
When expressed in fractional form, note the following points.
1. There should be at least one digit, and could be either positive or negative value. A
decimal point is must.
2. There should be no commas or blanks.
Ex; 12.33, -19.56, +123.89
◼ When expressed in exponential form, a floating point constant will have 2 parts. One is
before e and after it. The part which appears before e is known as mantissa and the one
which follows is known as exponent. When expressed in this format, note the following
points.
1. mantissa and exponential should be separated by letter E.
2. mantissa can have a positive and negative sign.
3. default is positive.
Ex: 2e-10, 0.5e2, 1.2E+3, -5.6E -2
iii. Character Constant
These are single character enclosed in single quotes. A character can be single
alphabet, single digit, single special symbol enclosed with in single quotes. Not more than a
single character is allowed.
Ex:
1. ‘a’ ‘Z’ ‘5’ ‘$’
2. printf(“%d”,’a’);
o/p- 97 (‘a’ refers ASCII value is 97)
3. printf(“%c”,97)
o/p – a (97 refers ASCII value is ‘a’)
iv. String Constant
A String constant is sequence of characters enclosed in double quotes. So “a” is not
same as ‘a’. The characters comprising the string constant are stored in successive memory
locations.
Ex: “hello” “Programming” “cse”
6
UNIT –II COMPUTER PROGRAMMING
6. Data Types of C
C supports different types of data. Data type determines which type of data can be
stored in a declared variable. Data types can be broadly classified as shown in figure
Primitive Data Types: The variables which are declared with the primitive data
types occpies single memory cell only. Primitive data types listed as follows:
• Integer
• Character
• Float
• Void
i. Integer: Integer data type is used to declare a variable that can store numbers only. The
keyword used to declare a variable of integer type is “int”.
Syntax :- int variable_name; ex: int a;
integer is again classified as given below:
7
UNIT –II COMPUTER PROGRAMMING
ii. Character: character data type is used to declare a variable that can store characters/single
alphabets only. The keyword used to declare a variable of charcter type is “char”.
Syntax :- char variable_name; ex: char gender= ‘f’;
charcter is classified as follows:
• char
• signed char
• unsigned char
Data type Memory Size Range Format Specifier
7 7
-2 to 2 -1
char (or) signed char 1B %c
(-128 to 127)
0 to 28-1
unsigned char 1B %c
(0 to 255)
iii. Float: float data type is used to declare a variable that can store real constant numbers
only. The keyword used to declare a variable of float type is “float”.
Syntax :- float variable_name; ex: float r = 1.235;
Float can be classified as follows:
• float
• double
• long double
iv. void type: it holds no value and thus valueless. It is primarily used in three cases:
1.To specify the return type of a function (when the function returns no value)
2. To specify the parameters of the function (when the function accepts no arguments
from the caller.)
3. To create generic pointers.
7. Delimiters:
Delimiters are used for syntactic meaning in C. These are given below:
8. Variables
A variable is named memory location that stores a value. When using a variable, we
actually refer to address of the memory where the data is stored. C language supports two
basic kinds of variables:
1. Numeric variables
2. Character variables
8
UNIT –II COMPUTER PROGRAMMING
i. Numeric variables
Numeric variables can be used to store either integer values or floating point values.
While an integer value is a whole number without a fraction part or decimal point. A floating
point value can have a decimal point.
Numeric values may be associated with modifiers like short, long, signed, and
unsigned.
Variable declaration
To declare a variable, specify the data type of the variable followed by its name. The
data type indicates the kind of data that the variable will store. Variable names should always
be meaningful and must reflect the purpose of their usage in the program. In C, variable
declaration always ends with a semicolon.
Ex:
char grade;
int emp_no;
float salary;
double bal_amount
unsigned short int acc_no;
C allows multiple variable of same type to be declared in one statement, so the following
statement is absolutely legal in C
float temp_in_deg, temp_in_farh;
Initializing variables
Assigning value to variable is called variable initialization. For
example: char grade= ‘A’;
int emp_no=1007;
float salary=8750.25;
double bal_amount=100000000
◼ When variables are declared but not initialized they usually contain garbage values.
Basically variable declaration can be done in three different places in a C program.
1. Inside main() function are called local variables.
2. Outside main() function are called global variables.
3. In the function definition header are called formal parameters.
9. Operators in C
C supports different types of operators. An operator is a symbol that tells the computer
performs certain mathematical (or) logical manipulations. These operators can be categorized
into the following groups:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Increment/Decrement operators
5. Bitwise operators
6. Conditional operators
7. Assignment operators
8. Special operators
9
UNIT –II COMPUTER PROGRAMMING
1. Arithmetic operators: These are used to perform mathematical operations. These are
binary operators since they operate on two operands at a time. They can be applied to any
integers, floating-point number or characters.
C supports 5 arithmetic operators. They are +, -, *, /, %. The modulo (%) operator can
only be applied to integer operands and cannot be used on float or double values.
Ex: int a=9, b=3 (a and b are called operands.)
Program: /*An example program that illustrates the use of relational operators.*/
#include<stdio.h>
main()
{
10
UNIT –II COMPUTER PROGRAMMING
int a=9,b=3;
if(a<=b)
{
printf(“true”);
}
else {
printf(“false”);
}
}
Output: false
3. Logical operators
Operators which are used to combine two or more relational expressions are known as
logical operators (or) compound relational expression. C language supports three logical
operators – logical AND (&&), logical OR (||), logical NOT ( !).
✓
Logical&& and logical || are binary operators whereas logical ! is an unary operator.
✓
All of these operators when applied to expressions yield either integer value 0 (true) or an
integer value 1(false).
Truth table: logical AND (&&) – both the values are true result is true, remaining are false.
Logical OR (||) – both the values are false, result is false, remaining is true.
Logical NOT (!) – produces the result is inverse to the condition
A B A&&B A||B !A
0 0 0 0 1
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
11
UNIT –II COMPUTER PROGRAMMING
4. Unary operators
Unary operators act on single operands. C language supports three unary operators. They are:
1. Unary minus
2. Increment operator
3. Decrement operator
i. Unary minus
The unary minus operator returns the operand multiplied by –1, effectively changing
its sign. When an operand is preceded by a minus sign, the unary minus operator negates its
value.
For example,
int a, b=10;
a=-(b);
the result of this expression is a=-10.
12
UNIT –II COMPUTER PROGRAMMING
5. Bitwise operators
As the name suggests, the bitwise operators operate on bits. These operations include:
1. bitwise AND(&)
2. bitwise OR(|)
3. bitwise X-OR(^)
4. bitwise NOT(~)
5. shift operators:- 1. shift left(<<) 2. shift right(>>)
2. Bitwise OR (|)
When we use the bitwise OR operator, the bit in the first operand is ORed with the
corresponding bit in the second operand. If one or both bits are 1, the corresponding bit in the
result is 1 and 0 otherwise. In a C program, the | operator is used as follows.
Ex: int a=4,b=2,c;
c=a | b
printf(“%d”,c); //prints 6
A B A^B
0 0 0
0 1 1
1 0 1
1 1 0
Ex: int a = 4, b = 2, c; ex: 1 0 0 (binary value of 4) c
= a ^ b; (|) 0 1 0 (binary value of 2)
printf(“%d”, c); // prints 6 110
13
UNIT –II COMPUTER PROGRAMMING
5. Shift operators
C supports two bitwise shift operators. They are shift-left (<<) and shift-right (>>).
These operations are simple and are responsible for shifting bits either to left or to the right.
The syntax for shift operation can be given as:
23 22 21 20
(8 4 2 1)
x=4 0 1 0 0
0 0
x>>1 => 0 0 1 0 the result of x>>1 is 2
14
UNIT –II COMPUTER PROGRAMMING
6. Assignment operators
In C, the assignment operator (=) is responsible for assigning values to variables. When
equal sign is encountered in in an expression, the compiler processes the statement on the right
side of the sign and assigns the result to variable on the left side.
Ex: 1. int x;
x=10; //Assigns the value 10 to variable x.
2. if we have, int x=2,y=3,sum=0;
sum = x +
y; then
sum=5.
3. The assignment has right-to-left associativity, so the expression int a=b=c=10;
is evaluated as (a= (b= (c=10)))
Ex:
a = 5; // value of variable ‘a’ becomes 5
a = 5 + 10; // value of variable ‘a’ becomes 15
a = 5 + b; // value of variable ‘a’ becomes 5 + value of b
a = b + c; // value of variable ‘a’ becomes value of b + value of c
➔ Short hand/Compound assignment operators
The assignment operator can be combined with the major arithmetic operators such
operators are called compound assignment operators. C language supports a set of
compound assignment operators of the form:
variable op = expression; // where op is binary arithmetic operator.
The following table lists the assignment operators supported by the C:
Op Description Example
Add AND assignment operator. It adds the right C += A is equivalent to
+= operand to the left operand and assign the result to C = C + A
the left operand.
Subtract AND assignment operator. It subtracts the C −= A is equivalent to
−= right operand from the left operand and assigns the C = C – A
result to the left operand.
Multiply AND assignment operator. It multiplies C *= A is equivalent to
15
UNIT –II COMPUTER PROGRAMMING
*= the right operand with the left operand and assigns C=C*A
the result to the left operand.
Divide AND assignment operator. It divides the C /= A is equivalent to
/= left operand with the right operand and assigns the C=C/A
result to the left operand.
Modulus AND assignment operator. It takes C %= A is equivalent to
%= modulus using two operands and assigns the result C=C%A
to the left operand.
<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2
^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2
|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2
6. Conditional operator (? : )
It is also called ternary operator because it takes three operands.
syntax: variable = expression1 ? expression2 : expression3;
If the expression1 is evaluated to true then it evaluates expression2 and its value is
assigned to variable, otherwise it evaluates expression3 and its value is assigned to variable.
It is an alternative to simple if..else statement
Program: /* conditional operator */
#include<stdioh>
int main()
{
int a=5,b=6,big;
big = a>b ? a : b;
printf("%d is big\n", big);
return 0;
}
Output
6 is big
16
UNIT –II COMPUTER PROGRAMMING
7. Special operators:
i. Comma operator (,)
This operator allows the evaluation of multiple expressions, separated by the
comma, from left to right in the order and the evaluated value of the rightmost expression
is accepted as the final result.
Syntax: expressionM= ( expression1, expression2, expressionN);
Program: /* comma operator */
In C programming, there are mainly two types of expressions are available. They are as
follows:
17
UNIT –II COMPUTER PROGRAMMING
18
UNIT –II COMPUTER PROGRAMMING
19
UNIT –II COMPUTER PROGRAMMING
Flag Meaning
− Left justify the display
+ Display the positive or negative sign of value
0 Pad with leading zeros
Space Display space if there is no sign
Examples:
1. The simplest printf statement is
printf(“Welcome to the world of C language”); //When executed, it prints the string
enclosed in double quotes on screen.
2. printf(“Result:%d%c%f\n”,12,’a’,2.3); //Result:12a2.3
3. printf(“Result:%d%c%f\n”,12,’a’,2.3); //Result:12a2.3
4. printf(“Result:%d\t%c\t%f\n”,12,’a’,2.3); // Result: 12 a 2.3
5. printf(“%6d\n”,1234); // 1 2 3 4
6. printf(“%06d\n”,1234); // 0 0 1 2 3 4
7. printf(“%-6d\n”,1234); // 1 2 3 4
8. printf(“%-06d\n”,1234); // - 0 1 2 3 4
9. printf(“%2d\n”,1234); // 1 2 3 4
11. printf(“%X\n”,255);
FF
20
UNIT –II COMPUTER PROGRAMMING
Program:
#include <stdio.h>
int main()
{
int x;
printf(“Enter number:”);
scanf(“%d”, &x);
printf(“The value of x is %d\n”, x);
return 0;
}
Output
Enter a number: 45
The value of x is 45
Program: /* For accessing multiple values from keyboard using scanf() function */
#include <stdio.h>
int main()
{
int x,y;
printf(“Enter two numbere:”);
scanf(“%d%d”, &x,&y);
printf(“The value of x is %d\n”, x);
printf(“The value of y is %d\n”, y);
return 0;
}
Output
Enter two numbers: 29 47
The value of x is 29
The value of x is 47
Program: /* ‘C’ program that illustrates the use implicit type conversion */
#include<stdio.h>
int main()
{
int sum, num=17;
char ch='A';
sum=num+ch;
printf("The value of sum=%d\n", sum);
return 0;
}
Output:
The value of sum= 82 //i.e. sum=num+ch=>17+65 (ASCII value of ‘A’)
ii. Explicit typecasting: Which is intentionally performed by the programmer for his
requirement in a C program?The explicit type conversion is also known as type casting.We
can convert the values from one type to another explicitly using the cast operator as follows:
Syntax: (data_type) expression;
The following rules have to be followed while converting the expression from one type to
another to avoid the loss of information:
1. All integer types to be converted to float.
2. All float types to be converted to double.
3. All character types to be converted to integer.
Ex: Let us look at some examples of type casting.
✓
res = ( int ) 9.5;
9.5 is converted to 9 by truncation then assigned to res.
✓
res = ( int ) 12.3 / ( int ) 4.2 ;
It evaluated as 12/4 and the value 3 is assigned to res.
✓
res = ( double ) total / n;
total is converted to double and then division is done in float point mode.
22
✓
res = ( int )(a + b);
The value of (a + b) is converted to integer and then assigned to res.
✓
res = ( int )a + b;
a is converted to int and then added with b.
Function Meaning
Trigonometric
asin(x) Arc sin of x.
acos(x) Arc cosine of x
atan(x) Arc tangent of x
atan2(y,x) Arc tangent of y/x
sin(x) sine of x
cos(x) cosine of x
tan(x) tangent of x
Hyperbolic
sinh(x) hyperbolic sine of x
cosh(x) hyperbolic cosine of x
tanh(x) hyperbolic tangent of x
Other functions
exp(x) e to the power of x (ex)
ceil(x) x rounded up to the nearest integer.
floor(x) x rounded down to the nearest integer
fabs(x) absolute value |x|
log(x) Natural logarithm of x, x>0.
log10(x) Base 10 logarithm x, x>0.
fmod(x,y) Remainder of x/y
sqrt(x) square root of x, x>=0.
pow(x,y) x to the power y.
Control statements enable us to specify the flow of program control; ie, the order in
which the instructions in a program must be executed. They make it possible to make decisions,
to perform tasks repeatedly or to jump from one section of code to another.
Ch. Vijayanand@Dept. Of
CSE
(Variable/ Expression/ Constant) operator ( Variable/ Expression/ Constant)
Some examples of expressions are given below.
1. (num%2==0)
2. (year%4==0)
3. (a>b)
4. (sum==num)
5. (per>=80)
6. (num!=0)
7. (num>10)
8. (num<=10).
Syntax: Flowchart
if(test expression )
{
statement-block;
}
statement - x;
If the test expression is true then the statement-block will be executed; otherwise the statement
block will be skipped and the execution will jump to the statement-x. Remember, when the
condition is true both the statement-block and the statement-x are executed in sequence.
Ex 1: Write a program „C‟ to check whether the given number is +ve or –ve using simple
if statement.
#include<stdio.h>
int main()
{
int num;
printf("Enter a number:");
scanf("%d”, &num);
if(num>0)
Ch. Vijayanand@Dept. Of
CSE
Output:
Enter a number: 9
9 is a positive number.
if(test expression )
{
statement block - 1;
}
else
{
statement block - 2;
}
statement-x;
If the test expression is true, then statement block – 1 is executed and statement block-2 is
skipped. Otherwise, the statement-2 is executed. In both the cases, the control is transferred
subsequently to the statement-x.
Ex 2: Write a program „C‟ to check whether the given number is even or odd using if..else
statement.
#include<stdio.h>
int main()
{
int num;
printf("Enter a number:");
scanf("%d",&num);
if(num%2==0)
printf("%d is even number\n",num);
else
printf("%d is odd number\n",num);
return 0;
}
Output:
Enter a number: 8
8 is even number.
Ex 3: Write a „C‟ program to check whether the given year is leap or not using if..else
statement.
.#include<stdio.h>
int main()
{
int year;
printf("Enter any year:");
Ch. Vijayanand@Dept. Of
CSE
scanf("%d",&year);
if(year%4==0)
printf("%d is leap year\n", year);
else
printf("%d is non leap year\n", year);
return 0;
}
Output:
Enter any year: 1996
1996 is leap year.
Syntax: Flowchart:
if (test expression 1)
{
if (test expression 2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
}
statement-x;
If the test expression1 is false, the statement-3 will be executed; otherwise it continues
to perform the second test. If the test expression-2 is true, the statement-1 will be executed.
Otherwise the statement-2 will be executed and then the control is transferred to the statement-
x.
Ex 4: Write a C program to find the biggest among three numbers using nested-if statement.
#include<stdio.h>
int 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("%d is the big\n",a);
Ch. Vijayanand@Dept. Of
CSE
else
printf("%d is the big\n",c);
}
else
{
if(b>c)
printf("%d is the big\n",b);
else
printf("%d is the big\n",c);
}
return 0;
}
Output:
Enter a, b, c values: 9 5 17
17 is the big
All the conditions are evaluated one by one starting from top to bottom, if any one of
the condition evaluating to true then statement group associated with it are executed and skip
other conditions. If none of expression is evaluated to true, then the statement or group of
statement associated with the final else is executed.
Flowchart
Ch. Vijayanand@Dept. Of
CSE
The following program demonstrates a legal if-else if statement: In this program we
assign grades to students according to the marks they obtained, using else-if ladder statement.
Output
Enter marks of 5 subjects: 90 90 88 86 84
Total marks = 438
Aggregate = 87
Grade: Excellent
Ch. Vijayanand@Dept. Of 6
CSE
The switch statement
A switch statement is also a multi-way decision making statement that is a simplified
version of if..else..if block that evaluates a single variable. The syntax of switch statement is:
switch(variable)
{
case constant 1:
statements;
break;
case constant 2:
statements;
break;
case constant N:
statements;
break;
default:
default statement;
}
Output
Simple Calculator
1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter your choice(1..4): 2
Enter a,b values: 12 7
12 – 7 = 5
Looping Structures
The programmer sometimes interested to repeat a set statements a number of times. This is
known as looping in a computer program. A loop is a group of instructions that computer
executes repeatedly while some loop continuation conditions remains true. Two ways of
repetitions are possible:
1. Counter controlled loops
2. Sentinel controlled loops
(In computer programming, data values used to signal either the start or end of a data series
are called sentinels)
Counter controlled loops are sometimes called „definite loops‟ because we know in advance
exactly how many times the loop will be executed.
Sentinel controlled loops are sometimes called „indefinite loops‟ because it is not known in
advance how many times the loop will be executed.
Repetition structure has four required elements:
1. Repetition statement (while, for, do..while )
2. Condition to be evaluated
3. Initial value for the condition
Ch. Vijayanand@Dept. Of 8
CSE
UNIT-II COMPUTER PROGRAMMING
4. Loop termination
C supports the following types of loops:
1. The while loop
2. The do..while loop
3. The for loop
Advantages
✓ Reduce length of Code
✓ Take less memory space.
✓ Burden on the developer is reducing.
✓ Time consuming process to execute the program is reduced.
The body of the loop will be executed repeatedly till the value of test expression
becomes false (0). The initialization of a loop control variable is generally done before the loop
separately.
syntax:
Flowchart
Output: 1 2 3 4 5 6 7 8 9 10
Output
Enter a number to be reversed: 1234
The reverse number is: 4321
Ch. Vijayanand@Dept. Of 10
CSE
}
Output
Enter a number: 153
153 is Armstrong
do..while Statement
do-while loop is similar to while loop, however there is one basic difference between
them. do-while runs at least once even if the test condition is false at first time. Syntax of do
while loop is:
Syntax Flowchart
do
{
body of the loop;
}
while (expression);
statement -x;
Output: 1 2 3 4 5
Flowchart
Ch. Vijayanand@Dept. Of
CSE
The loop header contains three parts:
o an initialization,
o a test condition, and
o incrementation(++) / decrementation(˗ ˗) /update.
Initialization: This part is executed only once when we are entering into the loop first time.
This part allows us to declare and initialize any loop control variables.
Condition: if it is true, the body of the loop is executed otherwise program control goes outside
the for loop.
Increment or Decrement: After completion of initialization and condition steps loop body code
is executed and then increment or decrements steps is execute. This statement allows to us to
update any loop control variables.
✓ Then, the test expression is evaluated. If the test expression is false, for loop is
terminated. But if the test expression is true, codes inside the body of for loop is
executed and the update expression is executed. This process repeats until the test
expression becomes false.
Note: In for loop everything is optional but mandatory to place two semicolons (; ;)
Ex 11: Write a C program to check whether the given number is prime or not.
#include<stdio.h>
int main( )
{
int n,i,fact=0;
printf("Enter a number:");
scanf("%d",&n);
for (i=2;i<n/2;i++)
{
if(n%i == 0)
fact++;
}
if(fact == 0)
printf("%d is Prime\n",n);
else
printf("%d is not a Prime\n",n);
return 0;
}
Output
Enter a number: 13
13 is Prime.
Ex 12: Write a C program to print the factorial of a given number.
#include<stdio.h>
int main( )
{
int n,i;
Ch. Vijayanand@Dept. Of
CSE
long int fact=1;
printf("Enter a number:");
scanf("%d",&n);
for (i=1;i<=n;i++)
{
fact = fact*i;
}
printf("Factorial of %d is %ld\n", n, fact);
return 0;
}
Output
Enter a number: 5
Factorial of 5 is 120
Comparison between for and do, while loops
S.No For loop Do-while loop
1 Generally deterministic in nature Non-deterministic in nature
Loop index can be initialized and altered Index will be initialized outside the loop
2 with in loop
Very flexible in nature Not so flexible when compared with for
3 loop
Condition is checked at beginning of the Same in case of while loop. In do loop,
4 loop condition is checked after end of the
loop
Minimum iterations are zero Minimum iterations are zero (while)
5 Minimum iterations are one (do-while)
Pre-test loop: The condition can be tested- At the beginning is called as pre-test or entry-
controlled loop. Example: while and for loops.
Post-test loop: The condition can be tested - At the end is called as post-test or exit-
controlled loop. Example: do-while loop.
Nested loops
Insertion of one loop statement inside another loop statement is called nested loop.
Generally for loops are nested. In C loops can be nested to any desired level. General syntax
for nested for loops are:
Ch. Vijayanand@Dept. Of
CSE
printf("Enter number of rows:" );
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
printf("* ");
}
printf("\n");
}
return 0;
}
Output:
Enter number of rows: 5
*
* *
* * *
* * * *
* * * * *
Output
Enter number of rows: 5
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Ch. Vijayanand@Dept. Of
CSE
printf("Enter number of rows:" );
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
printf("%d ",k++);
}
printf("\n");
}
return 0;
}
Output
Enter number of rows: 5
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Ch. Vijayanand@Dept. Of
CSE
}
return 0;
}
Output
1 2
Ch. Vijayanand@Dept. Of
CSE
The goto statement is often combined with if statement to cause a conditional transfer of
control.
Output
Enter a number (999 for exit): 1
Enter a number (999 for exit): 3
Enter a number (999 for exit): -1
Enter a number (999 for exit): 7
Enter a number (999 for exit): 999
Sum of the numbers entered by the user is 11
Ch. Vijayanand@Dept. Of
CSE