EST 102 - Module 2
EST 102 - Module 2
PROGRAM BASICS
MODULE 2 - PROGRAM BASICS
▪ Basic structure of C program: Character set, Tokens, Identifiers in C, Variables and
using goto statement, While Loop, Do While Loop, For Loop, Break and Continue
statements.(Simple programs covering control flow)
2
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
3
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.
4
▪ A C program is divided into different sections. There are six main sections to a
basic c program. The six sections are,
▪ Documentation
▪ Link
▪ Definition
▪ Global Declarations
▪ Main functions
▪ Subprograms
5
STRUCTURE OF A C PROGRAM
6
A sample C program
int main()
{
int d_num1,d_num2,d_sum;
scanf("%d %d",&d_num1,&d_num2);
d_sum=d_num1+d_num2;
➢ All the statements starting with # (hash) symbol are known as preprocessor
directives/commands, therefore #define and #include are also known as
preprocessor directives
▪ Statements are formed using keywords and identifiers based on grammar rules.
9
CHARACTER SET
▪ Every language contains a set of characters used to construct words,
statements, etc.
▪ C language also has a set of characters which include alphabets, digits, and
special symbols.
✓ 1. Alphabets
✓ 2. Digits
✓ 3. Special characters
10
Alphabets
▪ C language supports all the alphabets from the English language. Lower and
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
11
Special Symbols
▪ Special Symbols are + - * / % = & % # ~ ! ( ) [ ] { }
characters
12
13
TOKEN
▪ Every C program is a collection of instructions and every instruction is a
▪ Tokens are used to construct C programs and they are said to be the basic
14
▪ In a c program tokens are of the following types:
➢ 1. Keywords
➢ 2. Identifiers
➢ 3. Constants
➢ 4. Strings
➢ 5. Special Symbols
➢ 6. Operators
15
Keywords
●
Keywords are specific reserved words in C each of which has a specific feature
associated with it.
●
They are having special predefined meaning.
16
Identifier
▪ An identifier is a collection of characters which acts as the name of variable,
18
Data Types
▪ Data types in the c programming language are used to specify what kind of value
▪ The memory size and type of the value of a variable are determined by the
19
Primitive Data Types
➢ char: The most basic data type in C. It stores a single character and requires a single
➢ int: As the name suggests, an int variable is used to store a decimal integer. It requires
2 or 4 bytes of memory.
➢ float: It is used to store real numbers (numbers with floating point value) with single
➢ double: It is used to store floating point numbers with double precision. Memory required
is 8 bytes.
20
Data Type Qualifiers in C
➢ Data type qualifiers are :
●
short, long
●
signed, unsigned
➢ Usage is :
➢ If no data type is specified with these qualifiers then default datatype is int.
➢ The datatype int will sometimes be same as either short int or long int.
21
Data Type Qualifiers in C
➢ sizeof(short int) <= sizeof (int)
➢ The data type double can also be qualified using long double.
22
23
void data type
▪ 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.
24
Variables
▪ A variable is an identifier that is used to represent some specified type of
the user can store different values of the same datatype during the program
execution.
▪ The data item can be accessed in the program simply by referring to the
variable name.
25
26
Declaration
▪ All variables must be declared before they can appear in executable statements.
▪ A declaration consists of a data type, followed by one or more variable names, ending with a
semicolon.
▪ General form is :
▪ Examples:
● float average;
● char flag;
27
Declaration
▪ To do so, the declaration must consist of a data type, followed by a variable name,
▪ General form :
●
datatype variable = constant;
●
int count = 0;
●
float sum = 0.0;
●
char space = ’ ‘;
28
Constants
▪ Constants are items whose value does not change during the execution of the
program.
● Integer constant
● Character constant
● String constant
29
Numeric Constants
▪ Numeric constants
● Integer constant
●
For each type of constant, these bounds will vary from one C compiler
to another. 30
Integer Constants
▪ An integer constant is an integer-valued number.
31
Decimal Integer Constants
▪ A decimal integer constant can consist of any combination of digits taken from
▪ If the constant contains two or more digits, the first digit must be
32
Decimal Integer Constants
▪ The following decimal integer constants are written incorrectly for the
reasons stated.
33
Octal Integer Constants
▪ An octal integer constant can consist of any combination of digits taken from
▪ However the first digit must be 0, in order to identify the constant as an octal
number.
● 0 01 0743 077777
▪ The following octal integer constants are written incorrectly for the reasons
stated.
▪ It can then be followed by any combination of digits taken from the sets 0
▪ Note that the letters a through f (or A through F) represent the (decimal)
35
Hexadecimal Integer Constants
▪ The following hexadecimal integer constants are written incorrectly for the
reasons stated :
●
0BE38 Does not begin with 0x or 0X
●
0x.4bffIllegal character ( . )
●
0XDEFG Illegal character (G)
36
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 to 32767.
( -(215) to (215-1) )
▪ They are identified by appending the letter U (either upper- or lowercase) to the
▪ If 2 bytes are used for representing, then the range will be 0 to 216-1.
(0-65535)
37
Long Integer Constants
▪ Identified by appending the letter L (either upper- or lowercase) to the end of the
constant.
● Eg. 23252000L
● If 4 bytes are used for representing, then the range will be - (231) to 231-1.
● However, the U must precede the L. Eg. 12345678UL decimal (unsigned long)
38
● Several unsigned and long integer constants are shown below :
39
Floating Point Constants
▪ A floating-point constant is a base-10 number that contains either a decimal point
●
0. 1. 0.2 827.602
●
50000. 0.000743 12.3 315.0066
●
2.1E-80.006e-3 1.6667E+8 .12121212e12
40
Floating Point Constants
▪ The following are not valid floating-point constants for the reasons stated.
●
2.34E+10.2 The exponent must be an integer quantity (it cannot contain
a decimal point).
●
3.47E 10 Illegal character (blank space) in the exponent.
41
Floating Point Constants
▪ Integer constants are exact quantities, whereas floating-point constants are
approximations.
42
Character Constants
●
‘A’ ’9’ ’+’ ’ ‘ ’&’
● ‘A’ - 65 ’B’ - 66
● ‘a’ - 97 ’b’ - 98
● ‘ ‘ - 32
● ‘0’ - 48
43
String Constant
▪ A string constant consists of any number of consecutive characters
▪ Examples :
●
“a+b” ” “ ”line1\nLine2\nLine3”
●
“She said, \” It is Ok \” “ printed as She said “It is Ok”
▪ The compiler automatically places a null character (\0) at the end of every string
● Length of “abcd” is 4
● Length of “a\nb” is 3
▪ A character constant (e.g. ‘A’ ) and the corresponding single-character string
45
Escape Sequences
▪ It is used for representing the nonprintable characters (backspace, tab,
▪ Such escape sequences always represent single character, even though they are
represented as \n.
46
Character Escape Seauence
bell (alert) \a
Backspace \b
horizontal tab \t
vertical tab \v
form feed \f
carriage return \r
Apostrophe (') \
’
question mark (?) \?
Backslash (\) \\
Null \0
47
Escape Sequences
▪ Note that the null character constant ‘\0’ is not equivalent to the character
constant ‘0’.
48
49
CONSOLE I/O FUNCTIONS
▪ The Console Input and Output functions can be classified into two categories:
50
CONSOLE I/O FUNCTIONS CONTD..
51
FORMATTED I/O FUNCTIONS
(header file)
52
Writing output data - printf()
▪ The printf function can be used to output any combination of numerical values, single
●
where control_string refers to a string that contains formatting information, and
▪ arg1, arg2, . . . , argn are arguments that represent the individual output data items.
▪ The arguments can be constants, single variable or array names, or more complex
expressions.
53
Writing output data - printf()
▪ The control_string consists of individual groups of characters, with one
▪ In its simplest form, an individual character group will consist of the percent sign,
54
Convertion characters– for printf() and scanf()
55
Writing output data - printf()
▪ printf(“%d”, d_sum);
▪ printf(“%f”, f_sum);
▪ f_sum = 7472.342789
▪ printf(%6d”,d_sum);
▪ printf(%2.3f”,f_sum);
56
Reading Input data - scanf()
▪ Input data can be entered into the computer from a standard input device by
▪ This function can be used to enter any combination of numerical values, single
▪ The function returns the number of data items that have been entered
successfully.
58
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);
59
UNFORMATTED CONSOLE I/O FUNCTIONS
▪ We often want a function that will read a single character the instant it is typed
60
Character Input
▪ In C language getchar() function is used to read a character through the
keyboard.
▪ Common usage is
▪ If ENTER key is pressed without giving a character then ENTER key is taken as the
input charater.
61
Character Output
▪ In C language putchar() function is used to output a character to the display
device.
▪ Common usage is
●
putchar(character_item)
▪ Examples:
● putchar(‘A’) //
A
● putchar(66) //
B 62
Character Output
● putchar(ch) // Z
● putchar(i) // B
● putchar(ch+32) // z
● putchar(‘a’-32) // A
● putchar(i+1) // C
63
64
▪ Write a program to read and display a number.
65
Operators in C
▪ The data items that operators act upon are called operands.
▪ Some operators require two operands, while others act upon only one
operand.
66
Operators in C
▪ Categories of operators :
● Arithmetic operators
● Unary operators
● Relational operators
● Logical operators
● Assignment operators
● Conditional operator
● Bitwise operators
67
Arithmetic Operators in C
▪ Arithmetic operators :
Operator Purpose
+ Addition
Sutraction
-
Multiplication
*
Division
/
% Remainder of integer
division
(modulus operator) 68
Arithmetic Operators in C
▪ There is no exponentiation operator in C.
▪ The operands acted upon by arithmetic operators must represent numeric values.
● integer quantities,
● Floating-point quantities or
●
characters (remember that character constants represent integer
values, as determined by the computer’s character set).
69
Arithmetic Operators in C
▪ The remainder operator (%) requires that
●
the second operand be nonzero.
▪ Division of one integer quantity by another is referred to as integer
division.
▪ This operation always results in a truncated quotient (ie. Interger part only).
70
Unary Operators in C
▪ Operators that act upon a single operand to produce a new value.
▪ The operand used with each of these operators must be a single variable.
71
Increment Operators in C
▪ Pre-increment operator - ++<id> - incremented value of <id>is used
● int a=5;
72
Increment Operators in C
Post-increment operator: <id>++ then
- value of <id>is used and
incremented
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
c = a++ + b; printf(“c = %d a=%d”,c,a); c = ++a + b;
●
// c= 8 a=6
printf(“c = %d a=%d”,c,a);
●
// c= 10 73
Decrement Operators in C
▪ Pre-decrement operator:
▪ First decrement the variable and then use the decremented value.
● int a=5;
74
Decrement Operators in C
▪ Post-decrement operator:
▪ Use the current value of the operand and then it will be decremented by 1
● int a=5;
75
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);
76
#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));
}
Output
1
4
4
8
77
Relational Operators:
▪ There are four relational operators in C.
Operator Meaning
▪ == equal to
▪ != not equal to
78
Relational Operators:
whether the two given operands are equal or not. If so, it returns
1. Otherwise it returns 0.
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.
79
▪ 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.
▪ 4. Less than operator: Represented as ‘<‘, the less than operator 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.
80
▪ 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.
▪ 6. Less than or equal to operator: Represented as ‘<=’, the less 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.
81
Logical Operators:
▪ They are used to combine two or more conditions/constraints or to complement
the evaluation of the original condition under consideration. They are described
below:
▪ 1. Logical AND operator: The ‘&&’ operator returns 1 when both the
82
▪ 2. Logical OR operator: The ‘||’ operator returns 1 even if one (or both) of the
83
▪ 3. Logical NOT operator: The ‘!’ operator returns 1 if the condition in
84
Assignment Operators:
▪ The left side operand of the assignment operator is a variable and right side
▪ The value on the right side must be of the same data-type of variable on the
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.
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
86
▪ 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.
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
87
Bitwise Operators:
▪ The Bitwise operators are used to perform bit-level operations on the operands.
▪ The operands are first converted to bit-level and then the calculation is
▪ 1. & (bitwise AND) in C takes two numbers as operands and does AND on every bit of
▪ 2. | (bitwise OR) in C takes two numbers as operands and does OR on every bit of two
88
▪ 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.
89
90
▪ 5. >> (right shift) in C takes two numbers, right shifts the bits of the first
91
Conditional Operator
True then we will execute and return the result of Expression2 otherwise if the
condition(Expression1) is false then we will execute and return the result of
Expression3.
92
Conditional Operator
▪ Note that only one of the embedded expressions (either expression-2 or
▪ Example
●
a>b?a:b
● small = a < b ? a : b
93
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\n");
scanf("%d%d",&d_num1,&d_num2);
d_large = d_num1>d_num2 ?d_num1:d_num2;
printf("Largest=%d\n",d_large);
94
Expressions in C
▪ An expression represents a single data item, such as a number or a
character.
more operators.
▪ Expressions can also represent logical conditions that are either true or false.
▪ However, in C the conditions true and false are represented by the integer values
1 and 0, respectively
95
Expressions in C
▪ An expression can be :
● A constant
●
A variable or
●
Operands connected with operators
▪ Examples
●
32, ‘A’, “String”, 3.14
Sum, name, average,
●
96
Operator Precedence and associativity
▪ Operator Precedence :
●
The operator with higher precedence will be evaluated before
evaluating an operator with a lower precedence.
▪ 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.
97
Operator Precedence and associativity
98
Operator Precedence and associativity
99
Operator Precedence and associativity
PUMA RELL TAC
Parenthese, dot, arrow
Operator Category Operators Associativity
Unary Operators - ++ -- ! sizeof (type) R->L
&
Arithmetic multiply, divide * / % L->R
and remainder
Arithmetc add and subtract + - L->R
int a = 5, b = 6, c =
4,result1; result1 = a-- * b -
++c; printf("\n%d",result1);
result1 = --a * b -
++c;
printf("\n%d",result1);
101
Type Conversions in C
●
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.
102
Type Conversions in C
103
Type Conversions in C
●
Programmer can force the system to convert the data type of an
expression .
●
The syntax is:
●
It is treated as a unary operator.
104
Control Structures
CONTROL FLOW
S TATE ME NT
105
Branching
1) if statement
▪ It allows the compiler to test the condition first and then, depending upon the
statement is executed
106
Syntax – if Statement
if (condition)
{
Block of statements;
}
107
//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("value of number is : %d\n", d_num);
}
108
Syntax – if else Statement
if (expression)
{
Block of statements;
}
else
{
Block of statements;
}
109
#include <stdio.h>
void main()
{
int m=40,n=20;
if(m==n)
{
printf("m and n are equal");
}
else
{
printf("m and n are not equal");
}
110
Syntax if….else if….else / Else-if ladder
if (expression)
{
Block of statements;
}
else if(expression)
{
Block of statements;
}
else
{
Block of statements;
}
111
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");
}
}
112
Nested if statement
▪ Placing if statement inside another if statement is called Nested if.
if(expression)
{
Block of statements;
}
}
else if(expression)
{
Block of statements;
}
else
{
Block of statements;
}
113
/*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);
}
114
The switch statement
▪ Switch statement in C tests the value of a variable and compares it with multiple
cases.
▪ Once the case match is found, a block of statements associated with that
an identifier.
▪ The value provided by the user is compared with all the cases inside the switch block
▪ If a case match is NOT found, then the default statement is executed, and the control
115
switch( expression )
{
case value-1:
Block-1;
Break;
case value-2:
Block-2;
Break;
case value-n:
Block-n;
Break;
default:
Block-1;
Break;
}
Statement-x;
116
#include <stdio.h>
int main() {
int num;
printf("Enter the number\n");
scanf("%d",&num);
switch (num) {
case 7:
printf("Value is 7");
break;
case 8:
printf("Value is 8");
break;
case 9:
printf("Value is 9");
break;
default:
printf("Out of range");
break;
}
return 0;
} 117
goto statement
▪ In C programming, goto statement is used for altering the normal sequence of
▪ The goto statement can be used to jump from anywhere to anywhere within
a function.
118
119
#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("Even\n");
else
printf("Odd\n");
END:printf("End");
}
120
Class Work –
121
LOOP CONTROL STRUCTURE
▪ This involves repeating some portion of the program either a specified
▪ while statement
▪ do-while statement
▪ for statement
122
LOOP CONTROL STRUCTURE
CONTD..
▪ A looping process, in general, would include the following four steps:
123
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;
}
124
How while loop works?
➢ The while loop evaluates the test expression inside the parenthesis ().
➢ If the test expression is true, statements inside the body of while loop are
executed. Then, the test expression is evaluated again.
125
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;
}
126
▪Instead of incrementing we can even decrement a loop counter void
main( )
{
int k = 4 ; while
( k >= 1 )
{
printf ( "decrement counter”) ; k
= k- 1 ;
}
}
127
▪ 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.
128
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);
}
129
DO –WHILE LOOP
▪ It is an exit control loop. That is, it evaluates its test expression at the
▪ do -while loop execute at least once even when the test expression
Syntax
do
{
Statement 1;
………
} while (condition);
130
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.
131
Q) Write a program to find sum of first n natural numbers using do..while ?
#include <stdio.h>
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);
}
132
133
134
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.
135
FOR LOOP
▪ A for loop is a repetition control structure which allows us to write a loop that
▪ First initialize this loop variable to some value, then check whether this
variable is less than or greater than counter value. If statement is true, then
loop body is executed and loop variable gets updated . Steps are repeated till
exit condition comes.
136
How for loop works?
▪ Then, the test expression is evaluated. If the test expression is evaluated to false,
▪ However, if the test expression is evaluated to true, statements inside the body
of the for loop are executed, and the update expression is updated.
▪ This process goes on until the test expression is false. When the test
137
The syntax of the for loop is:
138
▪ Initialization Expression: In this expression we have to initialize the loop counter
▪ Test Expression: In this expression we have to test the condition. If the 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;
▪ Update Expression: After executing loop body this expression
139
Example 1: for loop
// Print numbers from 1 to 10
#include <stdio.h>
int main() {
int i;
#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;
}
141
for (num=10; num<20; num=num+1)
{ for (i=1,j=1;i<10 && j<10; i++, j++)
//Statements
}
int num=10;
for (;num<20;num++) When you have a for loop that ends with a
{ //Statements semicolon, it means that there is no body for the
} loop. Basically its an empty loop. It can be useful
for finding the length of a string, number of
for (num=10; num<20; ) elements in a array, and so on.
{ int i;
//Statements
num++;
for (i = 0; s<=n ; ++i);
}
int num=10; for
(;num<20;)
{
//Statements
num++;
142
}
BREAK AND CONTINUE
STATEMENT
▪ The break and continue statement are used to alter the flow of a program.
▪ Loops are used to execute certain block of statements for n number of times
▪ There will be some situations where, we have to terminate the loop without
143
break statement
break;
▪ The break statement is almost always used with switch-case statement and inside
the loop.
144
How break statement works?
145
▪Example – break
#include <stdio.h>
void main()
{
int i;
for(i=0;i<5;i++)
{
printf(“%d”,i);
break;
146
#include <stdio.h>
int main() {
int i;
float number, sum = 0.0;
for (i = 1; i <= 10; ++i)
{
printf("Enter n%d: ", i);
scanf("%f", &number); if
(number < 0.0)
break;
sum += number;
}
printf("Sum = %.2f", sum);
}
147
continue statement
▪ The continue statement skips the current iteration of the loop and
continue;
▪ When continue is encountered inside any loop, control automatically passes
148
How continue statement works?
149
▪Example – continue
{
int i;
for(i=1;i<20;i++)
{
if(i%2==0)
continue;
printf(“%d ”,i);
}
printf(“\nFinally this will appear!”);
}
150
▪Example – continue
#include <stdio.h>
void main()
{
int i,num,f,n;
Scnf(“%d”&n);
for(i=0;i<n;i++)
{
scanf(“%d”,&num);
if(num<0)
continue;
for(f=1;num>=1; num--)
{
f=f*num;
}
printf(“\nFactorial of %d is %d”,num,f);
}
}
151
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.
152
Program to print half pyramid of *
*
* *
* * *
* * * *
* * * * *
for (i = 1; i <= rows; i++)
{
for (j = 1; j <= i; j++)
{
printf("* ");
}
printf("\n");
}
153
Program to print inverted half pyramid of *
* * * * *
* * * *
* * *
* *
*
for (i = rows; i >= 1; i--)
{
for (j = 1; j <= i; j++)
{
printf("* ");
}
printf("\n");
}
154