0% found this document useful (0 votes)
27 views105 pages

Module 2 Notes and Final

The document discusses the basic structure and components of a C program including sections like documentation, link, definition, global declaration, main function and sub program. It also covers C character set, tokens, identifiers and keywords.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views105 pages

Module 2 Notes and Final

The document discusses the basic structure and components of a C program including sections like documentation, link, definition, global declaration, main function and sub program. It also covers C character set, tokens, identifiers and keywords.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 105

PROGRAMMING IN C

Module II
• Basic structure of C program: Character set, Tokens, Identifiers
in C, Variables and Data Types, Constants, Console IO
Operations, printf and Continue statements. (Simple programs
covering control flow) scanf
• Operators and Expressions: Expressions and Arithmetic
Operators, Relational and Logical Operators, Conditional
operator, size of operator, Assignment operators and Bitwise
Operators. Operators Precedence
• Control Flow Statements: If Statement, Switch Statement,
Unconditional Branching using goto statement, While Loop, Do
While Loop, For Loop, Break
C PROGRAM STRUCTURE
• Documentation Section

• Link Section

• Definition Section

• Global Declaration Section

• The main( ) function

• Local Declarations

• Program Statements & Expressions

• Sub Program Section (User Defined Functions)


C PROGRAM STRUCTURE
DOCUMENTATION SECTION

Single line comments can be written


SINGLE LINE COMMENT using //
Eg: //sum of two numbers

Multi line comments can be represented


MULTI LINE COMMENTS using /*comment*/
Eg: /* This is a program for adding two
numbers*/
LINK SECTION
• The Link section provides instructions to the compiler to link functions from the
system library using the #include directive.

Eg: Header File or Standard files: These files contains definition of pre-defined
functions like printf(), scanf() etc. These files must be included for working with
these functions.
Syntax: #include<file name>
Eg: #include<stdio.h>

• These instructions are called preprocessor directives which tell the compiler to
preprocess the source code before compiling.

• All of these preprocessor directives begin with a ‘#’ (hash) symbol.


DEFINITION SECTION
• In the C Programming Language, the #define directive allows the definition of
macros within your source code.
• Macros are known as symbolic constants
• The #define command is used to make substitutions throughout the file in
which it is located.
• In other words, #define causes the compiler to go through the file, replacing
every occurrence of macro-name with replacement-string.
• All the symbolic constants are written in the definition section.
• Eg: #define AGE 10
GLOBAL DECLARATION SECTION
• There are some variables that are used in more than one function and such variables
which can be accessed by any function are called global variables.

• Global Declaration Section contains the global declaration of such user-defined


functions and variables and that is outside of all the functions.
MAIN FUNCTION
• The main( ) is the main function where program execution begins.
• Every C program must contain only one main function.
• Two parts are there within the opening and closing curly braces of the main().
• The execution of the program begins at the opening brace '{' and ends with the
closing brace '}'.
Main function consists of two parts

The declaration part is used to declare all


DECLARATION PART
variables that will be used within the program

There needs to be at least one statement in the


executable part, and these also, it has to be noted
EXECUTION PART
that all the statements of these two parts need to
be terminated with a semi-colon.
SUB PROGRAM SECTION
• The subprogram section contains all the user-defined functions that are
used to perform a specific task.
• These user-defined functions are called inside the main function.
• User-defined functions are generally placed just after the main() function,
although they may appear in any order
HELLO WORLD PROGRAM
/*This is a sample program and is my //Comments
first program*/

#include <stdio.h> //Preprocessor Directive

void main() //main function

printf("Hello, world!\n"); //Function Call

}
C CHARACTER SET
• All valid characters in C program are termed as C character set
Alphabet
All upper case letters and lower case letters
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ASCII CODE of A to Z is from 65 to 90
abcdefghIjklmnopqrstuvwxyz ASCII CODE of a to z is from 97 to 122

Digits
All digits. ASCII CODE of 0 to 9 is from 48 to 57
0 1 2 3 4 5 6 7 8 9

