0% found this document useful (0 votes)
23 views41 pages

CP Unit 2

This document provides an overview of C programming language. It discusses the history and evolution of C from earlier languages like ALGOL and BCPL. C was created by Dennis Ritchie at Bell Labs in 1972 and became more popular after the 1978 publication of The C Programming Language book. The document then describes the basic structure of a C program, which includes documentation, include, define, and main sections. It also covers C character set, tokens, keywords, variables, and constants. The document provides a high-level introduction to key concepts in C programming.

Uploaded by

sandeepsai2508
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views41 pages

CP Unit 2

This document provides an overview of C programming language. It discusses the history and evolution of C from earlier languages like ALGOL and BCPL. C was created by Dennis Ritchie at Bell Labs in 1972 and became more popular after the 1978 publication of The C Programming Language book. The document then describes the basic structure of a C program, which includes documentation, include, define, and main sections. It also covers C character set, tokens, keywords, variables, and constants. The document provides a high-level introduction to key concepts in C programming.

Uploaded by

sandeepsai2508
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

UNIT –II COMPUTER PROGRAMMING

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.

Fig: Taxonomy of C language

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.

3. Basic Structure of C program:-

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. //

ii. Link section


The link section provides instructions to the compiler to link functions from the system
library.

#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.

iii. Definition section


The definition section defines all symbolic constants. #define PI 3.1413

iv. Global declaration section


There are some variables that are used in more than one function. Such variables are
called global variables and are declared in the global declaration section that is outside of all
the functions. This section also declares all the user-defined functions.

v.main() function section


Every C program must have one main function section. This section contains two
parts:
1. Declaration part: It declares all the variables used in the executable part.
2. Executable part: There is at least one statement in the executable part.

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.

vi. Subprogram section


The subprogram section contains all the user-defined functions that are called in the
main () function. User-defined functions are generally placed immediately after the main ()
function, although they may appear in any order.
For Example a ‘C’ program that prints welcome message:

#include<stdio.h>
int main( )
{
printf(“Welcome to C Programming\n”);
return 0;
}

Output
Welcome to C Programming
3
UNIT –II COMPUTER PROGRAMMING

Language consists of:

4. Character Set:- the characters in C are grouped into following categories:


✓ Letters:
Uppercase ----> A, B, -------- , Z
Lowercase ----> a, b, --------- , z
✓ Digits: 0,1,2,3,4,5,6,7,8,9
✓ Special Characters: +, _, /, %, <, >, ^, &, *, {, }, (, ) ........... soon
✓ White Spaces:
White spaces
Meaning Result
Backspace Moves the cursor to the previous position of the current
\b line.
\a Bell(alert) Produces a beep sound for alert
\r Carriage return Moves the cursor to beginning of the current line.
\n New line Moves the cursor to beginning of the next line.
\0 Null Null character
\v Vertical tab Moves the cursor to next vertical tab position.
\t Horizontal tab Moves the cursor to next horizontal tab position.
\\ Backslash Present a character with backslash(\)

5. Tokens: - A valid character or a group of characters are called as Tokens. It is an atomic


unit of source 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”

Special Symbols: all symbols which are placed in a keyboard device.


Ex: +, _, / , %, <, >, ^, &, *, {, }, (, ), !, @, #, $, ^, -, =, ~, `, [, ], |, \, :, ;, ”, ’, ., ?,

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:

Data Type Memory Size Range Format Specifier


-2 to 215-1
15
%d
int 2B
(-32768 to 32767)
-27 to 27-1 %d
short int 1B (-128 to 127)
-231 to 231-1 %u
long int 4B (-2147483648 to
2147483647)
0 to 216-1 %u
unsigned int 2B (0 to 65535)
0 to28-1 %d
unsigned short int 1B
(0 to 255)
0 to 232-1 %u
unsigned long int 4B
(0 to 4294967295)

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

Data type Memory Size Range Format Specifier


Float 4B 3.4E-38 to 3.4E+38 %f
Double 8B 1.7E-308 to 1.7E+308 %lf
long double 10B 3.4E-4932 to 1.1E+4932 %lf

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:

Symbol Name Meaning


