Unit II
Unit II
Using C
( B.Tech-CSE-M & R)
Unit- II
C PROGRAMMING BASICS:
Structure of a C program, identifiers Basic data types and sizes. Constants,
Variables Arithmetic, relational and logical operators, increment and
decrement operator’s Conditional operator, assignment operator, expressions
Type conversions, Conditional Expressions Precedence andorder of evaluation,
Sample Programs.
2
Structure of a C program
Documentation:
It specifies
• the description of the program
• the name of the program
• the creation date and time of the program.
It is specified at the start of the program in the form of
comments.
// description, name of the program, programmer name,
date, time etc.
or
/*
description, name of the program, programmer name,
date, time etc.
3
*/
Structure of a C program
Preprocessor Section:
All the header files of the program will be declared in the preprocessor section of the
program.
Header files help us to access other’s improved code into our code.
A copy of these multiple files is inserted into our program before the process of
compilation.
#include:
An include directive tells the pre-processor to include the contents of the
specified file at the point in the program.
Path names must either be enclosed by double quotes or angle brackets.
Example:
#include<stdio.h>
#include<math.h> 4
Structure of a C program
Definition:
Preprocessors are the programs that process our source code before the
process of compilation.
Preprocessor directives start with the ‘#’ symbol. The #define
preprocessor is used to create a constant throughout the program.
Whenever this name is encountered by the compiler, it is replaced by the
actual piece of defined code.
#define:
ANSI C allows the declaration of constants. This directive is used to tell
the pre-processor to perform a search-and-replace operation.
Example:
#define PI 3.14159
#define Tax-rate 0.0735
6
Structure of a C program
Global Declaration:
• The global declaration section contains global variables, function
declaration, and static variables.
• Variables and functions which are declared in this scope can be used
anywhere in the program.
• Creates the global variable before main().
Example:
#include<stdio.h>
int a=50, b=40;
int main()
{
printf("a = %d and b=%d",a,b);
}
7
Structure of a C program
main() Function:
• Every C program must have a main function which is the entry point
of the C program.
• Every C program must have one and only one main function.
• Operations like declaration and execution are performed inside the
curly braces of the main program.
• The return type of the main() function can be int as well as void too.
• void() main tells the compiler that the program will not return any
value.
• The int main() tells the compiler that the program will return an
integer value.
Example:
void main()
or
int main()
8
Structure of a C program
Sub Programs:
User-defined functions are called in this section of the
program.
The control of the program is shifted to the called function
whenever they are called from the main or outside the main()
function.
These are specified as per the requirements of the
programmer.
Example:
int sum(int x, int y)
{
return x+y;
} 9
Structure of a C program
10
Structure of a C program
12
Keywords
Example:
#include<stdio.h>
int main()
{
float a, b;
printf("Showing how keywords are used.");
return 0;
}
• float and return are keywords.
• float keyword is used to declare variables.
• return is used to return an integer type value in this program.
14
Identifiers
15
Learning Objectives
16
Keyword vs Identifier
Keyword Identifier
Keywords are predefined and specific A particular name generated by the
reserved words, which hold special programmer to define a variable,
meaning. Keywords help in defining any structure, class, or function is called an
statement in the program. identifier.
A keyword begins with lowercase. In the identifier, the first character may
begin with uppercase, lowercase or
underscores.
It defines the type of entity. It classifies the name of the entity.
It can only have alphabetical characters. It can have numbers, alphabetical
characters, and underscores.
It should be lowercase. It can be both upper and lowercase.
It helps in defining a particular property It helps in locating the name of the entity.
that subsists in a computer language.
double, int, auto, char, break, and more Test, count1, high_speed, etc are examples
are examples of keywords. of identifiers.
17
Constants
Constants in C
A constant is a value assigned to the variable which will remain the same
throughout the program, i.e., the constant value cannot be changed.
There are two ways of declaring constant:
•Using const keyword
•Using #define pre-processor
Constant Example
Integer constant 10, 11, 34, etc.
Floating-point constant 45.6, 67.8, 11.2, etc.
Octal constant 011, 088, 022, etc.
Hexadecimal constant 0x1a, 0x4b, 0x6b, etc.
Character constant 'a', 'b', 'c', etc.
String constant "java", "c++", ".net", etc. 18
Constants
Types of constants
1. Numeric Constants
• Integer Constants
• Real Constants
2. Character Constants
• Single Character Constants
• String Constants
• Backslash Character Constants
19
Strings
20
Variables
❑ Types of Variables in C
local variable
global variable
static variable
22
Variables
❑ Local Variable
23
Variables
❑ Advantages:
• The same name of a local variable can be used in different
functions as it is only recognized by the function in which it is
declared.
• Local variables use memory only for the limited time when the
function is executed; after that same memory location can be
reused.
❑ Disadvantages:
• The scope of the local variable is limited to its function only and
cannot be used by other functions.
• Data sharing by the local variable is not allowed.
24
Variables
❑ Global Variable
A variable that is declared outside the function or block is called a
global variable. Any function can change the value of the global
variable. It is available to all the functions.
#include<stdio.h>
int a=50, b=40; // global variable
void main()
{
printf("a = %d and b=%d",a,b);
}
25
Variables
❑ Advantages:
•Global variables can be accessed by all the functions present in the
program.
•Only a single declaration is required.
•Very useful if all the functions are accessing the same data.
❑ Disadvantages:
26
Data Types
Variables in C are associated with the data type. Each data type requires
an amount of memory and performs specific operations.
The data type in a programming language is the collection of data with
values having fixed meanings and characteristics. Some of them are an
integer, floating points, characters, etc. Usually, programming languages
specify the range values for a given data type.
C data types are used for
Identify the type of a variable when it is declared.
Identify the type of return value of a function.
Identify the type of parameter expected by a function.
The syntax of the data type is as follows:
27
data_type variable_name;
Data Types
28
Learning Objectives
1. Integer (int): Refers to positive and negative whole numbers (without decimal),
such as 10, 12, 65, 3400, etc.
2. Character (char): Refers to all the ASCII character sets within single quotes
such as ‘a’, ‘A’, etc.
3. Floating-point (float): Refers to all the real number values or decimal points,
such as 3.14, 10.09, 5.34, etc. The precision of up to 6 digits.
4. Double (double): Used when the range exceeds the numeric values that do not
come under either floating-point or integer data type. The precision of up to 10
digits.
5. Void (void): As the name suggests, it holds no value and is generally used for
specifying the type of function or what it returns. If the function has a void type,
it means that the function will not return any value.
Modifiers are C keywords that modify the meaning of fundamental data types. It
indicates how much memory will be allocated to a variable. To adjust the memory
allocated for a variable, modifiers are prefixed with fundamental data types. C
Programming Language has four data type modifiers:
• long
• short 29
Data Types
30
Data Types
The data types that are derived from the primitive or built-in datatypes
are referred to as Derived Data Types.
31
Data Types
Example:
#include <stdio.h> Output:
int main() { Integer datatype : 10
// datatypes Character datatype : S
int a = 10; Float datatype : 2.880000
char b = 'S'; Double Float datatype :
float c = 2.88; 28.888000
double d = 28.888;
printf("Integer datatype :
%d",a);
printf("Character datatype :
%c",b);
printf("Float datatype :
%f",c);
printf("Double Float datatype
: %lf",d); 32
Data Types
#include <stdio.h>
int main() {
int numbers[5];
// Declares an integer array with a size of 5 ele
ments
// Assign values to the array elements
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
// Display the values stored in the array
printf("Values in the array: ");
for (int i = 0; i < 5; i++) { Output:
printf("%d ", numbers[i]); Values in the array: 10 20
} 30 40 50
printf("\n");
return 0;
33
}
Data Types
Example:
#include<stdio.h>
enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};
int main()
{
enum week day;
day = Wed;
printf("%d",day);
return 0;
34
}
Data Types
#include<stdio.h>
enum year{Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep,
Oct, Nov, Dec};
int main()
{
int i;
for (i=Jan; i<=Dec; i++)
printf("%d ", i);
return 0;
}
Output: 0 1 2 3 4 5 6 7 8 9 10 11
35
Data Types
36
Operators in C
❑ What is an
AnOperator?
operator is a symbol that tells the compiler to
perform a certain operation (arithmetic,
comparison, etc.) using the values provided along
with the operator.
38
Operators in C
❑ Unary Operators:
Operators that operate or work with a single operand
are unary operators. For example: Increment(++) and
Decrement(–) Operators.
Output: 11;
39
Operators in C
❑ Binary Operators:
Operators that operate or work with two operands
are binary operators. For example: Addition(+),
Subtraction(-), multiplication(*), Division(/) operators
Output: 30;
40
Arithmetic Operators
Meaning of
❑ Arithmetic Operator
Operator
Operator:
An arithmetic operator
+
addition or
unary plus
❑ Relational
A Operators:
relational operator checks the relationship between
two operands. If the relation is true, it returns 1; if the
relation is false, it returns value 0.
43
Relational Operators
Meaning Meaning
Operator of Example Operator of Example
Operator operator
5 == 3 is 5 != 3 is
Not
== Equal to evaluated != evaluat
equal to
to 0 ed to 1
❑ Logical Operators
An expression containing logical operator returns
either 0 or 1 depending upon whether expression
results true or false. Logical operators are
commonly used in decision making in C
programming
46
Logical operators
If c = 5 and d = 2
Logical AND. True
then, expression
&& only if all operands
((c==5) && (d>5))
are true
equals to 0.
If c = 5 and d = 2
Logical OR. True
then, expression
|| only if either one
((c==5) || (d>5))
operand is true
equals to 1.
47
Logical operators
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10, result; Output:
result = (a == b) && (c > b);
printf("(a == b) && (c > b) is %d \n", result); (a == b) && (c > b)
result = (a == b) && (c < b); is 1
printf("(a == b) && (c < b) is %d \n", result);
result = (a == b) || (c < b); (a == b) && (c < b)
printf("(a == b) || (c < b) is %d \n", result);
result = (a != b) || (c < b);
is 0
printf("(a != b) || (c < b) is %d \n", result); (a == b) || (c < b) is
result = !(a != b);
printf("!(a != b) is %d \n", result); 1
result = !(a == b); (a != b) || (c < b) is
printf("!(a == b) is %d \n", result);
return 0; 0
} !(a != b) is 1 !(a ==48
Logical operators
❑ Explanation of logical operator program
(a == b) && (c > 5) evaluates to 1 because both operands (a ==
b) and (c > b) is 1 (true).
(a == b) && (c < b) evaluates to 0 because operand (c < b) is 0
(false).
(a == b) || (c < b) evaluates to 1 because (a = b) is 1 (true).
(a != b) || (c < b) evaluates to 0 because both operand (a !=
b) and (c < b) are 0 (false).
!(a != b) evaluates to 1 because operand (a != b) is 0 (false).
Hence, !(a != b) is 1 (true).
!(a == b) evaluates to 0 because (a == b) is 1 (true). Hence, !(a
== b) is 0 (false).
49
Bitwise operators
❑ Bitwise Operators
During computation, mathematical operations like:
addition, subtraction, multiplication, division, etc
are converted to bit-level which makes processing
faster and saves power. Bitwise operators are used
in C programming to perform bit-level operations.
50
Bitwise operators
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
51
Bitwise operators
❑ Bitwise AND
12 = 00001100 (In #include <stdio.h>
Binary) int main()
{
25 = 00011001 (In
int a = 12, b = 25;
Binary) printf("Output = %d",
Bit Operation of 12 and a & b);
25 return 0;
00001100 }
& Output = 8
00011001
________ 53
Bitwise operators
❑ Bitwise OR
12 = 00001100 (In Binary) #include <stdio.h>
25 = 00011001 (In Binary) int main()
Bitwise OR Operation of 12 {
and 25
00001100 int a = 12, b = 25;
| printf("Output =
00011001 %d", a | b);
________ return 0;
00011101 = 29 (In decimal) }
Output = 29
54
Bitwise operators
❑ Shift Operators
There are two shift operators in C
programming:
•Right shift operator
•LeftShift
Right shift operator.
Operator:
Right shift operator shifts all bits towards right by certain
number of specified bits. It is denoted by >>.
Left Shift Operator:
Left shift operator shifts all bits towards left by a certain number of
specified bits. The bit positions that have been vacated by the left shift
operator are filled with 0. The symbol of the left shift operator is <<.
56
Bitwise operators
•The left operand specifies the value to be shifted and the right
operand specifies the number of positions that the bits in the
value have to be shifted.
a = 00010000
b=2
a << b = 01000000
a >> b = 00000100
57
Bitwise operators
❑ Assignment Operators
An assignment operator is used for assigning a value
to a variable. The most common assignment operator
is =
Operator Example Same as
= a=b a=b
+= a += b a = a+b
-= a -= b a = a-b
*= a *= b a = a*b
/= a /= b a = a/b
%= a %= b a = a%b
59
Assignment operators
#include <stdio.h>
int main()
{
int a = 5, c; Output:
c = a;
printf("c = %d\n", c);
c=5
c += a; c = 10
printf("c = %d\n", c); c=5
c -= a;
printf("c = %d\n", c);
c = 25
c *= a; c=5
printf("c = %d\n", c); c=0
c /= a;
printf("c = %d\n", c);
c %= a;
printf("c = %d\n", c);
return 0;
}
60
Conditional operators
61
Conditional operators
#include <stdio.h>
int main()
{
Output:
int age; Enter your age17
printf("Enter your age"); not eligible for
scanf("%d",&age); voting
(age>=18)? (printf("eligible
for voting")) : (printf("not eli
gible for voting"));
return 0;
}
62
Ooperator Precedence
Highest on top
The concept of operator
++ -- (Postfix)
precedence in C helps in
++ -- (Prefix)
determining which operators
* / %
will be given priority when
+ -
there are multiple operators in
<< >>
the expression.
< >
Result?? &
|
&&
||
63
Ooperator Precedence
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
+ - ! ~ ++ - -
Unary Right to left
(type)* & sizeof
Multiplicative */% Left to right
Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
= += -= *= /=
Assignment %=>>= <<= &= ^= Right to left
|=
Comma , Left to right 64
Ooperator Precedence
#include <stdio.h>
main() {
int a = 20;
int b = 10; Output:
int c = 15;
int d = 5;
Value of (a + b) * c / d is :
int e; 90
e = (a + b) * c / d; Value of ((a + b) * c) / d is
printf("Value of (a + b) * c / d is : : 90
%d\n", e );
Value of (a + b) * (c / d) is
e = ((a + b) * c) / d;
printf("Value of ((a + b) * c) / d is : %d\n" : 90
, e ); Value of a + (b * c) / d is :
e = (a + b) * (c / d); 50
printf("Value of (a + b) * (c / d) is :
%d\n", e );
e = a + (b * c) / d;
printf("Value of a + (b * c) / d is : %d\n" 66
, e );
Ooperator Precedence
67
Ooperator Precedence
68
Ooperator Precedence
69
Expressions
❑ Expressions in C?
Expressions are the combination of variables, operands, and
operators. The result would be stored in the variable once the
expressions are processed based on the operator's precedence.
❑ Example:z = a+b-(a*c)
70
Expressions
❑ Types of Expressions
Arithmetic expressions
Relational expressions
Logical expressions
Conditional expressions
71
Expressions
73
Expressions
76
Type Conversion
Syntax:
(datatype) expression
77
Type Conversion
❑ Implicit type conversion
#include<stdio.h>
Example
#include<conio.h>
void main(){ Output:
int i = 95 ; i value is 90
float x = 90.99 ; x value is
char ch = 'A' ; 90.000000
i=x; i value is 65
printf("i value is %d\n",i);
x=i;
printf("x value is %f\n",x);
i = ch ;
printf("i value is %d\n",i);
} 78
Type Conversion
#include <stdio.h>
int main()
{
int x = 10; // integer x
char y = 'a'; // character c Output:
// y implicitly converted to
int. ASCII
x = 107, z =
// value of 'a' is 97 108.000000
x = x + y;
// x is implicitly converted to
float
float z = x + 1.0;
printf("x = %d, z = %f", x, z);
return 0; 79
Type Conversion
❑ Explicit type conversion
Example
#include<stdio.h>
int main()
{
Output:
double x = 1.2;
sum = 2
// Explicit conversion from
double to int
int sum = (int)x + 1;
printf("sum = %d", sum);
return 0;
}
80
SELECTION & DECISION
MAKING
❑ Conditional Statements
A program is a set of statements which are normally executed
sequentially in the order in which they appear. This happens when no
options or no repetitions of certain calculations are necessary. However,
in practice, we have a number of situations where we may have to
change the order of execution of statements based on certain conditions,
or repeat a group of statements until certain specified conditions are
met. This involves a kind of decision making to see whether a particular
condition has occurred or not and then direct the computer to execute
certain statements accordingly.
C language possesses such decision- making capabilities by supporting
the following statements.
1) if statements
2) switch statements
3) Conditional operator statement 81
SELECTION & DECISION
MAKING
These statements are popularly known as decision-making
statements. Since these ‘control’ the flow of execution, they are
also known as control statements.
Program Control Structure: The structure of the program
which decides the order of program statements execution is
called ‘control structure’. There are three types of control
structures.
− Sequence: In this control structure, the instructions are
executed linearly from top to bottom
− Selection: This control structure makes decision according to
some predefined condition.
82
− Iteration: This control structure executes certain instructions
SELECTION & DECISION
MAKING
❑ Simple-if Statement:
The if statement is a decision making statement. It is used to control the
flow of execution of the statements and also used to test logically whether
the condition is true or false. It is always used in conjunction with
condition. If the condition is true, then the True statements are executed.
The 'True statements' may be a single statement or group of statements. If
the condition is false then the true statements are not executed, instead the
program skip past it. The condition is given
1. if (bank byisthe
balance relational operator like
zero)
==,! =, <=, >=, etc. Borrow money
2. if(room is dark)
Put on lights
3 .if(code is M)
Person is male
4 .if(age is more then 55 )
Person is retired 83
SELECTION & DECISION
MAKING
1. Write a program to determine
whether a person is eligible to vote
#include<stdio.h>
Output:
#include<conio.h> Enter the age : 19
int main() You are eligible to
{ vote
int age;
printf("Enter the age : ");
scanf("%d",&age);
if(age>=18)
{
printf("You are eligible to vote");
}
getch();
return 0;
} 84
SELECTION & DECISION
MAKING
1. Write a program to determine the character entered by the user
#include<stdio.h>
Output:
#include<ctype.h>
Enter any key : s
#include<conio.h> The User has entered a character
int main()
{
char ch;
printf("Enter any key : ");
scanf("%c",&ch);
if(isalpha(ch)>0)
printf("\n The User has entered a character");
if(isdigit(ch)>0)
printf("\nThe user has entered a digit");
if(ispunct(ch)>0)
printf("\nThe user has entered a punctuation mark..");
if(isspace(ch)>0)
printf("\nThe user has entered a white space character");
}
85
SELECTION & DECISION MAKING
❑ If-else statement
The if..else statement is an extension of the simple if statement. It is
basically two way decision making statement and always used in
conjunction with condition. It is used to control the flow of execution and
also used to carry out the logical test and then pick one of the two
possible actions depending on the logical test.
After it has been evaluated, if its value is true, statement1 is executed, otherwise
statement2 is executed.
86
Note : it's impossible for both statements to be executed in the same evaluation.
SELECTION & DECISION
MAKING
1. Write a program to find the largest of two
numbers
#include<stdio.h>
int main()
{ Output:
int a,b,large; Enter the values
printf("\nEnter the values of a and b : "); of a and b : 12 13
scanf("%d%d",&a,&b); Large = 13
if(a>b)
large=a;
else
large=b;
printf("\n Large = %d",large);
}
87
SELECTION & DECISION
MAKING
1. Write a program to find whether the
given number is even or odd
#include<stdio.h>
int main()
Output:
{
int num;
printf("Enter any number : ");
??????
scanf("%d",&num);
if(num%2==0)
printf("\n %d is an even number
",num);
else
printf("\n %d is an odd number
",num);
88
}
SELECTION & DECISION
MAKING
❑ Write a program to enter a character and then
determine whether it is a vowel or not?
Output:
??????
❑ Write a program to find whether the given year is a leap
year or not
Output:
??????
89
SELECTION & DECISION
MAKING
❑ Nested If-Else Statements
When a series of if. Else statements are occurred in a program, we can write
an entire if..else statement in another if. else statement called nesting. When
an if else included with in if.else is known as a nested if statements.
There is no limit to how many levels can be nested, but if there are more than
three, they can be difficult to read.
90
SELECTION & DECISION
MAKING
Output:
??????
91
SELECTION & DECISION
MAKING
To check if a number is less than 100 or not. If it is less than 100
then check if it is odd or even.
#include<stdio.h>
int main()
{
int n; Output:
printf("Enter a number:");
scanf("%d",&n);
if(n<100)
??????
{
printf("%d is less than 100",n);
if(n%2 == 0)
printf("%d is even",n);
else
printf("%d is odd",n);
}
else
printf("%d is equal to or greater than 100",n);
return 0;
} 92
SELECTION & DECISION
MAKING
❑ Write a program to given Number is even or odd and
Negative or zero.
Output:
??????
93
SELECTION & DECISION
MAKING
❑ Multi-way Selection
In addition to two-way selection, most programming languages provide
another selection concept known as multiway selection. Multiway selection
chooses among several alternatives. C has two different ways to implement
multiway selection: the switch statement and else-if construction.
95
SELECTION & DECISION MAKING
Marks Grade
>=90 A
75-89 B
60-74 C
50-59 D
< 50 F
96
SELECTION & DECISION MAKING
Output:
??????
97
SELECTION & DECISION MAKING
#include<stdio.h> #include<stdio.h>
int main() int main()
{ {
int day; int day;
printf("Enter day number: "); printf("Enter day number: ");
scanf("%d", &day); scanf("%d", &day);
if(day==1) if(day==1)
{ {
printf("SUNDAY."); printf("SUNDAY.");
} }
else if(day==2) else if(day==2)
{ {
printf("MONDAY."); printf("MONDAY.");
} }
else if(day==3) else if(day==3)
{ {
printf("TUESDAY."); printf("TUESDAY.");
} }
else if(day==4) else if(day==4)
{ {
printf("WEDNESDAY."); printf("WEDNESDAY.");
} }
98
SELECTION & DECISION
MAKING
❑ The Switch Statement
The switch statement is used to pick up or executes a particular group of
statements from several available groups of statements. It allows us to
make a decision from the number of choices. It is a multi-way decision
statement, it tests the value of the variable or expression against a list of
case values and when a match is found, a block of statements associated
with that case is executed.
99
SELECTION & DECISION
MAKING
100
SELECTION & DECISION
MAKING
#include <stdio.h>
int main()
{
char gender; Output:
printf("Enter Gender Enter Gender
code:(M/F)"); code:(M/F)F
scanf("%c",&gender); Female
switch(gender)
{
case 'M':printf("Male");
break;
case 'F':printf("Female");
break;
default:printf("Wrong 101
SELECTION & DECISION
MAKING
1. Program to print Today's
name of the Day by using
switch case statement.
Output:
Enter a Number : 1
Today is Monday
102
SELECTION & DECISION
MAKING
1. Write a program in C
which is menu driven
program to compute
the area of the various
geometrical shape
Output:
1.Area of circle
2.Area of rectangle
3.Area of triangle
4.Area of Square
Enter your choice : 4
❑ Loops
The loop is defined as a block of statements which are repeatedly executed for a
certain number of times. There are two types of loop statements available: Those
loops which checks the test condition at the entry level itself, and the other checks
test condition at the exit level. The loop in a program consists of two parts, one is
the body of the loop and another is the control statement. The control statement is
used to test the condition and then directs the repeated execution of the
statements in the body of the loop.
104
ITERATION
❑ PRETEST AND POST-TEST
LOOPS
In a pretest loop, the condition is checked before we start and at the
beginning of each iteration. If the condition is true, we execute the code, if
the condition is false, we terminate the loop.
In the post-test loop, we always execute the action at least once. The loop
control expression is then tested. If the expression is true, the loop
repeats, if the expression is false, the loop terminates.
105
ITERATION
106
ITERATION
107
ITERATION
Example 1 :
#include <stdio.h>
int main ()
{ Output:
/* local variable definition */ value of a: 10
int a = 10; // Initialization or a is value of a: 11
called as counter variable value of a: 12
/* while loop execution */ value of a: 13
while( a < 20 ) // condition or loop value of a: 14
value of a: 15
{
value of a: 16
printf("value of a: %d\n", a); //body value of a: 17
of the loop value of a: 18
a++; value of a: 19
}
return 0; 108
}
ITERATION
153 = (1*1*1)+(5*5*5)+(3*3*3)
where:
(1*1*1)=1
(5*5*5)=125
(3*3*3)=27
So:
1+125+27=153 109
ITERATION
#include<stdio.h>
int main()
{
int n,r,sum=0,temp;
printf("enter the number ="); Output:
scanf("%d",&n);
temp=n;
while(n>0)
{
?????
r=n%10;
sum=sum+(r*r*r);
n=n/10;
?
}
if(temp==sum)
printf("%d is armstrong number ",temp);
else
printf("%d is not armstrong number",temp);
return 0;
} 110
ITERATION
❑ Write a C program to check whether a given number is
palindrome number or not.
A palindrome number is a number that is same after reverse. For example
121, 34543, 343, 131, 48984 are the palindrome numbers.
111
ITERATION
#include<stdio.h>
int main()
{
int n,r,sum=0,temp;
printf("enter the number="); Output:
scanf("%d",&n);
?????
temp=n;
while(n>0)
{
r=n%10;
}
sum=(sum*10)+r;
n=n/10; ?
if(temp==sum)
printf("%d is a palindrome number ",temp);
else
printf("%d is not palindrome",temp);
return 0;
}
112
ITERATION
❑ do...while loop
The do-while loop is similar to the while loop with one
important difference. The body of do-while loop is executed at
least once. Only then, the test expression is evaluated.
do
{
// the body of the loop
}
while (testExpression);
113
ITERATION
❑ For Loop
The for loop is another repetitive control structure, and is used to execute
a set of instructions repeatedly until the condition becomes false. The
assignment, incrimination or decrementation and condition checking is
done in for statement only, where as other control structures are not
offered all these features in one statement.
For loop has three parts:
1. Initialize counter.
2. Test condition is used to initialize counter variable.
3. Increment/decrement is used to increment or decrement counter
variable.
115
ITERATION
❑ For Loop
116
ITERATION
❑ Write a program in C to display n terms of natural number and their
sum.
#include <stdio.h>
void main()
{
Output:
int i,n,sum=0;
Input Value of terms : 5
printf("Input Value of terms : ");
scanf("%d",&n);
The first 5 natural
printf("\nThe first %d natural numbers
numbers are:
are:\n",n);
12345
for(i=1;i<=n;i++)
The Sum of natural
{ numbers upto 5 terms : 15
printf("%d ",i);
sum+=i;
}
printf("\nThe Sum of natural numbers upto %d
terms : %d \n",n,sum);
117
ITERATION
1. Write a C program to calculate the factorial of a given
number.
Factorial of a positive integer (number) is the sum of multiplication of all the
integers smaller than that positive integer. For example, factorial of 5 is 5 * 4 * 3 *
2 * 1 which equals to 120.
#include <stdio.h>
void main()
{
int i,f=1,num;
printf("Enter the number : "); Output:
scanf("%d",&num); Enter the number : 5
for(i=1;i<=num;i++) The Factorial of 5 is: 120
{
f=f*i;
}
printf("The Factorial of %d is: %d\n",num,f);
}
118
ITERATION
1. Write a program in C to display the pattern like right angle triangle
with a<stdio.h>
#include number.
void main()
{
int i,j,rows;
printf("Enter number of rows : Output:
"); Enter number of rows : 5
scanf("%d",&rows); 1
for(i=1;i<=rows;i++) 12
{ 123
for(j=1;j<=i;j++) 1234
{ 12345
printf("%d",j);
}
printf("\n");
}
119
}
ITERATION
The Fibonacci sequence is a sequence where the next term is the sum of the
previous two terms. The first two terms of the Fibonacci sequence are 0
followed by 1.
#include<stdio.h>
int main()
{
int n1=0,n2=1,n3,i,number;
printf("Enter the number of elements:"); Output:
scanf("%d",&number); Enter the number
printf("\n%d %d",n1,n2); //printing 0 and 1 of elements:5
for(i=2;i<number;i++) //loop starts from 2 because 0 and 1 are
already printed 01123
{
n3=n1+n2;
printf(" %d",n3);
n1=n2;
n2=n3;
}
return 0;
}
120
ITERATION
The Break
The Continue
Statement
Statement 121
ITERATION
❑ THE BREAK
STATEMENT
❑ The break statement is used to terminate the loop.
123
ITERATION
124
ITERATION
#include<stdio.h>
int main()
{
int a=0; OUTPUT
while(a<10) Statement 1
{
a++; Statement 2
if(a==5) Statement 3
break;
Statement 4
printf("\nStatement End of Program.
%d",a);
}
printf("\nEnd of Program.");
}
125
ITERATION
❑ THE CONTINUE
STATEMENT
❑The continue statement skips the current iteration of the
loop & continue with the next iteration.
Syntax : continue;
126
ITERATION
127
ITERATION
128
ITERATION
#include<stdio.h> OUTPUT
int main()
Statement 1
{
int a=0;
Statement 2
while(a<10) Statement 3
{ Statement 4
a++; Statement 6
if(a==5) Statement 7
continue; Statement 8
printf("\nStatement %d",a); Statement 9
}
Statement 10
printf("\nEnd of Program.");
} End of Program.
129
ITERATION
131
ITERATION
#include <stdio.h>
int main()
{
int i,sum=0;
for(i = 1; i<=10; i++)
{
sum = sum+i;
if(i==7) OUTPUT
{ Sum = 28
goto addition;
}
}
addition:
printf("Sum = %d", sum);
return 0;
}
132
ITERATION
134
ITERATION
int count;
for( count=1; count<=100; count++)
printf("%d",count);