Special Characters
Most of the special characters are supported in C programming.
~ ! # $ % ^ & * _ - + = { } [ ] | \ / < > , . : ; ‘ “ ?

White Spaces
White spaces are any sort of spaces or sequence of characters called escape sequences to generate spaces like tabs or new
lines.
\b blank space
\n new line
\t horizontal tab
\v vertical tab
C TOKENS
smallest individual units
1. Keywords int
Char
Integer data type
Character datatype
float Floating point datatype
•Keywords are predefined, reserved words used in programming double Double datatype
auto Automatic storage class
static Static storage class
•Meaning of the keywords has already been described to the C compiler. extern Extern storage class
register Register storage class
global Global variable declaration
•They cannot be used as variable names. struct Structure datatype
union Union datatype
•Keywords are part of the syntax and they cannot be used as an identifier. if If conditional statement
else Else conditional statement
break Break unconditional statement
while While loop statement
do Do loop statement
void Void datatype
continue Continue statement
volatile Volatile qualifier for a variable
switch Switch conditional statement
case Case in switch statement
default Default case in switch statement
for For loop statement
goto Goto unconditional jump statement
typedef Defining a new name to existing data type
const Constant definition
size of Operator to find size of a datatype
enum Enumeration data type
return Return a value to called function
long Make Long version of any data type
short Make short version of any data type
signed Make Signed version of datatypes
unsigned Make unsigned version of datatypes
2. Identifiers
• These are the names we use for a variable, functions etc in our program.
• Names can begin with a character or an underscore followed by any characters or
numbers.
• Uppercase and lowercase letters are not equivalent in C, so the two identifiers r1 and
R1 do not describe the same object.

Rules for naming identifiers


1. A valid identifier can have letters (both uppercase and lowercase letters),
digits and underscores.

2. The first letter of an identifier should be either a letter or an underscore.

3. You cannot use keywords as identifiers.

4. There is no rule on how long an identifier can be. However, you may run
into problems in some compilers if the identifier is longer than 31
characters.
3. Constants
Integer Constants
• They are integer numbers
• It can have a positive or negative sign. In case it doesn’t have any sign it is taken as a positive
integer.
• No blank spaces or commas are allowed in an integer constant.
• Eg: 257, +563,-3245,-56

Real Constants
• also known as Floating point Constants are numbers that have a whole number followed by a
decimal point followed by the fractional number.
• The real constants can be expressed in two forms: Fractional Form and Exponential Form
• It can have a positive or negative sign. In case it doesn’t have any sign it is taken as positive.
• No blank spaces or commas are allowed.
• Eg: 546.236, +453.89, -22.564
5.6e9, +2.0e-7, -5.6e+8, -7.8e-5.
Character Constants
• It is a single alphabet, digit or special character enclosed within ‘single quotes’.
• Should be enclosed within single quotes.
• It can have only one character, digit or special character.
• Eg: ‘A’, ‘f’, ‘4’

String Constants
• It is a combination of alphabet, digits and special characters enclosed within “double
quotes”.
• Should be enclosed within double quotes.
• It can be of any length.
• It ends with a null character assigned to it by the compiler.
• Eg: “Welcome to Saintgits”, “Good to see you”, “5 modules”, “learning is fun”.
4. Strings
• Strings are sequence of characters enclosed in double quotes for example
• Eg: “Hello”, “abc”, ”hello123”
• Every string is automatically ending with a special character called the null
character (/0).
5. Special Symbols
• These are the punctuators used in C and have a special meaning .
Brackets [ ] Opening and closing brackets are used as array element reference. These
indicate single and multidimensional subscripts.
Parentheses ( ) These special symbols are used to indicate function calls and function
parameters.
Braces { } These opening and ending curly braces mark the start and end of a block of
code containing more than one executable statement.
Semicolon ; It is used to separate more than one statements like in for loop is
separates initialization, condition, and increment.
comma , It is an operator that essentially invokes something called an initialization
list.
an asterisk * it is used for multiplication.
assignment = It is used to assign values.
Preprocessor # The preprocessor is a macro processor that is used automatically by
the compiler to transform your program before actual compilation.
6. Operators in C
• C supports a rich set of operators.