: Colon Used for label
; Semicolon End of statement
() Parenthesis Used in expression
[] Square brackets Used in expression
{} Curly braces Used for block of statements
# Hash Pre-processor directive
, Comma Variable separator

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.

ii. Character variables


Character variables can include any letter from the alphabet or from ASCII chart and
numbers 0-9 that are given within single quotes.

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: /* write a ‘C’ program to perform arithmetic operations. */


#include<stdio.h>
int a=10,b;
main()
{
int c,d,e,f,g;
printf(“enter b value”);
scanf(“%d”,&b);
c=a+b;
d=a-b; e=a*b; f=a/b; g=a%b;
printf(“%d\n%d\n%d\n%d\n%d”,c,d,e,f,g);
}
Output: enter b value 3
12
6
18
3
0
2. Relational operators
A relational operator, also known as a comparison operator, is an operator that
compares two operands. Relational operators always return either true (1) or false (0)
depending on the relation between two operands. C has six relational operators.
Ex:
Operator Meaning Example
< Less than a<b (3<5) gives 1
> Greater than a>b (7>9) gives 0
<= Less than or equal to a<=b (100<=100) gives 1
>= Greater than or equal to a>=b (50>=100) gives 0
== Equal to a==b (10==9) gives 0
!= Not equal to a!=b (10!=9) gives 1

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

Ex: a=10, b=20, c=10 Relation1 = (a<=b), relation2 = (a==c)


