Introduction to C-programming
Introduction to C-programming
22-08-2024
PROGRAM BASICS
PROGRAM BASICS
▪Basic structure of C program: Character set, Tokens, Identifiers in C,
Variables
and Data Types , Constants, Console IO Operations, printf and scanf
Relational and
Logical Operators, Conditional operator, size of operator, Assignment
operators and Bitwise Operators. Operators Precedence
Branching using goto statement, While Loop, Do While Loop, For Loop,
3
Break and
C PROGRAM
INTRODUCTION
●
Martin Richards developed a language and
named it as BCPL(Basic Combined Programming
Language).
●
Ken Thomson developed a new language by
modifying BCPL and
is named it a B, the first letter of BCPL.
●
Dennis Ritchie modified the B language and is
named it as C.
●
C is the next letter in BCPL
●
C is the next letter coming after B in
alphabetical order also
4
C PROGRAM
INTRODUCTION
●
C is a high level programming language
●
C also supports low level programming
features
●
Bit-wise operations
● Register operations
●
Accessing memory locations using
● pointers
So it can be termed as a middle level language.
●
C is a structured programming language.
●
Programs written in C are efficient and fast.
●
It was actually developed as a language for writing
efficient
programs in UNIX systems. 5
▪A C program is divided into different sections. There are six main
sections a basic c program. The six sections are,
▪Documentation
▪Link
▪Definition
▪Global Declarations
▪Main functions
▪Subprograms
6
STRUCTURE OF A C
PROGRAM
7
A sample C
program
//Program to add two
numbers
#include<stdio.h>
int main()
{
int d_num1,d_num2,d_sum;
scanf("%d
%d",&d_num1,&d_num2);
d_sum=d_num1+d_num2;
based on
a set of rules called grammars.
1
0
CHARACTER
SET
▪Every language contains a set of characters used to
✓ 1. Alphabets
✓ 2. Digits
✓ 3. Special characters
1
1
Alphabe
ts
▪C language supports all the alphabets from the English language.
Lower
and upper case letters together support 52 alphabets.
Digits
▪C language supports 10 digits which are used to construct
numerical
values in C language.
▪ Digits - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 1
2
Special Symbols
▪Special Symbols are + - * / % = & % # ~ !
()[]{}
_ ^ , ; . < > ? \ | ‘ “ blank space.
▪Space , tab and newline are called white
space
characters
1
3
1
4
TOKE
N
Every C program is a collection of instructions and every
▪
1
5
▪In a c program tokens are of the following
types:
➢ 1. Keywords
➢ 2. Identifiers
➢ 3. Constants
➢ 4. Strings
➢ 5. Special Symbols
➢ 6. Operators
1
6
Keywor
ds Keywords are specific reserved words in C each of which has a
●
specific
feature associated with it.
●
They are having special predefined
meaning.
▪Keywords are always in
lowercase.
1
7
Identifi
er
▪An identifier is a collection of characters which acts as the name of
-
Can be of any length, ANSI C recognizes first 31
characters.
-Keywords can not be used as
identifiers.
Case sensitive 1
8
Identifi
er
▪Examples for valid
identifiers
●
A, sum, Sum_of_Numbers, Avg2,
_int, FOR
▪Examples for Invalid
identifiers
●
2to - starts with a
●
4 digit Special
A-b charater -
▪ Mark, mark, MARK - Represents 3
-
identifiers.
1
9
Data Types
▪Data types in the c programming language are used to specify what kind
of
value can be stored in a variable.
requires a
single byte of memory in almost all compilers.
➢ int: As the name suggests, an int variable is used to store a decimal integer. It
➢ float: It is used to store real numbers (numbers with floating point value)
with
single precision. It requires 4 bytes of memory.
➢ double: It is used to store floating point numbers with double precision. Memory
required is 8 bytes.
2
➢ Size varies from one compiler to another. 1
Data Type Qualifiers
in C
➢ Data type qualifiers
are :
●
short,
long
●
signed,
unsigned
➢ Usage is
:
●
short -2
int bytes
●
long int - 4 bytes (or 8 bytes)
●
signed int - same as int (-ve and +ve)
●
unsigned int - 0 to maximum
➢ The datatype int will sometimes be same as either short int or long 2
int. 2
Data Type Qualifiers
in C
➢ sizeof(short int) <= sizeof
(int)
➢ ●
signed
Qualifiers with char - value (-128 to
char +127)
●
unsigned char - value
( 0 to 255)
long
➢ The data type double can also be qualified double.
➢ using qualifiers are keywords
These
in C.
2
3
2
4
void data
type
▪The void data type means nothing or no value.
▪Generally, the void is used to specify a function which does not return
any
value.
▪We also use the void data type to specify empty parameters of a
function.
2
5
Variabl
es
▪ A variable is an identifier that is used to represent some specified
locations where
the user can store different values of the same datatype during the
program execution.
2
6
2
7
Declarati
on
▪A declaration associates a group of variables with a specific data type.
▪All variables must be declared before they can appear in executable statements.
ending with
a semicolon.
▪General form is :
▪ datatype identifier-1, identifer-2, ....,
identifier-n;
▪ Example
s:
●
int number, mark,
sum;
●
float average;
●
char flag;
2
8
Declarati
on
▪Initial values can be assigned to variables within a type declaration.
variable
name, an equal sign (=) and a constant of the appropriate type.
▪General form :
●
datatype variable =
constant;
●
int count =
0;
●
float sum =
0.0;
●
char space = ’ ‘;
2
9
Constan
ts
▪Constants are items whose value does not change during the
execution of
the program.
●
Integer constant
●
Floating point constant
●
Character constant
●
String constant
3
0
Numeric
Constants
▪Numeric constants
●
Integer constant
●
Floating point constant
●
Commas and blank spaces cannot be included within the
constant.
●
The value
constant
of acan be preceded
constant cannotby a minus
exceed (-) sign if
specified
●
desired.
minimum and maximum bounds.
●
For each type of constant, these bounds will vary from one C
compiler
to 3
another. 0
Integer
Constants
▪An integer constant is an integer-valued number.
●
decimal (base 10),
●
octal (base 8) and
●
hexadecimal (base 16).
3
2
Decimal Integer
Constants
▪A decimal integer constant can consist of any combination of digits
taken
from the set 0 through 9.
▪If the constant contains two or more digits, the first digit
3
3
Decimal Integer
Constants
▪The following decimal integer constants are written incorrectly
●
12,245 illegal character (, )
●
36.0illegal character (.)
●
10 20 30illegal character (blank space)
●
123-45-6789 illegal character (-)
●
0900 the first digit cannot be a zero.
3
4
Octal Integer
Constants
▪An octal integer constant can consist of any combination of digits
taken
from the set 0 through 7.
an
octal number.
●
0 01 0743 077777
▪The following octal integer constants are written incorrectly for the
reasons stated.
3
●
743 does not begin with 0. 5
Hexadecimal Integer
Constants
▪A hexadecimal integer constant must begin with either 0x or 0X.
▪It can then be followed by any combination of digits taken from the
sets
0 through 9 and a through f (either upper- or lowercase).
●
0X29 0x1 0X7FFF 0xabcd
3
6
Hexadecimal Integer
Constants
▪The following hexadecimal integer constants are written incorrectly
●
0X12.34 Illegal character ( . )
●
0BE38 Does not begin with 0x
or 0X
●
0x.4bffIllegal character ( . )
●
0XDEFG Illegal character
(G)
3
7
Integer
Constants
▪The magnitude of an integer constant can range from some minimum to
some maximum value that varies from one computer to another (and
from one
compiler to another, on the same computer).
▪ If 2 bytes are used for representing the integer then the range is -32768
to32767. ( -(215) to
(215-1) )
▪If 4 bytes are used the the range will be - (231) to (231-1)
●
Eg. 23252000L
●
If 4 bytes are used for representing, then the range will be - (231) to
231-1.
●
Unsiged Long Integer Constants
●
An unsigned long integer may be specified by appending the letters UL to
the
end of the constant.
●
The letters may be written in either upper or lowercase. 3
9
●
Several unsigned and long integer constants are shown
below :
●
Constant Number System
●
50000U decimal
●
123456789 (unsigned)
L decimal (long)
●
123456789 decimal (unsigned
UL long) octal (long)
●
0123456L octal (unsigned)
●
07777771U hexadecimal
●
0X50000U (unsigned)
●
0XFFFFFUL hexadecimal
(unsigned long)
4
0
Floating Point
Constants
▪A floating-point constant is a base-10 number that contains either a
decimal
point or an exponent (or both).
●
50000. 0.000743 12.3
315.0066
●
2.1E-80.006e-3 1.6667E+8
.12121212e12
▪The number 1.2 x 10-3 would be written as 1.2E-3 or
1.2e-3.
4
1
Floating Point
Constants
▪The following are not valid floating-point constants for the reasons
stated.
●
1 Either a decimal point or an exponent must be
present.
2.34E+10.2 The exponent must be an integer quantity (it cannot
●
●
1,000.0 Illegal character (, ).
4
2
Floating Point
Constants
▪Integer constants are exact quantities, whereas floating-point
4
3
Character
Constants
▪A character constant is a single character, enclosed in single
quotation marks.
●
‘A’ ’9’ ’+’ ’ ‘ ’&’
●
‘A’ -
- 97 65 ’B’
’b’ - - 66
●
‘a’
98
●
‘ ‘
- 32
●
‘0’
- 48
4
4
String
Constant
▪A string constant consists of any number of consecutive
▪Examples :
●
“Welcome ”green” ”Abdul Khalam “$10.35
” Azad” ”
●
“a+b” ” “
”line1\nLine2\nLine3”
●
“She said, \” It is Ok \” “ printed as She said “It is
Ok”
▪A null string is represented as “”
every
4
string constant, as the last character within the string. 5
String
Constant
▪Lenght of a string constant is the number of characters in it.
●
Length of “abcd” is 4
●
Length of “a\nb” is 3
▪A character constant (e.g. ‘A’ ) and the corresponding single-
character
string constant ( "A" ) are not equivalent.
can
be represented as \n.
4
7
Charact Escape
er Seauence
bell \a
(alert)
Backspa \b
ce
horizontal \t
tab
vertical \
tab v
newline (line \n
feed)
form \f
feed
carriage \r
return
quotation mark \”
(")
Apostrophe \
(')
question mark ’
(?) \
Backslash ?
\\
(\)
Nul \
4
l 0
7
Escape
Sequences
▪Of particular interest is the escape sequence \0.
▪Note that the null character constant ‘\0’ is not equivalent to the
4
9
5
0
CONSOLE I/O
FUNCTIONS
▪A console comprises the screen and the keyboard.
▪The Console Input and Output functions can be classified into two
categories:
5
2
FORMATTED I/O
FUNCTIONS
▪They provide the flexibility to receive the input in
5
3
Writing output data -
printf()
▪The printf function can be used to output any combination of numerical
values,
single characters and strings.
●
●
printf ( control_string, arg1, arg2, . . . , argn)
where control_string refers to a string that contains formatting information,
▪arg1,
andarg2, . . . , argn are arguments that represent the individual output
data
items.
complex expressions.
5
4
Writing output data - printf()
▪The control_string consists of individual groups of characters,
▪In its simplest form, an individual character group will consist of the
by
other characters, including whitespace characters
5
5
Convertion characters– for printf()
and scanf()
5
6
Writing output data - printf()
▪printf(“%d”, d_sum);
▪printf(“%f”, f_sum);
▪f_sum = 7472.342789
printf(“%f %e”, // 7.472343e+
f_sum,f_sum); 7472.342789 03
▪printf(%6d”,d_sum
);
▪printf(%2.3f”,f_su
m); 5
7
Reading Input data - scanf()
▪Input data can be entered into the computer from a standard input
device
by means of the C library function scanf.
values,
single characters and strings.
▪The function returns the number of data items that have been
entered successfully.
5
9
Reading Input data -
scanf()
▪scanf(“%d %d”,&d_first,&d_second);
▪scanf(“%f %c”,&f_v1,&c_v2);
▪scanf(“%d-%d-
%d”,&d_day,&d_month,&d_year);
6
0
UNFORMATTED CONSOLE I/O
FUNCTIONS
▪The unformatted console input/output functions deal with a
▪We often want a function that will read a single character the instant it
is
typed without waiting for the ENTER key to be hit as in scanf( )
6
1
Character Input
▪In C language getchar() function is used to read a character
▪Common usage is
●
ch = getchar(); where ch is a char or int
variable.
▪If ENTER key is pressed without giving a character then ENTER key is
taken as 6
2
Character
Output
▪In C language putchar() function is used to output a to the
display
character device.
▪ Common
usage is
●
putchar(character_ite
m)
▪ The character_item can be expressed as :
●
A char/int constant or A char/int variable or A
char/int expression
▪ Examples:
●
putchar(‘A’ //
) A
●
putchar(6 //
B 6
6)
2
Character
Output
▪Examples: char ch=’Z’; int
i=66;
●
putchar(ch) //
Z
●
putchar(i) // B
●
putchar(ch+32)
// z
●
putchar(‘a’-32)
// A
●
putchar(i+1) //
C 6
4
6
5
▪Write a program to read and display a number.
6
6
Operators in
C
▪The data items that operators act upon are called operands.
6
7
Operators in
C
▪Categories of operators :
●
Arithmetic
operators
●
Unary operators
●
Relational
operators
●
Logical operators
●
Assignment
operators
●
Conditional
operator 6
8
Arithmetic Operators
in C
▪Arithmetic operators :
●
There are five arithmetic operators in C.
They are
Operator Purpose
+ Addition
-
Sutraction
*
Multiplication
/
Division
% Remainder of 6
9
Arithmetic Operators
in C
▪There is no exponentiation operator in C.
●
integer quantities,
●
Floating-point quantities or
●
characters (remember that character constants represent
integer values, as determined by the computer’s
character set).
7
0
Arithmetic Operators
in C
▪The remainder operator (%) requires that
●
both operands be integers and the second operand be
nonzero.
integer division.
7
1
Unary Operators
in C
▪Operators that act upon a single operand to produce a
new value.
▪Unary Minus (-)
●
Ex:- - -
root1 (x+y
-743 )
(++)
▪Decrement operator (--)
●
causes its operand to be decreased by 1.
●
Ex :- ++a where a is an interger
variable.
●
printf ("a = %d\n", a);//
int a=5; a=5
●
printf ("a = %d\n", + //
+a);
●
printf ("a = %d\n", a);
//
a=6 a
7
3
Increment Operators
Post-increment
in C operator: <id>++
- value of <id>is used
then incremented and
●
Ex :- a++ where a is an interger variable.
▪ Use the current vaule of the operand and then incremented
by 1.
int
a=5,b=3;
●
printf ("a = %d\n", a); // a=
5
●
printf ("a = %d\n", a++); // a=
5
●
printf ("a = %d\n", a); a =6
// a=%d”,c,a); c=+
●
c = a++ + b; printf(“c +a + b; // c= 8
= %dprintf(“c = %da= a=6
●
%d”,c,a); // c= 7
3
Decrement Operators
in C
▪Pre-decrement operator:
●
Ex :- --a where a is an interger variable.
●
int a=5;
●
printf ("a = %d\n", a);// a=5
●
printf ("a = %d\n", //
--a);
●
printf ("a = %d\n", a);
//
a=4 a
75
Decrement Operators
in C
▪Post-decrement operator:
●
Ex :- a-- where a is an interger variable.
76
The sizeof Operator
in C
▪The sizeof operator returns the size of the its operand in
bytes
▪Usage is
Example Output
printf(“%ld”, sizeof 123); 4
printf(“%ld”, sizeof “abcd”); 5
printf(“%ld”, sizeof 12.3); 8
char ch;
1
printf (“%ld”, sizeof ch);
77
#include
<stdio.h> void
main()
{
printf("%ld\n",
sizeof(char)); printf("%ld\
n", sizeof(int));
printf("%ld\n",
} sizeof(float)); printf("%ld\
n", sizeof(double));
Outp
ut
1
4
4
8
78
Relational
Operators:
▪There are four relational operators
in C. Operator Meaning
▪
>= greater than or equal
▪Theretoare two equality operators
in C. Operator Meaning
▪ == equal to
▪ != not equal
to
79
Relational Operators:
1. Otherwise it returns 0.
▪For example, 5==5 will return 1.
▪2. Not equal to operator: Represented as ‘!=’, the not equal to
operator checks
whether the two given operands are equal or not. If not, it returns 1.
Otherwise it returns 0. It is the exact boolean complement of the
‘==’ operator.
80
▪For example, 5!=5 will return 0.
▪ 3. Greater than operator: Represented as ‘>’, the greater than
operator checks
whether the first operand is greater than the second operand or not.
If so, it returns 1. Otherwise it returns 0.
checks
whether the first operand is lesser than the second operand. If so, it
returns
1. Otherwise it returns 0.
▪ For example, 6<5 will return 0.
81
▪5. Greater than or equal to operator: Represented as ‘>=’, the
greater than or
equal to operator checks whether the first operand is greater than or
equal to the second operand. If so, it returns 1 else it returns 0.
than or equal to
operator checks whether the first operand is less than or equal to the
second operand. If so, it returns 1 else 0.
82
Logical Operators:
▪They are used to combine two or more conditions/constraints or to
▪1. Logical AND operator: The ‘&&’ operator returns 1 when both
83
▪2. Logical OR operator: The ‘||’ operator returns 1 even if one (or both)
84
▪3. Logical NOT operator: The ‘!’ operator returns 1 if the condition
85
Assignment Operators:
right
side operand of the assignment operator is a value.
variable on
the left side otherwise the compiler will raise an error.
to
86
assign the value on the right to the variable on the left.
▪2. “+=”: This operator is combination of ‘+’ and ‘=’ operators. This
operator first adds the current value of the variable on left to the value
on right and then
assigns the result to the variable on the left.
operator first
subtracts the value on right from the current value of the variable on left
and then assigns the result to the variable on the left.
Example: (a -= b) can be written as (a = a - b) If
87
initially value stored in a is 8. Then (a -= 6) = 2.
▪4. “*=”: This operator is combination of ‘*’ and ‘=’ operators. This
operator first multiplies the current value of the variable on left to the
value on right and then assigns the result to the variable on the left.
*= 6) = 30.
▪5. “/=”: This operator is combination of ‘/’ and ‘=’ operators. This
operator first
divides the current value of the variable on left by the value on right
and then assigns the result to the variable on the left.
Example: (a /= b) can be written as (a = a / b)
If 88
Bitwise Operators:
▪1. & (bitwise AND) in C takes two numbers as operands and does AND on
every bit of two numbers. The result of AND is 1 only if both bits are 1.
▪2. | (bitwise OR) in C takes two numbers as operands and does OR on every
89
▪3. ^ (bitwise XOR) in C takes two numbers as operands and does XOR
on every
bit of two numbers. The result of XOR is 1 if the two bits are different.
▪4. ~ (bitwise NOT) in C takes one number and inverts all bits of it.
90
91
▪5. >> (right shift) in C takes two numbers, right shifts the bits of the
first
●
Expression1 ? Expression2 : Expression3 .
▪Here, Expression1 is the condition to be evaluated. If the
93
Conditional
Operator
▪Note that only one of the embedded expressions (either
▪Example
●
a>b?a:
b
●
small = a < b ? a : b
94
Largest of two numbers using conditional operator
(ternary
operator)
//Program to find the largest of two numbers
#include<stdio.h>
{
void main()
int
d_num1,d_num2,d_large;
printf("Enter two numbers\
scanf("%d%d",&d_num1,&d_num2);
n");
d_large = d_num1>d_num2 ?
d_num1:d_num2;
printf("Largest=%d\n",d_large);
95
Expressions in
C
▪An expression represents a single data item, such as a
number or a character.
by one
or more operators.
▪Expressions can also represent logical conditions that are either true or
false.
●
A constant
●
A variable or
●
Operands connected with
operators
▪Exampl
es
●
32, ‘A’, 3.14
“String”, Sum, average,
●
name,
a*b, a-
●
mark b, a<
=b
a+b, a/b,
97
Operator Precedence and
associativity
▪Operator Precedence :
●
Defines the order in which operators in an expression will be
evaluated.
The operator with higher precedence will be evaluated before
evaluating an operator with a lower precedence.
●
Eg. 2*3 +4;
▪Associativity of
operator:
●
Defines the order in which operators of the same precedence in an
expression will be evaluated.
●
It can be either left to right or right to
left. 98
Operator Precedence and
associativity
99
Operator Precedence and
associativity
10
0
Operator Precedence and
associativity PUMA RELL
Parenthese,
Operator dot, arrow Operator
Category TAC Associativity
s
Unary Operators - ++ sizeof R->L
-- ! (type)
&
Arithmetic multiply, * / % L->R
divide and remainder
Arithmetc add and + - L->R
subtract
Relational Operators < <= > L->R
>
=
Equality Operators == != L->R
Logical and && L->R
Commor
Logical || L->R
10
1
Operator Precedence and
associativity
int a = 5, b = 6, c = 4,result1;
result1 = a-- * b -++c;
printf("\n%d",result1);
10
2
Type Conversions in C
▪Implicit type conversion :
●
Both the operands must be of same type for an arithmetic operation.
●
If the operands are of different types, then the system automatically converts the type
of operand with lower precision to the type of other.
●
This is also used when LHS of an assignment operrator is having lower precision
than that of the RHS operand.
●
It is performed only if the operand data types are compatible.
10
3
Type Conversions
in C
▪Implicit type
conversion :
10
4
Type Conversions
in C
▪Explicit type conversion (type
casting) :
●
Programmer can force the system to convert the data type of an
expression .
●
The syntax
is:
●
( <data
type> )<exp>
●
Eg. (float) 3/4;
●
It is treated as a unary
operator.
10
5
Control Structures
CONTROL FLOW
S TATE ME NT
10
6
Branchi
ng
1) if statement
▪It allows the compiler to test the condition first and then, depending
upon
the result it will execute the statement.
10
7
Syntax – if
Statement
if (condition)
{
Block of
statements;
}
10
8
//Example – if
Statement #include
<stdio.h>
void main ()
{
int d_num = 10;
if( d_num < 20 )
{
//if
condition is
true then
print the
following
printf("d_nu
m is less
than 20\ 10
n" ); 9
Syntax – if else
Statement
if (expression)
{
Block of
statements;
}
else
{
Block of
statements;
}
11
0
#include
<stdio.h> void
main()
{
int
m=40,n=20;
if(m==n)
{
pri
ntf
("
m
an
d
n
ar
e
eq 11
ua 1
Syntax if….else if….else / Else-if
ladder
if (expression)
{
Block of statements;
}
else if(expression)
{
Block of statements;
}
else
{
Block of statements;
}
11
2
Write a program to test whether a number is negative or
positive or zero?
#include <stdio.h>
void main()
{
int n;
printf("Enter the value of n");
scanf("%d",&n);
if( n > 0)
{
printf("Positive");
}
else if(n < 0)
{
printf("Negative");
else {
} printf("Zero"
);
} }
11
3
Nested if
statement
▪ Placing if statement inside another if statement is
called Nested if.
Syntax of Nested if statement
if (expression)
{
Block of statements;
if(expression)
{
Block of statements;
}
}
else if(expression)
{
Block of statements;
}
else
{
Block of statements;
}
11
4
/*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;
printf("Enter a number:");
scanf("%d",&n); if(n<100)
{
printf("%d is less than 100\n",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
return 100",n);
0;
}
11
5
The switch
▪ Switch statement in C statement
tests the value of a variable and compares it
with
multiple cases.
referred to
as an identifier.
▪The value provided by the user is compared with all the cases inside the
switch
block until the match is found.
11
▪If a case match is NOT found, then the default statement is executed, and the 6
switch( expressio
n)
{
case value-1:
Block-
1;
Break;
case value-2:
Block-
2;
Break;
case value-n:
Block-
n;
Break;
default:
Block-
1;
Break; 11
7
#include
<stdio.h> int
main() {
int num;
printf("Enter
the
number\
n");
scanf("%d",&nu
m); switch
(num) {
case 7:
printf("Value is
7"); break;
case 8:
printf("Value is
8");
break;
case 9:
printf("Value is
9");
break;
} default: 11
printf("Out of 7
goto
statement
▪In C programming, goto statement is used for altering the normal
anywhere
within a function.
11
9
12
0
#include
<stdio.h> void
main()
{
int n;
printf("Enter
the value of
n");
scanf("%d",
&n);
if(n<0)
goto
END;
if(n % 2
==0)
printf("E
12
ven\n"); 1
Class Work
–
● [40,60 - Passed
) - Failed
[0,40)
▪Using switch-case develop a simple menu driven calculator
program.
12
2
LOOP CONTROL
STRUCTURE
▪This involves repeating some portion of the program either a
▪ while statement
▪ do-while statement
▪ for statement
12
3
LOOP CONTROL
STRUCTURE CONTD..
▪A looping process, in general, would include the following four steps:
12
4
WHILE
LOOP
▪It is an entry control loop.
▪In a while loop, loop control variable should be initialized before the loop
begins.
▪The loop variable should be updated inside the body of the while
Syntax
initialize loop counter;
while (test loop counter using a condition)
{
statement(s);
…………
increment loop counter;
}
12
5
How while loop
works?
12
6
Example 1: while loop
// Print numbers from 1 to
5
#include <stdio.h>
int main()
{
int i = 1;
while(i <= 5)
{
printf("%d\n", i);
++i;
}
return 0;
}
12
7
▪Instead of incrementing we can even decrement a loop
counter
void main( )
{
int k = 4 ;
while ( k >=
1)
{
printf ( "decrement
counter”) ;
k= k- 1 ;
}
}
12
8
▪ Q) Write a program to find the largest of N numbers.
▪ Q) Write a program to find the factorial of a number.
▪ Q) Write a program to find the sum of the first N natural
numbers.
▪ Q) Write a program to find xn, where n is an integer number and x
is a nonzero number.
▪ Q) Write a program to find the largest digit in a positive integer.
12
9
Q) Write a program to read a number and find sum of digits
of a numbers.
#include <stdio.h>
void main()
{
int d_N,d_sum=0,temp;
printf("Enter the value of
n"); scanf("%d",&d_N);
}
printf("Sum = %d",d_sum);
}
13
0
DO –WHILE
LOOP
▪It is an exit control loop. That is, it evaluates its test expression
▪do -while loop execute at least once even when the test
Syntax
do
{
Statement 1;
………
} while (condition); 13
1
How do...while loop
works?
➢ The body of do...while loop is executed once. Only then, the test
expression
is evaluated.
➢ If the test expression is true, the body of the loop is executed again and
the
test expression is evaluated.
void main()
{
int n,i,sum=0;
printf("Enter the value of n");
scanf("%d",&n);
i=1;
do
{
sum = sum + i;
i++;
}while(i<=n);
printf("Sum =
%d",sum); 13
3
13
4
13
5
Q) Write a program to find the first composite number from a
given set of
N numbers.
Q) Write a program to find the factors of odd numbers from a
given set of
N numbers.
Q) Write a program to print fibonacci numbers less than N, where
N is a
positive integer. ( 0, 1, 1, 2, 3, 5, 8....)
Q) Write a program to find the single digit sum of a given
number. Digit sum
operation is repeated until it result in a sum which is a single
decimal digit.
13
6
FOR
LOOP
▪A for loop is a repetition control structure which allows us to write a
loop
that is executed a specific number of times.
▪First initialize this loop variable to some value, then check whether
to
false, the for loop is terminated.
the
body of the for loop are executed, and the increment expression is
incremented.
13
9
▪ Initialization Expression: In this expression we have to initialize the
loop
counter to some value. for example: int i=1;
condition evaluates to true then we will execute the body of loop and go
to update
expression otherwise we will exit from the for loop. For example: i
<= 10;
▪ Increment Expression: After executing loop body this expression
int main()
{ int i;
for (i = 1;
i < 11; +
+i)
{
printf("%
d ", i);
} 14
1
Example 2: for loop
// Program to calculate the sum of first n natural
numbers
// Positive integers 1,2,3...n are known as natural
numbers
#include <stdio.h>
int main()
{
int num, count, sum = 0; printf("Enter
a positive integer: ");
scanf("%d", &num);
// for loop terminates when num is less than
count for(count = 1; count <= num; +
+count)
{
sum += count;
}
} printf("Sum = %d", sum);
return 0; 14
2
for (num=10; num<20;
num=num+1)
for (i=1,j=1;i<10 && j<10; i++, j++)
{
//Statements
}
int num=10; When you have a for loop that ends with a
for (;num<20;num++) semicolon, it means that there is no body
{ //Statements
for the loop. Basically its an empty loop. It
}
can be useful for finding the length of a
for (num=10; string, number of elements in a array, and
num<20; )
so on.
{
//Statements int i;
num++; for (i = 0; s<=n ; ++i);
}
int num=10;
for
(;num<20;)
{
//
Statements
14
num++;
} 2
BREAK AND
CONTINUE
▪The break and continue statement are used to alter the flow of a
STATEMENT
program.
▪Loops are used to execute certain block of statements for n number
of
times until the test condition fails.
14
4
break
statement
break;
▪The break statement is almost always used with switch-case statement
and
inside the loop.
14
5
How break statement
works?
14
6
▪Example –
break #include
<stdio.h> void
main()
{
int i;
for(i=0;i<5;i++)
{
printf(“%d”,i
); break;
int i;
float number,
sum = 0.0;
{
for (i = 1; i
printf("Enter n%d: ", i);
<= 10; ++i)
scanf("%f", &number);
if (number < 0.0)
break;
sum +=
} number;
printf("Sum = %.2f",
sum);
14
} 8
continue statement
▪The continue statement skips the current iteration of the
continue;
▪When continue is encountered inside any loop, control automatically
14
9
How continue statement
works?
15
0
▪Example – continue
#include <stdio.h>
void main()
{
int i;
for(i=1;i<20;i++)
{
if(i%2==0)
continue;
printf(“%d
”,i);
}
printf(“\nFinally this
will appear!”);
} 15
1
▪Example –
continue
#include
<stdio.h> void
main()
{
int i,num,f,n;
Scnf(“%d”&n);
{
for(i=0;i<n;i++)
scanf(“%d”,&nu
m); if(num<0)
continue;
for(f=1;num>=1;
num--)
{
f=f*num;
}
printf(“\nFactorial of %d is
%d”,num,f);
}
}
15
2
1. Read a Natural Number and check whether the number is
prime or not 2.Read a Natural Number and check whether the
number is Armstrong or not
3. Program to print half pyramid of numbers 1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
4. Write a program to find the nth fibonacci number.
15
3
Program to print half pyramid
of *
*
* *
* * *
* * * *
* * *
* * for (i
= 1; i <= rows; i++)
{
for (j = 1; j
<= i; j++)
{
printf("* ");
}
printf("\n"); 15
4
Program to print inverted half pyramid
of *
* * * * *
* * * *
* * *
* *
*
for (i = rows; i >= 1; i--)
{
for (j = 1; j <= i; j++)
{
printf("* ");
}
printf("\n");
}
15
5