• An operator is a symbol that takes one or more arguments and operates


on them to produce a result

• Operators are used in programs to manipulate data and variables.

• They usually form a part of the mathematical of logical expressions.


Types of Operators
• Arithmetic Operators
• Relational operators
• Logical operators
• Assignment operators
• Increment and Decrement operators
• Conditional operator
• Bitwise operators
• Special operators
Arithmetic Used to perform arithmetic operations
Operators Type: Binary (works on two operands)
Operands must be numbers

Result of
Operator Operation Example
operation

+ Addition 7+3 10
- Subtraction 7–3 4
* Multiplication 7*3 21
/ Division 7/3 2
% Modulus (Remainder after division) 7% 3 1

Note: All operands are assumed to be of integer data type.


Relational
Used to perform relational operations. ie: It checks the relation between two operands and returns
the result as true or false ( Boolean: 1 or 0)

Operators Type: Binary (works on two operands)

Operands must be numbers. It can also be expressions or functions which results in a numeric value.

Result of
Operator Operation Example
operation

< Less than 7<3 0


> Greater Than 7>3 1
== Equal to 7 == 3 0
<= Less than or equal to 7 <= 3 0
>= Greater than or equal to 7 >= 3 1
!= Not equal to 7 != 3 1
Used to perform logical operations. ie It performs logical analysis of its operands and produces a True or false result
Logical ( Boolean: 1 or 0)

Operators Type: && and || are Binary (works on two operands)


! is Unary (Only one operand)

Operands can be Boolean values. It can also be expressions or functions which results in a Boolean value.

Result of
Operator Operation Examples
operation
0 && 0 0
0 && 1 0
&& Logical AND
1 && 0 0
1 && 1 1
0 || 0 0
0 || 1 1
|| Logical OR
1 || 0 1
1 || 1 1
!0 1
! Logical NOT
!1 0
Assignment Used to assign values to a variables
Type: Binary (works on two operands)
Operators
Operands must be numbers
Let x= 5 initially for all examples
Result of
Operator Operation Example Meaning operation
(value of x)
= Assign value from right to left x=2 x=2 2
+= Add and assign x += 2 x=x+2=5+2 7
-= Subtract and assign x -= 2 x=x-2=5-2 3
*= Multiply and assign x *= 2 x=x*2=5*2 10
/= Divide and assign x /= 2 x=x/2=5/2 2
%= Modulus operation and assign x %= 2 x=x%2=5%2 1
&= Bitwise AND and assign x &= 2 x=x&2=5&2 0
|= Bitwise OR and assign x |= 2 x=x|2=5|2 7
^= Bitwise XOR and assign x ^= 2 x=x^2=5^2 7
<<= Bitwise shift left and assign x <<= 2 x = x << 2 = 5 << 2 20
>>= Bitwise shift right and assign x >>= 2 x = x >> 2 = 5 >> 2 1
Increment
Used to perform increment / decrement operations

& Type: Unary (works on single operand)

Decrement Operands can be numeric variable constants. It can also be expressions or functions returning a
number.

Result of
Operator Operation Example
operation
Let x = 5 and y = 7.
++ Increment x++ 6
-- Decrement y-- 6

These operators can be prefixed or post fixed.


x++ is post increment which returns the value of x first then increments x by 1
++ x is pre increment which returns the value of x incremented by 1
y-- is post decrement which returns the value of y first then decrements y by 1
--y is pre decrement which returns the value of y decremented by 1
This can be used instead of an if else statement to perform operations based on a condition
Conditional
Operators Type: Ternary (works on three operands)

Note: Let x= 5 & y = 2

Operator Operation Example Result


(It can be used in two methods)

If expression 1 is
true, Expression 2
Method 1 is executed;
Expression 1? Expression 2 : Expression 3 If expression 1 is (x<y) ? printf(“%d”, x) : printf(“%d”, y); 2
false Expression 3
is executed