Condition is – (a<=b) && (a==c); relation1 produce 1(t), relation2 produce 1(t).
Then 1 && 1 is 1(t).
Program: /* ‘C’ program that illustrates the use of logical operators */
#include<stdio.h>
main()
{
int a=10, b=20, c=10;
if((a<=b)&&(a==c)
{
printf(“true”)
}
else {
printf(“false”);
}
}
Output: true

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.

ii. Increment (++) and decrement (− −) operators


The increment operator is unary operator that increases value of its operand by 1.
Similarly, the decrement operator decreases value of its operand by 1. These operators are
unique in that they work only on variables not on constants. These are used in loops like while,
do-while and for statements.
There are two ways to use increment or decrement operators in expressions.
-- If you put the operator in front of the operand (prefix),
-- If you put the operator after the operand (postfix),

Operator Name Value returned Effect on variable


x++ Post-increment x Incremented
++x Pre-increment x=x+1 Incremented
x− − Post-decrement x Decremented
− −x Pre-decrement x=x - 1 Decremented

Ex: int x=6, y;


y=x++ // x=7, y=6 in post increment value can be incremented after assignment
y=++x // x=8, y=8 in pre increment value is incremented then assigned
y=x- - // x=7, y=8 in post decrement value can be decremented after assignment
y=--x // x=6, y=6 in pre decrement value is decremented then assigned
Program: /* write a c program that illustrates the use of unary operators */
#include<stdio.h>
int main()
{
int x=5;
printf("x=%d\n", x++);
printf("x=%d\n",++x);
printf("x=%d\n", x--);
printf("x=%d\n",--x);
printf("x=%d\n",-x);
return 0;
}
Output x=5 x=7 x=7 x=5 x= -5

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(>>)

1. Bitwise AND (&)


When we use the bitwise AND operator, the bit in the first operand is ANDed with the
corresponding bit in the second operand. If 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 0

100 (binary equivalent of decimal 4)


&010 (binary equivalent of decimal 2)
000

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

100 (binary equivalent of decimal 4)


| 01 0 (binary equivalent of decimal 2)
110

3. Bitwise XOR (^)


When we use the bitwise XOR operator, the bit in the first operand is XORed with the
corresponding bit in the second operand. If both bits are same, the corresponding bit in the
result is 0 and 1 otherwise. In a C program, the | operator is used as follows. The truth table
operator is shown below:

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

4. Bitwise NOT (~)


One’s complement operator (Bitwise NOT) is used to convert each 1 to 0 and 0 to 1,
in the given binary pattern. It is a unary operator i.e. it takes only one operand. In a C program,
the ~ operator is used.
Ex:
int a=4,c;
c=~a;
printf(“%d”,c); //prints -5

~100 (binary equivalent of decimal 4)


101

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:

operand operator num


where the bits in operand are shifted left or right depending on the operator (<<, >>) by the
number of places denoted by num.

Left shift operator


When we apply left-shift, every bit in x (operand) is shifted to left by one place. So,
the MSB (Most Significant Bit) of x is lost, the LSB (Least Significant Bit) of x is set to 0.

Ex: Let us consider int x=4;


Now shifting the bits towards left for 1 time, will give the following result
MSB LSB
23 22 21 20
(8 4 2 1)
x=4 0 1 0 0
1 0
x<<1 => 1 0 0 0 the result of x<<1 is 8

Left-shift is equals to multiplication by 2.

5.2 Right shift operator


When we apply right-shift, every bit in x is shifted to right by one place. So, the LSB
(Least Significant Bit) of x is lost, the MSB (Most Significant Bit) of x is set to 0.
Ex: Let us consider int x=4;
Now shifting the bits towards right for 1 time, will give the following result.

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

Right-shift is equals to division by 2.

14
UNIT –II COMPUTER PROGRAMMING

Program: /* ‘C’ program that illustrates the use of bitwise operators */


#include <stdio.h>
int main()
{
int a=4,b=2;
printf("%d | %d = %d\t",a,b,a|b);
printf("%d & %d = %d\t",a,b,a&b);
printf("%d ^ %d = %d\t",a,b,a^b);
printf("~%d = %d\t",a,~a);
printf("%d<<1 = %d\t",a,a<<1);
printf("%d>>1 = %d\t",a,a>>1);
return 0;
}
Output:
4 |2=6 4&2=0 4^2=6 ~4 = -5 4 << 1 = 8 4 >> 1 = 2

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

Program: /* ‘C’ program that illustrates the use of assignment operators*/


#include <stdio.h>
int main()
{
int a = 21,c;
c = a;
printf("Operator is = and c = %d\n", c );
c += a;
printf("Operator is += and c=%d\n",c); }
Advantages:
1. Short hand expressions are easier to write.
2. The statement involving short hand operators are easier to read as they are more
concise.
3. The statement involving short hand operators are more efficient and easy to
understand.

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 */

ii. sizeof Operator


The operator sizeof is a unary operator used calculates the size of data types and
variables. The operator returns the size of the variable, data type in bytes. i.e. the sizeof
operator is used to determine the amount of memory space that the variable/data type will take.
The outcome is totally machine-dependent.
For example:
#include<stdio.h
> int main()
{
printf("char occupies %d bytes\n",sizeof(char));
printf("int occupies %d bytes\n",sizeof(int));
printf("float occupies %d bytes\n",sizeof(float));
printf("double occupies %d bytes\n",sizeof(double));
printf("long double occupies %d bytes\n",sizeof(long
double)); return 0;
}
Output
char occupies 1 bytes
int occupies 2 bytes
float occupies 4 bytes
double occupies 8 bytes
long double occupies 10 bytes
10. Expressions
In C programming, an expression is any legal combination of operators and operands
that evaluated to produce a value. Every expression consists of at least one operand and can
have one or more operators. Operands are either variables or values, whereas operators are
symbols that represent particular actions.
In the expression x + 5; x and 5 are operands, and + is an operator.

In C programming, there are mainly two types of expressions are available. They are as
follows:

17
UNIT –II COMPUTER PROGRAMMING

1. Simple expression: In which contains one operator and two operands or


constants. Ex: x+y; 3+5; a*b; x-y etc.
2. Complex expression: In which contains two or more operators and operands or
constants. Ex: x+y-z; a+b-c*d; 2+5-3*4; x=6-4+5*2 etc.

➔ Operators provided mainly two types of properties. They are as follows:


1. Operator Precedence
It definesthe order in which operators in an expression are evaluated depends on their
relative precedence. Example: Let us see x=2+2*2
1st pass- 2+2*2
nd
2 pass- 2+4
rd
3 pass- 6 that is x=6.
2. Associativity it defines the order in which operators with the same order of precedence are
evaluated.
Ex: Let us see x = 2/2*2
1st pass-- 2/2*2
nd
2 pass-- 1*2
rd
3 pass-- 2 that is x=2
The below table lists C operators in order of precedence (highest to lowest) and their
associativity indicates in what order operators of equal precedence in an expression are
applied.

S.No Operators Associativity


1 ( ) [ ] → . ++ (postfix) − −(postfix) L to R
++ (prefix) -- (prefix)! ~ sizeof(type) + (unary) − (unary) R to L
2
&(address) * (indirection)
3 */% L to R
4 +− L to R
5 <<>> L to R
6 <<= >>= L to R
7 = = != L to R
8 & L to R
9 ^ L to R
10 | L to R
11 && L to R
12 || L to R
13 ?: R to L
14 = += −= *= /= %= >>= <<= &= ^= |= R to L
15 , L to R

Program: /* operator associativity */


#include<stdio.
h> int main()
{
int a, b=4,c=8,d=2,e=4,f=2;
a=b+c/d+e*f; // expression1
printf(" The value of a is%d", a);
a=(b+c)/d+e*f; // expression2

18
UNIT –II COMPUTER PROGRAMMING

printf("The value of a is%d", a);


a=b+c/((d+e)*f); // expression3
printf("The value of a is%d", a);
return 0;
}
Output:
The value of a is 16 The value of a is 14 The value of a is 6

11. Formatted input and output functions


When input and output is required in a specified format the standard library functions
scanf() and printf() are used

Output function printf( )


printf() is a function that is used to print any data on the video monitor screen.
Syntax: printf(“control string”,list_of_variables);
The function accepts two arguments - control string, which controls what gets printed,
and list of variables.

The control string is all-important because it specifies
o The type of each variable in the list and how user wants it printed. It is also
called as format specifier.
o Characters that are simply printed as they are.
o Control string that begins with a % sign.
o Escape sequences that begin with a \ sign

List of variables must be separate by comma.

The number of format specifiers must exactly match the number of variables.
Format specifiers
Format
Data Type Display
specifier
%c Char Single character
%c unsigned char
%s Sequence of characters (String)
Int Signed integer (both +ve and –ve
%d
values)
%u unsigned int Unsigned integer (only +ve values)
%hd short int Signed short integer
%ld long int Long integer
unsigned long Unsigned long integer (only +ve
%lu Int values)
%o Int Octal values
%x Int Hexa decimal values
%f Float Floating-point value
Long Double precision floating-point
%lf float/double Value
long double Double precision floating-point
%Lf Value
%p Pointer Address stored in pointer
%% None Prints %

19
UNIT –II COMPUTER PROGRAMMING

Flag characters used in printf

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

10. char ch=’A’; printf(“%c\n%2c\n%3c\n”,ch,ch,ch);


A
A
A

11. printf(“%X\n”,255);
FF

Input function scanf()


C provides scanf( ) function for entering input data. This function accepts all types of
data as input (numeric, character, string).
Syntax: scanf(“control string”,variable1,variable2,…,variable n);
This function should have at least two parameters.
-First parameter is control string which is conversion specification character. It should
be within double quotes. This may be one or more, it depends on the number of
variables.
-The other parameter is variable names.
Each variable must preceded by ampersand (&) sign. This gives starting address of the
variable name in memory. scanf ( ) uses all the format specifiers used in printf( ) function.
Note: comments are not allowed in scanf()

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

12. Type Conversion


Type casting: Type casting is a way to convert a variable from one data type to
another data type. It can be of two types:
1. Implicit type casting
2. Explicit type casting

i. Implicit type casting


When the type conversion is performed automatically by the compiler without
programmer’s intervention, such type of conversion is known as implicit type conversion or
type promotion. In this, all the lower data types are converted to its next higher data type.
If the both operands are of the same type, promotion is not needed. If they are not,
promotion follows these rules:

float operands are converted to double.

char or short are converted to int.

If anyone operand is double, the other operand is also converted to double, and that
is the type of result.
or

If anyone operand is long, the other operand is also converted to long, and that is the
type of result.

If anyone operand is unsigned, the other operand is also converted to unsigned, and
21
UNIT –II COMPUTER PROGRAMMING

that is the type of result.


The smallest to the largest data types with respect to size are given as follows:

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.

13. Mathematical Functions in C


The mathematical functions such as sin, cos, sqrt, log etc., are frequently used in
analysis of real-life problems. Most of the C compilers support these basic math functions
using #include<math.h> header file. The following Table lists some standard math functions

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.

Program: /* ‘C’ program that illustrates the use mathematical functions


*/ #include <stdio.h> #include <math.h> int main()
{
printf("sin 90 = %.0f",sin(90));
printf("cos 0= %.0f",cos(0));
printf("sqrt(9) = %.0f",sqrt(9));
printf("floor(9.56) = %.2f\n",floor(9.56));
printf("ceil(9.56) = %.2f",ceil(9.56));
printf("abs(-9) = %.2f",fabs(-9));
printf("power(2,3) = %.0f",pow(2,3));
return 0;
}
Output: sin 90 = 1 cos 0= 1 sqrt(9) = 3
floor(9.56) = 9.00 ceil(9.56) = 10.00 abs(-9) = 9.00 power(2,3) = 8
Control Statements in C
Statements
✓ The statements of a C program control the flow of program execution.
✓ A statement is a command given to the computer that instructs the computer to take a
specific action, such as display to the screen, or collect input.
✓ A computer program consists of a number of statements that are usually executed in
sequence. Statements in a program are normally executed one after another.

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.

Control statements in C programming language are divided into two types.


1. Selection/ Branching statements (also called Decision making statements) and
2. Iteration/ Looping statements (also called Repetitive statements).

✓ Branching is deciding what actions to take and


✓ Looping is deciding how many times to take a certain action.

Selection/ Branching statements are again divided into two types.


1. Conditional statements:(if,if-else, nested if-else, else-if ladder, switch and
conditional expression/conditional operator)
2. Unconditional statements ( break, continue,goto and exit)

Iteration/ Looping(Repetitive) statements are as follows:There are three types of loops in C


programming:
1. while loop
2. do..while loop
3. for loop
Specifying Test Condition for Selection and Iteration
A test condition used for selection and iteration is expressed as a test expression. If an
expression evaluates to true, it is given the value of 1. If a test expression evaluates to false, it
is given the value of 0.
✓ Relational and Logical operators are available to specify the test condition used in the
control statements of C.
✓ Relational operators are used to specify individual test expression.
✓ Logical operators are used to connect more than one test expression.
Relational Operators
To Specify Symbol Logical Operators
Used
Less than < To Specify Symbol
Less than or equal to <= Used
Greater than > Logical AND &&
Greater than or equal >= Logical OR ||
to Logical NOT !
Equal to ==
Not equal to !=

Writing Test Expression


Test condition is specified with test expression. The syntax of the test expression for
specifying the test condition is as follows:

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).