If expression is
true, value 1 is
assigned to
Method 2 variable;
Variable = Expression ? Value 1: Value 2 If expression is z = (x != y) ? (x+100) : (x-100); 105
false value 2 is
assigned to
variable
Used to perform bitwise operations.
Bitwise
Operators Type: &, |, <<, >> and ^ are Binary (works on two operands)
~ Unary (works on single operand).

Operands must be numbers. It can also be expressions or functions which results in a numeric value.

Result of
Operator Operation Example
operation
& Bitwise AND 4&2 0
| Bitwise OR 4|2 6
~ Bitwise one’s compliment ~4 -5
^ Bitwise XOR 4^2 6
>> Bitwise Right shift 4 >> 2 1
<< Bitwise Left shift 4<<2 16

4 & 2 bitwise 4 & 2 bitwise ~4 bitwise 1’s 4^ 2 bitwise XOR


4>> 2 bitwise right 4 << 2 bitwise left
AND operation OR operation compliment operation operation
shift operation shift operation
1 0 0 1 0 0 00000100 00000100
00000100 00000100
0 1 0 0 1 0 ---------------- 00000010
---------------- ----------------
---------------- ---------------- 11111011 ----------------
00000001 00010000
0 0 0 1 1 0 (2’s complement form) 00000110
Result = 1 Result = 16
Result = 0 Result = 6 Result = -5 Result = 6
Special Used to perform special operations

Operators
Let char c;
int x=4, *p;

Result /
Operator Operation Example Meaning of
operation
Returns the right side operand value. Both
operands can be expressions resulting in a x = ( (4+2) , (++x) )
, 5
value. Both expressions will be executed but
result of first expression is discarded.
sizeof(char) 1
sizeof Size of a data type or memory location sizeof(c) 1
sizeof(x) 4
& Address of a memory location &x Address of x
Value of the
variable, that
* Pointer *p
the pointer p
points to
Expressions
• The combination of operators and operands is said to be an expression.
Arithmetic Expressions
• An arithmetic expression is a combination of variables, constants, and operators
arranged as per the syntax of the language.
• Example: a = x + y;
• Expressions are evaluated using an assignment statement of the form

variable = expression;
Operator Precedence

Operator precedence determines which operator is performed first in


an expression with more than one operators with different precedence.

Eg: 10 + 20 * 30 is calculated as 10 + (20 * 30)

Operators Associativity

Operators Associativity is used when two operators of same precedence


appear in an expression. Associativity can be either Left to Right or
Right to Left.

Eg: ‘*’ and ‘/’ have same precedence and their associativity is Left to
Right, so the expression “100 / 10 * 10” is treated as “(100 / 10) * 10”.
Operator Precedence and Associativity
Example 1:-
Example 2:-
• The red colored portion of the expression represents the order of execution based on
operator precedence and associativity.

Y = (3+2*2)*5 == 0 ? 10 : 20 ;
Y = (3+2*2)*5 == 0 ? 10 : 20 ;
Y = (3+2*2)*5 == 0 ? 10 : 20 ;
Y = (3+4)*5 == 0 ? 10 : 20 ;
Y = (7)*5 == 0 ? 10 : 20 ;
Y = 35 == 0 ? 10 : 20 ;
Y = 0 ? 10 : 20 ;
Y = 20 ;
Data Types in C Data Types in C

Primary data Derived data types User defined data


Data type in a programming types types

language represents the type of data it


Integer Array Structure
deals with. The data type of a value
determines the types of operations Character Pointer union

that can be performed on it. All


variables, arrays, functions must be Floating point Functions Enumerated

declared as one of the data types.


Boolean Typedef

Void
PRIMARY DATA TYPES

Integer
Integers datatype holds integer numbers

Keyword to declare an integer variable : int


Datatype Example of declaration : int num;
here the variable num is declared as
int type.
Format Specifier : %d

Memory Size : 4 bytes


Value range : 232 values
From -232 to (232-1)
Examples of values int type can hold : 10, 35, 0, -102, -900
Variants Format specifier Memory size

short Int (or short) %hd 2 bytes


unsigned short int %hu 2 bytes
int (or signed int) %d 4 bytes (minimum 2 bytes)
unsigned int %u 4 bytes (minimum 2 bytes)
long int (or long) %li 4 bytes minimum
long long int %lli 8 bytes minimum
Character Character datatype is used to hold characters. Only one character can be stored in a char variable

char
Datatype
Keyword to declare an character variable :
Example of declaration : char ch;
here the variable ch is declared as char
type.
Format Specifier : %c

Memory Size : 1 byte


Value range : 28 values
From -28 to (28-1) ie. -128 to 127
Examples of values char type can hold : ‘d’, ‘Y’, ‘5’, ‘9’, ’32’, -’27’
char is basically an int type with 1 byte memory space
when we store a character in a char variable, it is given within single quotes and the corresponding ASCII value is actually stored in it.
We can also store an integer as in the example without the quotes.
%c format specifier can be used to print the character
%d format specifier can be used to print corresponding ASCII value

Variants Format specifier Memory size

char (or signed char) %c 1 byte


unsigned char %c 1 byte (value range: 0
to 255)
Floating
Floating point datatype are used for real numbers

Keyword to declare an float variable : float


Point Example of declaration : float var;

Datatype
here the variable var is declared as
float type.
Format Specifier : %f

Memory Size : 4 bytes


Value range : From -3.4 x 1038 to 3.4 x 1038
6 decimal place Precision

Examples of values float type can hold : 3.5, +512.4543, -86.784 Decimal form - using %f
8.964578e+02 Exponential
form – using %e
Variants Format specifier Memory size

float %f 4 bytes
double %lf 8 bytes
Long double %Lf 16 bytes
Boolean This datatype is used to hold boolean values. ie 1 or 0 to represent true or false respectively

bool
Datatype
Keyword to declare an Boolean variable :
Example of declaration : bool B;
here the variable B is declared as bool
type.
Examples of values bool type can hold : 0,1

Format Specifier : %d can be used to print bool values

Memory Size : 1 byte. But actually utilizes only one bit.

Value range : 2 values


0 and 1

stdbool.h library must be included to use bool datatype

Void
This datatype represents no value.
It used for declaring functions having no return value.

Datatype Keyword to declare void function : void


Data Types in C Data Types in C

Primary data Derived data types User defined data


Data type in a programming types types

language represents the type of data it


Integer Array Structure
deals with. The data type of a value
determines the types of operations Character Pointer union

that can be performed on it. All


variables, arrays, functions must be Floating point Functions Enumerated

declared as one of the data types.


Boolean Typedef

Void
DERIVED DATA TYPES

Array
Used for storing a set of elements of same datatype (one dimensional / multi dimensional)

Keyword : Keyword used is that of the basic data type.

Example : int array[10]


one dimensional integer array with 10 elements capacity
DETAILED EXPLANATION IN MODULE 3

Pointer
Used for storing address of a memory location

The operator * is used to make a variable of pointer type.

Example : int *ptr;


here ptr is a pointer variable pointing to int value.
DETAILED EXPLANATION IN MODULE 5

Functio
A function is a set of code that performs some specific task or a set of tasks.

n Example
returns int data.
: int sum ( int a, int b);
Sum is declared as a function which takes two arguments a and b of int data type and

DETAILED EXPLANATION IN MODULE 4


Data Types in C Data Types in C

Primary data Derived data types User defined data


Data type in a programming types types

language represents the type of data it


Integer Array Structure
deals with. The data type of a value
determines the types of operations Character Pointer Union

that can be performed on it. All


variables, arrays, functions must be Floating point Functions Enumerated

declared as one of the data types.


Boolean Typedef

Void
USER DEFINED DATA TYPES
Structure To make a collection of variables of same or different data types
Keyword : struct

Example : struct Library {


char bookName[25];
int year;
} book;
book is declared as struct Library type with two members of char array type and int type
Memory allocation is that of the size of all the members.

DETAILED EXPLANATION IN MODULE 4

To make a collection of variables of same or different data types.


Union But in the case of union only one member of a union can contain a value at a time