Selection/ Branching statements


The simple if
This 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 in conjunction with an
expression. It takes the following form:

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)

printf(“%d is a positive number\n”, num);


}
return 0;
}

Ch. Vijayanand@Dept. Of
CSE
Output:
Enter a number: 9
9 is a positive number.

The if..else statement


The if..else statement is an extension of the simple if statement. The general form is:
Syntax Flowchart

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.

Nested if..else statement


When a series of decisions are involved, we may have to use more than one if..else statement
in nested form. Nested if means one if statement with in another if statement.

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

Multi-way Branching statements


In some situations we may like to have more than two possible paths for program flow.
In such cases else..if or switch statement may be used.

The if..else..if/Ladder if statement


This is the multi-way selection statement (i.e. used to test multiple conditions). The
syntax is:
if(test expression 1)
{
statements block-1;
}
else if (test expression 2)
{
statements block-2;
}
.....................
.....................
else if (test expression N)
{
statement block-N;
}
else
{
default statements;
}

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.

Ex 5: Write a C program to display student grades using else..if statement.


#include<stdio.h>
int main( )
{
int s1,s2,s3,s4,s5,tot;
int aggr;
printf("Enter marks of 5 subjects:");
scanf("%d%d%d%d%d",&s1,&s2,&s3,&s4,&s5);
tot=s1+s2+s3+s4+s5;
printf("Total marks = %d\n",tot);
aggr=tot/5;
printf("Aggregate = %d\n",aggr);
if(aggr>=80)
printf("Grade: Excellent\n");
else if (aggr>=75)
printf("Grade: First class with Distinction");
else if(aggr>=60)
printf(" Grade : First Class");
else if(aggr>=50)
printf("Grade : Second Class");
else if(aggr>=40)
printf("Grade : Pass class");
else
printf("Grade: Fail");
return 0;
}

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;
}