Keyword : union
Example : union Library {
char bookName[25];
int year;
} book;
book is declared as union Library type with two members of char array type and int type
Memory allocation is that of the member with largest size.

DETAILED EXPLANATION IN MODULE 4


Enumerated This datatype can be used to assign names to constants. It just increases the readability of code.

Keyword: enum
Syntax : enum enumName { member1, member2,…… member N };
The enumName is the name of enumeration having members member1, member2
etc.
Example : enum Trimester { July, August, September, October};
July, August, September, October are the members of enumerated type Trimester
by default the value of first member is 0, second member 1, third member 2, …
ie in this example by default July = 0, August = 1, September = 2, October = 3
we can also provide alternate values inside the definition like
enum Trimester { July = 1, August = 2, September = 3, October = 4};

Declaration: To declare a variable as enum Trimester type, the following can be written.
enum Trimester t;
t is declared as enum Trimester type.
t can take the values of the enumerated type ie. July, August, September
or October.
Typedef This is used to give a new name to an existing datatype.

Keyword: typedef

Syntax : typedef dataType newName;


dataType is the existing data type name and newName is the new name given
to it.

Example : typedef unsigned int positive;


A new name positive is given to the existing datatype unsigned int
Now we can declare a variable x as unsigned int type by writing
positive x;
instead of unsigned int x;
Input Output functions in C
scanf()
It is used to read data from a standard input device like keyboard.
This function is defined in stdio.h library
Syntax:
scanf ("formatSpecifiers", argumentList);

formatSpecifiers Specifies the data type of the data to be read from the keyboard
Common format specifiers are
%c character
%d integer
%f float
%lf double
%s string
argumentList: The list of address locations to which the data from input device need to be stored.
Input Output functions in C
printf()
It is used to display formatted data on a standard output device like an LCD screen.
This function is defined in stdio.h library
Syntax:
printf ("formatSpecifiers and/or strings", argumentList);

formatSpecifiers Specifies the data type of the data to be read from the keyboard
Common format specifiers are
%c character
%d integer
%f float
%lf double
%s string
strings: Any combination of strings and escape sequences can be given within double quotes to display on screen.
argumentList: The list of values to display
Output:
Control Flow Statements
• If Statement

• Switch Statement
Decision Making Statements

• Conditional Operator

• Unconditional Branching using goto statement

• While Loop
Looping Statements
• Do While Loop

• For Loop

• Break and Continue statements


If Statement

• A two-way decision statement and is used in conjunction with an


expression

Syntax

if (test expression) {

// statements to be

// executed if the

// test expression is true

}
• If the test expression is evaluated to true, statements inside the body of if are executed.

• If the test expression is evaluated to false, statements inside the body of if are not executed.
If Statement (Flowchart)
If else Statement

• An extension of simple if statement where the false


condition of the expression is also considered.

Syntax
if (condition) {
// statements to be executed if the test expression is true
}
else {
// statements to be executed if the test expression is false
}
If else Statement (Flowchart)
Nested if Statement

• When a series of decisions are involved, we may have to use


more than one if-else statements in the nested form.

Syntax
if (condition1) {
// Executes when condition1 is true
if (condition2) {
// Executes when condition2 is true.
}
}
Nested if Statement (Flowchart)
if - else if - else ladder Statement
• Another way of putting ifs together when multipath decisions are involved.

Syntax
if (condition 1) {
//statements if condition 1 is true
}
else if (condition 2) {
//statements if condition 2 is true
}
else if (condition 3) {
//statements if condition 3 is true
}
.
.
.
else {
// statements if all the above conditions are false
}
if else ladder Statement (Flow chart)
Switch Statement
• Tests the value of a given variable (expression) against a list of case values and when a match is found, a
block of statements associated with that case is executed.

Syntax
switch (n) {
case 1: // code to be executed if n = 1;
break;
case 2: // code to be executed if n = 2;
break;
case 3: // code to be executed if n = 3;
break;
.
.
.

default: // code to be executed if n doesn't match any cases


}
Switch Statement (Flow Chart)
Conditional Operator

• Unusual operator useful for making two-way decisions.

• This operator takes 3 operands

Syntax

conditional expression ? expression 1: expression 2;

• The conditional expression is evaluated first. If the result is non-


zero(true), expression 1 is evaluated and is returned. Otherwise
(false), expression 2 is evaluated and its value is returned.
go to statements in C
• The goto statement is a jump statement which is sometimes also
referred to as unconditional jump statement.
• The goto statement can be used to jump from anywhere to anywhere
within a function.

Forward Jump Backward Jump


LOOPING STATEMENTS IN C
• Differentiate Entry controlled and
Exit controlled loop statements
with example
While Statement (entry controlled loop)

• Here the test condition is evaluated and if the condition is true, then the body
of the loop is executed.

• After the execution of the body, the test condition is once again evaluated and if
true only, the body will be executed once gain.

• This continues until the test expression becomes false and the control is
transferred out of the loop.

Syntax
while (test_expression)
{
// statements

update_expression;
do while Statement (exit controlled loop)
• Here the body of the loop will be executed at least once before the test is
performed.
• On reaching the do statement, the program proceeds to evaluate the body of
the loop first. At the end of the loop, the test condition in the while statement is
evaluated.
• If the condition is true, the program continues to evaluate the body of the loop
once again. This process continues as long as the condition is true.
• When the condition becomes false, the loop will be terminated and the control
goes to the statement that appears immediately after the while statement.
do while Statement (exit controlled loop)
Syntax
do
{
// loop body

update_expression;
}
while (test_expression);
for statement (entry controlled loop)

• another entry controlled loop

Syntax
for (initialization expr; test expr; update expr)
{
// statements in the loop
}
for Statement (entry controlled loop)

Execution order
• The initialization expr step is executed first, and only once. This step allows you
to declare and initialize any loop control variables. You are not required to put a
statement here, as long as a semicolon appears.
• Next, the test expr is evaluated. If it is true, the body of the loop is executed. If it
is false, the body of the loop does not execute and the flow of control jumps to the
next statement just after the 'for' loop.
• After the body of the 'for' loop executes, the flow of control jumps back up to the
update expr statement. This statement allows you to update any loop control
variables. This statement can be left blank, as long as a semicolon appears after
the condition.
• The condition is now evaluated again. If it is true, the loop executes and the
process repeats itself (body of loop, then increment step, and then again
condition). After the condition becomes false, the 'for' loop terminates.
continue and break statements in C

• break statement: the break statement terminates the smallest


enclosing loop (i. e., while, do-while, for or switch statement)

• continue statement: the continue statement skips the rest of the


loop statements and causes the next iteration of the loop to take
place.
#include <stdio.h>
int main() {
int n, i, sum = 0;

printf("Enter a positive integer: ");


scanf("%d", &n);

for (i = 1; i <= n; ++i) {


sum += i;
}

printf("Sum = %d", sum);


return 0;
}
// C program to print the sum of all odd numbers from 1 to n

#include <stdio.h>

int main()
{
int i, n, sum=0;

/* Input range to find sum of odd numbers */


printf("Enter upper limit: ");
scanf("%d", &n);

/* Find the sum of all odd number */


for(i=1; i<=n; i+=2)
{
sum += i;
}

printf("Sum of odd numbers = %d", sum);

return 0;
}
#include <stdio.h> // Include the standard input/output header file.
int main() { int i, n, sum = 0; // Declare variables 'i' for loop counter, 'n' for
user input, and 'sum' to store the sum.
printf("Input number of terms : "); // Print a message to prompt user input.
scanf("%d", &n); // Read the value of 'n' from the user.
printf("\nThe odd numbers are :"); // Print a message indicating that odd numbers
will be displayed.
for (i = 1; i <= n; i++) { // Start a loop to generate odd numbers based on user
input.
printf("%d ", 2 * i - 1); // Print the odd number. sum += 2 * i - 1; // Add the
odd number to the running sum. }
printf("\nThe Sum of odd Natural Number upto %d terms : %d \n", n, sum); // Print
the sum of odd numbers.
return 0; }

You might also like