When switch statement is executed, A variable successively matched against a list of


integer or character constants. When a match is found, a statement or block of statements is
executed where the default is executed if no matches are found. The default is optional and, if
not present, no action takes place if all matches fail.
When a match is found, the statements associated with that case is executed until the
break is encountered.
A switch statement work with only char and int primitive data types, it also works
with enumerated types and string.

Ex 6: Write a C program to implement simple calculator using switch statement.


#include<stdio.h>
int main()
{
int choice;
int a,b;
printf("Simple Calculator\n");
printf(" \n");
printf("1.Addition\n2.Subtraction\n3.Multiplication\n4.Division\n");
printf("Enter your choice(1..4):");
Ch. Vijayanand@Dept. Of 7
CSE
UNIT-III COMPUTER PROGRAMMING
scanf("%d",&choice);
printf("Enter a,b values:");
scanf("%d%d",&a,&b);
switch(choice)
{
case 1:
printf("%d+%d=%d\n",a,b,a+b);
break;
case 2:
printf("%d-%d=%d\n",a,b,a-b);
break;
case 3:
printf("%d*%d=%d\n",a,b,a*b);
break;
case 4:
printf("%d/%d=%d\n",a,b,a/b);
break;
default:
printf("Invalid choice ... !");
}
return 0;
}

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 While Loop


The while loop is a pre-test or entry-controlled loop. It uses test expression to control
the loop. The while loop evaluates (checking) the test expression before every iteration of the
loop, so it can execute zero times if the condition is initially false.

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:

while (test expression)


{
body of the loop;
}
statement-x;

Flowchart

How while loop works?


✓ Initially the while loop evaluates (checking condition) the test expression.
✓ If the test expression is true (nonzero i.e.,1), statements inside the body of while loop
is evaluated. Then, again the test expression is evaluated. The process goes on until the
test expression is false.
✓ When the test expression is false, the while loop is terminated.

Ex 7: Write a C program to print 1 to 10 numbers using while loop.


#include<stdio.h>
int main( )
{
Ch. Vijayanand@Dept. Of 9
CSE
UNIT-II COMPUTER PROGRAMMING
int n=1;
while(n<=10)
{
printf(“%d\t”,n);
n++;
}
return 0;
}

Output: 1 2 3 4 5 6 7 8 9 10

Ex 8: Write a C program to print reverse of given number using while loop.


#include<stdio.h>
int main( )
{
int n,rem;
printf("Enter a number to reversed:");
scanf("%d",&n);
printf("The reverse number is ");
while(n != 0)
{
rem = n%10;
printf("%d",rem);
n = n/10;
}
printf("\n");
return 0;
}

Output
Enter a number to be reversed: 1234
The reverse number is: 4321

Ex 9: Write a C program to check whether the given number is Armstrong or not.


#include<stdio.h>
int main( )
{
int n,rem,sum=0,temp;
printf("Enter a number:");
scanf("%d",&n);
temp=n;
while(n != 0)
{
rem = n%10;
sum = sum+(rem*rem*rem);
n = n/10;
}
if(sum == temp)
printf("%d is Armstrong\n", temp);
else
printf("%d is not an Armstrong\n", temp);
return 0;

Ch. Vijayanand@Dept. Of 10
CSE
}

Output
Enter a number: 153
153 is Armstrong

Ex 10: Write a C program for sum of individual digits of a number.


#include<stdio.h>
int main()
{
int n,rem,sum=0;
printf("enter a number:\n");
scanf("%d", &n);
while(n != 0)
{
rem=n%10;
sum=sum+rem;
n=n/10;
}
printf("The sum of individual digits is %d", sum);
return 0;
}
Output:
Enter a number: 1234
The sum of individual digits is 10

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;

How do-while loop works?


✓ First the code block (loop body) inside the braces ({….}) is executed once.
✓ Then, the test expression is evaluated (checking condition). If the test expression is true,
the loop body is executed again. This process goes on until the test expression is
evaluated to false (0).
✓ When the test expression is false, the do...while loop is terminated.
Ch. Vijayanand@Dept. Of
CSE
The following example illustrates the use of do-while loop.
#include<stdio.h>
int main()
{
int num=1;
do
{
printf( “ %d\t”, num);
num++;
}while(num<=5);
return 0;
}

Output: 1 2 3 4 5

Comparison between do and while loops


S.No While loop Do-while loop
Condition is checked before entering Condition is checked after executing
1
into loop statements in loop
2 Top-tested /entry-controlled loop Bottom-tested /exit-controlled loop
3 Minimum iterations are zero Minimum iterations are one
4 Maximum iterations are N+1 Maximum iterations are N
General loop statement but well suited
5 General loop statement for menu-driven applications
6 Non-deterministic loop Non-deterministic loop

The For Statement


It most general looping construct in C. The for loop is commonly used when the
number of iterations are exactly known. The syntax of a for loop is

for(initialization; test expression; increment /decrement/ update)


{
body of the loop;
}

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.

How for loop works?


✓ First the loop initialization statement is executed.

✓ 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:

for (initialization; test expression; updation) //outer loop


{
for (initialization; test expression; updation) //inner loop
{
body of inner for loop;
}
}

Note: generally nested for loops are used to generate patterns.

Here is an example program that uses nested loops


#include<stdio.h>
int main()
{
int n, i, j; //i and j represents rows and columns respectively

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
*
* *
* * *
* * * *
* * * * *

Ex 13: Write a C program to print the following pattern


#include<stdio.h>
int main()
{
int n, i, j; //i and j represents rows and columns respectively
printf("Enter number of rows:" );
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
printf("%d ",j);
}
printf("\n");
}
return 0;
}

Output
Enter number of rows: 5
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Ex 14: Write a C program to print the Floyd‟s triangle.


#include<stdio.h>
int main()
{
int n, i, j,k=1; //i and j represents rows and columns respectively

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

3.3. Unconditional branching statements


The break statement
In C, when break statement is encountered inside a loop, the loop is immediately
terminated, and program control is transferred to nest statement following the loop. The break
statement is widely used with for loop, while loop, do-while loop and switch statement. Its
syntax is quite simple, just type keyword break followed with a semicolon.
break;
Following figure shows the sequences in break statements

The following example illustrates the use of break;


#include<stdio.h>
int main()
{
int i=1;
while( i <= 5)
{
if (i==3)
break;
printf("%d ", i);
i = i + 1;

Ch. Vijayanand@Dept. Of
CSE
}
return 0;
}

Output
1 2

The continue statement


In C, when continue statement is encountered inside a loop, the loop is immediately
terminated, and program control is transferred to nest statement following the loop. The break
statement is widely used with for loop, while loop, do-while loop and switch statement. Its
syntax is quite simple, just type keyword continue followed with a semicolon.
continue;
Following figure shows the sequence of actions in continue statement

The following example illustrates the use of continue;


#include<stdio.h>
int main()
{
int i=0;
while(i<5)
{
i=i+1;
if (i==3)
continue;
printf("%d ",i);
}
return 0;
}
Output
1 2 4 5

The goto statement


The goto statement is used to transfers control to a specified label. Here label is an
identifier that specifies the place where the branch is to be made. Label can be any valid variable
name that is followed by a colon (:). The label is placed immediately before the statement
where the control has to be transferred.
The syntax of goto statement is:

Ch. Vijayanand@Dept. Of
CSE
The goto statement is often combined with if statement to cause a conditional transfer of
control.

The following example illustrates the use of goto;


#include<stdio.h>
int main( )
{
int n,sum=0;
read:
printf("\nEnter a number (999 for exit):");
scanf("%d",&n);
if(n != 999)
{
if(n<0)
goto read; //jump to label - read
sum += n;
goto read; //jump to label - read
}
printf("Sum of the numbers entered by the user is %d\n",sum);
return 0;
}

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

You might also like