0% found this document useful (0 votes)
5 views169 pages

Module 2 C Programming Constructs

Module 2 covers the fundamentals of C programming, including its basic structure, programming paradigms, and various constructs such as data types, variables, and operators. It explains the execution process of C programs, the role of preprocessor directives, and the types of files used in C programming. Additionally, it discusses the different types of tokens, constants, and variable declarations, along with examples of arithmetic and increment/decrement operators.

Uploaded by

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

Module 2 C Programming Constructs

Module 2 covers the fundamentals of C programming, including its basic structure, programming paradigms, and various constructs such as data types, variables, and operators. It explains the execution process of C programs, the role of preprocessor directives, and the types of files used in C programming. Additionally, it discusses the different types of tokens, constants, and variable declarations, along with examples of arithmetic and increment/decrement operators.

Uploaded by

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

Module 2

C Programming Constructs
Introduction to C
Contents
• Basic structure of a C program and execution process.

•Pre-processor directives

• Constants and Variables

• Operators,

•Primitive data types

• Type casting

• I/O statements and format specifications.

Control statements

•Decision making and Loop control structure

•Unconditional control transfer statements


Overview C program
• C is a general-purpose, procedural, structured language.

• Computer programming language developed by Dennis MacAlistair


Ritchie was an American computer scientist. He created the C
programming language.

• C language was developed on UNIX and was invented to write UNIX


system software.

• It is portable and It can extend itself.

• C is easy to learn.
Programming Paradigm
• Paradigm can also be termed as a method to solve problems or do tasks. A programming paradigm is an
approach to solving a problem using some programming language or it is a method to solve a problem
using tools and techniques that are available to us following some approach

1. Monolithic Programming Paradigm

• It is also known as the imperative(commanding) programming paradigm. The whole program is written in a
single block in this programming paradigm. We use the goto statement to jump from one statement to
another statement. It uses all data as global data which leads to data insecurity.

2. Procedural Programming

Procedural programming is a programming paradigm derived from imperative programming based on the
procedure call concept. Procedures contain a series of computational steps to be carried out.
Programming Paradigm
3. Structured Programming

• Structured programming, or modular programming, is a programming paradigm that facilitates the creation of
programs with readable code and reusable components. All modern programming languages support
structured programming, but the mechanisms of support, like the programming language’s syntax, may
vary.

4. Object Oriented Programming

Object-oriented programming (OOP) is a programming style characterized by identifying classes of objects


closely linked with the methods (functions) with which they are associated. It also includes ideas of
inheritance of attributes and methods.
Basic Structure of C program
Basic Structure of C program
Documentation section :consists of a set of comment line giving the name of
the program, the author name, and other details. Compiler ignores these
comments when it translates the program into executable code.
C uses 2 different formats
1. Block comments /*this is multi line comments*/
2. Line comments //this is single line comments
The Link section: provides instruction to the compiler to link functions from
system library. This Section is also called as pre-processor Statements.
Basic Structure of C program
The definition section: defines all symbolic constants
eg: #define PI 3.1415.

Global Declaration section: there are some variables that are used in more
than on function, such a variable are called global variable and are declared
in the global declaration section that is outside of all functions. This section
also defines user defined functions.
Basic Structure of C program
Every C program must have one main () function section. This section contains two parts
declaration part and executable part

Declaration part : declares all the variables


Executable part: There is at least one statement in an executable part.

These two part must appear at the beginning of the brace and ends at the closing brace. All
statement in the declaration and executable part ends with semicolon (;).

The sub program section: contains all the user defined functions that are called in the main
function although they appear in any order.
Basic Structure of C program
/* Display my details */
#include <stdio.h> // PREPROCESSOR DIRECTIVES
void main() //MAIN FUNCTION/ENTRY POINT
{
printf("Name: Amrutha\n"); //BODY OF MAIN FUNCTION
printf("Dept: CSE\n");
printf("Collge: MITE\n");
}
/* C program to display Area of a circle */ // DOCUMENTATION SECTION
#include<stdio.h> // PREPROCESSOR DIRECTIVES
#define pi 3.142 // DEFINITION SECTION
void hello(); // GLOBAL DECLERATION
void main( ) //MAIN FUNCTION/ENTRY POINT
{
int r =5, Area; //VARIABLE DECLERATION
Area= pi*r*r;
printf(“Area of a Circle= %d\n", Area); //BODY OF MAIN FUNCTION
}
void hello() // USER DEFINED FUNCTION
{ printf("Hello");
}
Executing a C program
Executing a C
program
Files used in C program
A C program uses four types of files as follows:
Files used in C program
A C program uses four types of files as follows:

1. Source Code File


•This file includes the source code of the program.
•The extension for these kind of files are '.c’.
• It defines the main and many more functions written in C.
•main() is the starting point of the program. It may also contain other
source code files.
Files used in C program
A C program uses four types of files as follows:

2. Header Files
They have an extension '.h'. They contain the C function declarations and macro definitions
that are shared between various source files.
C provides us with some standard header files which are available easily.
Common standard header files are:
i) string.h – used for handling string functions.
ii) stdlib.h – used for some miscellaneous functions.
iii) stdio.h – used for giving standardized input and output.
iv) math.h – used for mathematical functions.
v) conio.h – used for clearing the screen.
Files used in C program
A C program uses four types of files as follows:

3. Object files
•They are the files that are generated by the compiler as the source code file is processed.
•These files generally contain the binary code of the function definitions.
•The object file is used by the linker for producing an executable file for combining the object
files together. It has a '.o' extension.
4. Executable file
•This file is generated by the linker.
•Various object files are linked by the linker for producing a binary file which will be executed
directly.
•They have an '.exe' extension.
Pre Processor Directives
Preprocessor Directives:-Preprocessor is a program which is invoked by the
compiler before the compilation of the user written program.
–The declaration of preprocessor statements always begin with # symbol
–These statements are usually placed before the main( ) function.
Types of Preprocessors:-
–Macros
–File Inclusion
–Conditional compilation
–Other directives
Pre Processor Directives
Macros:-These are the piece of code in the program which is given

some name.

• Whenever the name is encountered by the compiler in the program

, the compiler replaces the name with the actual piece of code.

• The “#define” directive is used to define a macro.


Pre Processor Directives
Macros:-
/* C program to demonstrate macros */
# include<stdio.h>
# define pi 3.142
void main()
{
float r,area;
printf("Enter the value of radius\n");
scanf("%f",&r);
area=pi*r*r;
printf("Area of circle = %f\n",area);
}
Pre Processor Directives
File Inclusion:-This type of preprocessor directive tells the compiler to

include a file in the source code program

• These files contains the definition of the predefined functions like

printf( ), scanf( ), etc. Different functions are declared in different

header files.
Pre Processor Directives
File Inclusion:-
/* C program to demonstrate file inclusion */

#include<stdio.h>
#include<math.h>
void main()
{
int num, root;
printf("Enter a number\n");
scanf("%d",&num);
root=sqrt(num);
printf(“squareroot= %d\n", root);

}
Pre Processor Directives
Conditional Compilation:-these are the type of directives that
helps to compile a specific portion of the program or to skip a
specific part of the program based on some conditions.

Some of the conditional compilation directive are: – #ifdef,


#ifndef, #if, #else
Pre Processor Directives
Conditional Compilation:-
/* C program to demonstrate use of #ifdef*/
#include<stdio.h>
#define age 18
void main()
{
#ifdef age
printf("The person is eligible to vote");
#endif
}
Pre Processor Directives
Other Directives:-Apart from the above directive there are two more directives

which are not commonly used

#undef directive:-this directive is used to undefined a value which was declare

using the #define directive

#pragma directive:-this directive is used in parallel programming (thread

programming) which is a major concept of operating system.


C Tokens
C has 6 Different types of tokens. C programs are written using these tokens.

[Link] : Keywords are reserved words that have special meaning in


compiler
ii. Identifiers: the names supplied for variables, types, functions, and labels
in the program
iii. Constants: is a name given to the variable whose values can't be altered
or changed.
iv. Strings: is a sequence of characters
v. Operators: Its is used to perform some operations
vi. Special symbols: the special symbols have some special meaning and
they cannot be used for other purposes.
C Tokens

for
const
else
C Tokens
•Identifiers: These are the names given to various elements of

the C program like variables, functions, arrays, etc. These are

user defined names and consist of sequence letters, digits or

underscore.
C Tokens
• Rules to define an Identifiers
1. The first character of the identifier must always be a letter or an underscore
followed by any number of letters digits or underscore.

2. Keywords cannot be used as identifiers or variables.

3. An Identifier or a variable should not contain two consecutive underscores

4. Whitespaces and special symbols cannot be used to name the identifiers.

5. Identifiers are case sensitive


Constants in C
• Constants refer to fixed values that the program may not alter during its
execution. These fixed values are also called literals.

• for example: 10, 20, 'a', 3.4, "c programming" etc.

Constant Example
Decimal Constant 10, 20, 450 etc.
Real or Floating-point 10.3, 20.2, 450.6 etc.
Constant
Octal Constant 021, 033, 046 etc.
Hexadecimal Constant 0x2a, 0x7b, 0xaa etc.
Character Constant 'a', 'b', 'x' etc.
String Constant "c", "c program", "c in javatpoint" etc.
Constants in C
2 ways to define constant in C
1. const keyword

2. #define preprocessor
Variables
• A variable is nothing but a name given to a storage area that our programs
can manipulate.

• Each variable in C has a specific type, which determines the size and layout
of the variable's memory.

• A variable can be composed of letters, digits, and the underscore character.


Variable Declaration
• Variables should be declared in the C program before it is used
data_type variable_name;
int age = 20; value
Data type Variable name
Void main()
{
int a,b;
}
Types of Variables
[Link] Variable
A variable that is declared and used inside the function or block is called local
variable.
It cannot be used outside the block. Local variables need to be initialized before
use.
Types of Variables
2. Global Variable
A variable that is declared outside the function or block is called a global
variable.
It is declared at the starting of program. It is available to all the functions.
Rules To Declare Variables
• Name your variables based on the terms of the subject area, so that the

variable name clearly describes its purpose.

• Every variable name should start with alphabets or underscore (_).

• No spaces are allowed in variable declaration.

• Except underscore (_) no other special symbol are allowed in the middle of the

variable declaration (not allowed -> roll-no, allowed -> roll_no).


Rules To Declare Variables
• Maximum length of variable is 8 characters depend on compiler.

• Every variable name always should exist in the left hand side of assignment

operator (invalid -> 10=a; valid -> a=10;).

• No keyword should access variable name (int for <- invalid because for is

keyword).
Types of Variables
Types of Variables
3. Static Variable
Static variables have a property of preserving their value even after they are out
of their scope.

A static variable is the one allocated “statically,” which means its lifetime is
throughout the program run.

It is declared with the 'static' keyword and persists its value across the function
calls.
Types of Variables
3. Static Variable By default
• which means the variable remains in memory throughout the life of
the program

#include <stdio.h>
Output:
void main()
a= 0
{

static int a=0;

printf(“a=%d ", a);

}
Data Types used in C
• String (or str or text). Used for a combination of any characters that appear
on a keyboard, such as letters, numbers and symbols.

• Character (or char). Used for single letters.

• Integer (or int). Used for whole numbers.

• Float (or Real). Used for numbers that contain decimal points, or
for fractions.

• Boolean (or bool). Used where data is restricted


to True/False or yes/no options.
Data Type used in Variables
Integer
Character
Float
Double
Bool bool a=true, b= false;
String char a[10]=”MITE”;
Data Types used in C
• Integer (or int). Used for whole numbers.

#include <stdio.h> Output:


void main() The integer value is: 5
{
int i = 5;
printf(“The integer value is: %d \n”, i);
}
Data Types used in C
• Float (or Real). Used for numbers that contain decimal points, or
for fractions.

#include <stdio.h> Output:


void main() The float value is: 7.2357
{
float f = 7.2357;
printf(“The float value is: %f \n”, f);
}
Data Types used in C
• Character (or char). Used for single letters.

#include <stdio.h>
void main() Output:
{ The character value is: b
char c;
c = ‘b’;
printf(“The character value is: %c \n”, c);
}
Data Types used in C
•String (or str or text). Used for a combination of any characters
that appear on a keyboard, such as letters, numbers, alpha numeric
and symbols.
#include<stdio.h> Output:
int main() The string value
is :Greeks
{
char str[] = "Greeks";
printf(“The string value is %s",str);
}
Data Types used in C
•Boolean data type: Used to store true or false values.
#include <stdbool.h>
#include <stdio.h>
int main()
{
bool a=true, b=false;
printf("%d\n",a&&b);
printf("%d\n",a||b);
printf("%d\n",!b);
}
Operators used in C
• An operator is a symbol that tells the compiler to perform specific
mathematical or logical functions.

• C language has built-in operators & provides the following types of operators

1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Misc Operators
1. Arithmetic Operators
An arithmetic operator performs mathematical operations such as addition,
subtraction, multiplication, division etc. on numerical values (constants and
variables).
1. Arithmetic Operators
#include <stdio.h> // Working of arithmetic operators
int main()
{
int a = 9,b = 4, c,d,e,f,g;
c = a+b; //Addition
printf("a+b = %d \n",c);
d= a-b; // Subtraction
printf("a-b = %d \n",d);
e= a*b; //Mutiplication
printf("a*b = %d \n",e);
f = a/b; //Division
printf("a/b = %d \n",f);
g = a%b; //Modulus
printf("Remainder when a divided by b = %d \n",g);
}
2. Increment and Decrement Operators
C programming has two operators

1)Increment ++ To change the value of an operand

2)Decrement -- of an operand (constant or variable) by 1.


Increment ++ increases the value by 1
Decrement -- decreases the value by 1.
These two operators are unary operators, meaning they only operate on a single
operand.
Increment Operators
• Increment Operators are the unary operators used to increment or add 1 to
the operand value.

• The Increment operand is denoted by the double plus symbol (++). It has
two types:

Pre Increment and Post Increment Operators.


Increment Operators -Pre-increment Operator
The pre-increment operator is used to increase the original value of the operand
by 1 before assigning it to the expression.

#include<stdio.h>
void main()
{ int a = 10, b;
Here first the value of a
b = ++a;
increments and then is assigned
printf("b = %d\n\n", b);
printf("a = %d\n", a); to variable b. So both a and b
} value will be 11.
Increment Operators –Post-increment Operator
The post-increment operator is used to increment the original value of the
operand by 1 after assigning it to the expression.

#include<stdio.h>
void main()
{ Here first value of a(i.e., 10) is
int a = 10, b;
b = a++; assigned to b and then value of a is
printf("b = %d\n", b); incremented. So b = 10 and a = 11 is
printf("a = %d\n", a);
} printed.
Decrement Operator
Pre-increment
#include<stdio.h>
void main()
{
int a = 10, b;
b = --a;
printf("b = %d\n\n", b); Here first the value of a decrements
printf("a = %d\n", a); and then is assigned to variable b. So
}
both a and b value will be 9.
Decrement Operator
Post Decrement
#include<stdio.h>
void main()
{
int a = 10, b;
Here first value of a(i.e., 10) is
b = a--;
printf("b = %d\n\n", b); assigned to b and then value of a is
printf("a = %d\n", a); decremented So b = 10 and a = 9 is
}
printed.
3. Relational Operators
Relational operators in C are commonly used to check the relationship between
the two variables

return 0;
4. Logical Operators
These operators are used to perform logical operations on the given
expressions.
4. Logical Operators
#include <stdio.h>
void main()
{
int a = 10, b = 4, c = 10, d = 20;
if (a > b && c == d)
printf("a is greater than b AND c is equal to d\n");
else
printf("AND condition not satisfied\n");
if (a > b || c == d)
printf("a is greater than b OR c is equal to d\n");
else
printf("Neither a is greater than b nor c is equal d\n ");
}
5. Bitwise Operators
• Bitwise operator works on bits and perform bit-by-bit operation.
• The truth tables for &, |, and ^.

5. Bitwise Operators
5. Bitwise Operators
5. Bitwise Operators 70

Empty boxes will be marked as zero 24


6. Assignment Operators
6. Assignment Operators
7. Misc Operators
Besides the operators discussed above, there are a few other
important operators including sizeof and ? : supported by the C
Language.
Expressions in C
An expression is a formula in which operands are linked to each other by the use of
operators to compute a value.
example: A*B

There are 4 types of expressions:


1. Arithmetic expressions
2. Relational expressions
3. Logical expressions
4. Conditional expressions
Expressions in C
1. Arithmetic Expressions
Addition (+), Subtraction(-), Multiplication(*), Division(/), Modulus(%), Increment(++) and
Decrement(–) operators are said to “Arithmetic expressions”.
This operator works in between operands. like A+B, A-B, A–, A++ etc.
2. Relational Expressions
== (equal to), != (not equal to), != (not equal to), > (greater than), < (less than), >= (greater
than or equal to), <= (less than or equal to) operators are said to “Relational expressions”.
This operators works in between operands. Used for comparing purpose. Like A==B, A!=B,
A>B, A<B etc.
Expressions in C
3. Logical Expressions
&&(Logical and), ||(Logical or) and !(Logical not) operators are said to “Logical
expressions”. Used to perform a logical operation.
This operator works in between operands. Like A&&B, A||B,A!B etc.
4. Conditional Expressions
?(Question mark) and :(colon) are said to “Conditional expressions”. Used to perform a
conditional check. It has 3 expressions first expression is condition.
If it is true then execute expression2 and if it is false then execute expression3. Like
(A>B)?”A is Big”:”B is Big”.
Evaluation of Expressions in C
Evaluation of Expressions in C

Assignment Right to left 14


+= *= -=
Evaluation of Expressions in C
Evaluation of Expressions in C
Evaluation of Expressions in C
a=5

++a Is Incrementtor so
Executed First

10 + 4 * 3 / 2
1+2*5+3
4-2+6*3
a+b*a/b-a%b -> a=10,b=2
Evaluation of Expressions in C
1. If a=8, b=15 and c=4 calculate the expression
2*((a%5)*(4+(b–3)/(c+2)))
2. Evaluate the expression
a += b *= c -=5 , Given a=3, b=5, c=8.
3. Evaluate the expression
100 / 20 <= 10 – 5 + 100 % 10 – 20 == 5 >= 1 != 20
Evaluation of Expressions in C
Evaluation of Expressions in C
Evaluation of Expressions in C
Input/output statements in C
• Reading, processing, and writing of data are the three essential functional
functions of a computer program input and output operations.

• There are two methods of providing data to the program variables.


✔ One method is to assign values to variables( variable declaration)
✔ Another method for outputting results extensively(printf)

81
Input/output statements in C
• All input/output operations are carried out through function calls such
as printf and scanf.

• These functions are predefined in the respective header files.

• The input and output functions are used in the program whose functionality are
predefined in the header file “#include<stdio.h>”

82
MANAGING INPUT AND OUTPUT
Input and output functions are broadly classified into

A)Formatted Input Formatted Output

scanf () printf()

B) Unformatted Input Unformatted Output

1) getch() 1) putch()

2) getche() 2) putchar()

3) getchar()
83
MANAGING INPUT AND OUTPUT
A) Formatted Output:

1. printf(): It is a predefined function from the header<stdio.h>


It is used to write the formatted output.

printf : syntax printf(“format specifier”,var1,var 2);


• The number of format specifier must match the number of variables in the
variable list.

84
MANAGING INPUT AND OUTPUT
A) Formatted Output:

1. printf():

printf(“%d%c”,var1,var 2);
• format specifier indicates the type of data to be displayed

• variable list indicates the value present in the variable

85
MANAGING INPUT AND OUTPUT
A) Formatted Input:

1. scanf():
• scanf() function reads all type of data value from input device or from a file.

• The address operator “&” is used to indicate the memory location of the
variable.

• This memory location is used to store the data which is read through the
keyboard

86
MANAGING INPUT AND OUTPUT
A) Formatted Input:

1. scanf():
• syntax:
scanf(“format specifier”,addresslist);

• format specifier indicates the type of data to be stored in the variable.

• address list indicates the location of the variable where the value of the data is
to be stored
scanf(“%d %d”,&value1,&value 2);
87
Format specifications

88
C program to demonstrate Formatted Input and Output
Statements
#include<stdio.h>
void main()
{
int a, b, c, sum;
printf(“Enter three numbers\n”);
scanf(“%d%d%d”,&a,&b&c);
sum=a+b+c;
printf(“ Addition of three Numbers=%d\n”,sum);
}
89
C program to find the area of circle by reading the input from
keyboard
#include<stdio.h>
#define pi 3.14
int main()
{
int r;
float area;
printf("enter the radius of a circle\n");
scanf("%d",&r);
area=3.14*r*r;
printf("area of a circle is:%f",area);
return 0;
} 90
C program to find the area of circle by reading the input from
keyboard
#include<stdio.h>
int main()
{
int r;
float pi,area;
printf("enter the radius of a circle\n");
scanf("%d",&r);
printf("enter the value of pi\n");
scanf("%f",&pi);
area=pi*r*r;
printf("area of a circle is:%f",area);
return 0;
}
91
MANAGING INPUT AND OUTPUT
B) UnFormatted Input: b) getch(): pauses the Output Console until
a key is pressed
#include<stdio.h>
#include<conio.h>
void main()
{
printf("Waiting for a character to be pressed from the keyboard to
exit.\n");
getch();
} 92
MANAGING INPUT AND OUTPUT
B) UnFormatted Input: a) getche(): to read a single character from the keyboard
which displays immediately on screen without waiting for the enter key
#include<stdio.h>
#include<conio.h>
void main()
{
printf("Waiting for a character to be pressed from the keyboard to exit.\n");
getche();
}
93
MANAGING INPUT AND OUTPUT
B) UnFormatted Input: c) getchar(): reads a single character from the standard input
stream stdin, regardless of what it is, and returns it to the program.

#include<stdio.h>
void main()
{
char ch;
printf("Enter a character\n");
ch=getchar();
printf("The entered character is %c\n",ch);
}
94
MANAGING INPUT AND OUTPUT
B) UnFormatted Output: putchar(), puts()

putchar() function is used to write a character on standard


output/screen.
putchar()
In a C program, we can use putchar function as below.
putchar(char); where, char is a character variable/value.

puts() Used to print the string variable/value.

95
MANAGING INPUT AND OUTPUT
B) UnFormatted Output: getchar() and putchar()

#include<stdio.h>
int main()
{
char ch;
printf("Enter a character\n");
ch=getchar();
printf("The entered character is \n");
putchar(ch);
return 0;
} 96
MANAGING INPUT AND OUTPUT
B) UnFormatted Output: gets() and puts()

#include<stdio.h>
int main()
{
char s[30];
printf("Enter the string? ");
gets(s);
printf("You entered a string called:");
puts(s);
return 0;
} 97
Type Conversion:
Implicit Type Conversion: This type of conversion is done by the compiler, so

it is called as implicit type conversion. Without user intervention this process

is carried out.

• Whenever we are converting narrow operand (lower data type variable)

into wide operand (higher data type variable) then compiler will do it

implicitly.
Type Conversion:
Implicit Type Conversion

#include<stdio.h>
void main( )
{
char b= ‘A’;
int a;
a=b;
printf(“%d”,a);
}
OUTPUT: 65
Type Conversion:
Explicit Type Conversion/Type casting: This type of conversion is done by the

user, Instead of being done automatically according to the rules of the

language for implicit type conversion so it is called explicit type conversion.

Type casting is a mechanism in which one data type is converted to another data
type using a casting () operator by a programmer.
Type conversion allows a compiler to convert one data type to another data
type at the compile time of a program or code.
Type Conversion:
It is a process of converting an expression from one data type to
another data type
There are two types:
Implicit Type conversion
Explicit Type Conversion
Type Conversion:
Implicit Type Conversion

#include<stdio.h>
void main( )
{
char b= ‘A’;
int a;
a=b;
printf(“%d”,a);
}
OUTPUT: 65
Type Conversion:
Explicit Type Conversion:

Explicit type conversion


Conditional Branching and Loops.

104
Conditional statements
• Conditional statements are used to execute A set of statements on some
conditions.

• It provides A unit of block in which we can either execute one statement


or more than one statements.

• If the given condition is true then the set of statements are executed
otherwise body is skipped and next statement will be executed..

105
Conditional statements
• There are different types of Conditional statements
• IF Condition
• IF ELSE Condition
• Nested IF ELSE condition
• Cascaded if-else or else if ladder
• Switch Case

106
Conditional statements
1. IF CONDITION

• It is conditional statement, which is used to execute a set of statement on


some conditions.

• The condition must be of Boolean type expression.

• An expression, which returns only two value either TRUE or FALSE, is known
as Boolean type expression.

107
Conditional statements
1. IF CONDITION

Syntax: if (condition)

{ ………………..

……………….. }
If the Boolean expression evaluates to true, then the
block of code inside the 'if' statement will be executed.
If the Boolean expression evaluates to false, then the
first set of code after the end of the 'if' statement will
be executed 108
Conditional statements
1. IF CONDITION
#include<stdio.h>
int main()
{
int number;
printf("enter a number:");
scanf("%d",&number);
if(number==10)
printf("number is equals to 10");
return 0;
} 109
Conditional statements
2. IF ELSE CONDITION

• It is known as double blocked conditional statements.

• It means, it has TRUE parts as well as FALSE part.

• If the given condition is true then the true part is executed otherwise false part
is executed.

110
Conditional statements
2. IF ELSE CONDITION
Syntax: - if (CONDITION)
{ ………………..
}
else
{ ………………..
}
If condition returns true then the statements inside
the body of “if” are executed and the statements
inside body of “else” are skipped.
If condition returns false then the statements inside
the body of “if” are skipped and the statements in
“else” are executed.
111
Conditional statements
2. IF ELSE CONDITION
#include <stdio.h>
int main()
{
int age;
printf("Enter your age?");
scanf("%d",&age);
if(age>=18)
{
printf("You are eligible to vote...");
}
else
{
printf("Sorry ... you can't vote");
} 112
Conditional statements
3. NESTED IF ELSE

• Using One If Statement Within Another If Statement Is Known As Nested If


else Statement.

• Nested if statements are often used when you must test a combination of
conditions before deciding on the proper action.

113
Conditional statements
3. NESTED IF ELSE
if(conditional_expression1)
syntax-
{
if(conditional_expression2)
{
statement1;
}
else
{
statement2;
}
}
else
{
statement 3;
} 114
Conditional statements
3. NESTED IF ELSE

115
Conditional statements
4. Cascaded if-else or else if ladder

• With an if or if/else statement we evaluate a single true/false condition. A


cascaded if statement, on the other hand, makes it possible to evaluate
several conditions in a row. This type of if statement has several if code
blocks placed below each other, with optional else code at the end.

• Here the conditions are evaluated from top to bottom. As soon as the true
condition is found the statement associated with it is executed and the control
is transferred to statement X, skipping the rest of the ladder.

116
Conditional statements
4. Cascaded if-else or else if ladder

Syntax:

117
Conditional statements
4. Cascaded if-else or else if ladder

118
Conditional statements
5. SWITCH CASE CONDITION

• It is multiple conditioned checking statements, which is generally used for


menu- driven program.

• Where we have to select one option out of several options at a time. The
number of ―case within switch – statement is same as the number of
options present in menu.

• Each ―case is used to do only one work at a time.

119
Conditional statements
5. SWITCH CASE CONDITION

Syntax: switch(expression)
{
case constant1: statement
sequence
break;
case constant2: statement
sequence
break;
...
default: statement sequence
break;
} 120
121
#include <stdio.h> NESTED IF ELSE // Write a C program to check whether the
void main() person is eligible for work using nested if
{
int age; 1) If age is in between 18 – 60 eligible to
printf("Please Enter Your Age Here:\n");
work
scanf("%d",&age);
if (age >= 18)
2) If age >60 too old to work
if(age <= 60 ) 3) If age< 18 not eligible to work
{
printf("You are Eligible to Work \n");
}
else
{
printf("You are too old to work \n");
}
else
{
printf("Not Eligible to Work");
}
} 122
#include <stdio.h> Cascaded if-else or else if ladder
void main()
{ int num;
printf("Enter a number:\n"); // C Program to check whether
scanf("%d", &num); a number is positive,
if (num > 0) negative or zero using if else
{ if ladder
printf("Positive");
}
else if(num < 0)
{
printf("Negative");
}
else
{
printf("Zero");
}
} 123
#include<stdio.h>
Switch Statement
void main()
{
int Semester; // C Program to display the
printf(“Enter the Semester number:\n ");
scanf("%d", &Semester);
semester in which student is
printf("The semester you selected is : "); studying using switch
switch (Semester) { statement
case 1:
printf("First");
break;
case 2:
printf("Second");
break;
case 3:
printf("Third");
break;
default:
printf("Invalid Input");
break;
}
124
}
Introduction to Conditional looping statements.
• A set of statements have to be repeatedly executed for a specified number of
times until a condition is satisfied.

• The statements that help us to execute the set of statements repeatedly are
called as looping condition.

125
Introduction to Conditional looping statements.
• The various looping constructs in C are:

(i) while Loop

(ii) do-while Loop

(iii) for Loop structs or loop control statements.

126
Introduction to Conditional looping statements.
(i) while Loop

•The while loop evaluates the test Expression inside the parentheses ().

•If test Expression is true, statements inside the body of while loop are

executed. Then, test Expression is evaluated again.

•The process goes on until test Expression is evaluated to false.

•If test Expression is false, the loop terminates (ends).

127
Introduction to Conditional looping statements.
(i) while Loop

initialization;
while(test condition)
{
set of statements to be executed
including increment/decrement
opetator
}
128
Introduction to Conditional looping statements.
(i) while Loop

#include<stdio.h> // Print numbers from 1 to 5


int main()
{
int i = 1;
while (i <= 5)
{
printf("%d\n", i);
++i;
}
return 0;
}
129
Introduction to Conditional looping statements.
(i) while Loop

Step 1: initialized i to 1.

Step 2:When i = 1, the test expression i <= 5 is true. Hence, the body of the while loop is
executed. This prints 1 on the screen and the value of i is increased to 2.

Step 3:Now, i = 2, the test expression i <= 5 is again true. The body of the while loop is
executed again. This prints 2 on the screen and the value of i is increased to 3.

Step4: This process goes on until i becomes 6. Then, the test expression i <= 5 will
be false and the loop terminates. 130
Introduction to Conditional looping statements.
(i) while Loop

#include<stdio.h>
int main(){
int i=1,number;
printf("Enter a number: ");
scanf("%d",&number);
while(i<=10){
printf("%d \n",(number*i));
i++;
}
return 0;
}
131
Introduction to Conditional looping statements.
(ii) do- while Loop

• A do-while loop is similar to the while loop except that the condition is always executed

after the body of a loop. It is also called an exit-controlled loop.

• The body is executed if and only if the condition is true. In some cases, we have to execute

a body of the loop at least once even if the condition is false.

• This type of operation can be achieved by using a do-while loop. In the do-while loop, the

body of a loop is always executed at least once.

132
Introduction to Conditional looping statements.
(ii) do- while Loop

do
{

// the body of the loop


}

while (testExpression);
133
Introduction to Conditional looping statements.
(ii) do- while Loop

•The body of do...while loop is executed once. Only then,


the testExpression is evaluated.

•If testExpression is true, the body of the loop is executed


again and testExpression is evaluated once more.

•This process goes on until testExpression becomes false.

•If testExpression is false, the loop ends.


134
Introduction to Conditional looping statements.
(ii) do- while Loop

#include <stdio.h>
int main()
{
int j=0;
do
{ int j=4;
printf("Value of variable j is: %d\n", j);
j++;
}
while (j<=3);
return 0;
}

135
Introduction to Conditional looping statements.
(ii) do- while Loop

#include<stdio.h> // Program to add numbers until the user enters zero


int main()
{
int number, sum = 0;
do
{ / the body of the loop is executed at least once
printf("Enter a number: ");
scanf("%d", &number);
sum += number;
}
while(number != 0);
printf("Sum = %d",sum);
return 0;
} 136
Introduction to Conditional looping statements.
Difference between While and do- while Loop

137
Introduction to Conditional looping statements.
Difference between While and do- while Loop

138
Introduction to Conditional looping statements.
(iii) for loop

A for loop is a more efficient loop structure in 'C' programming which is used when the
loop has to be traversed for a fixed number of times. The for loop basically works on
three major aspects

(i) The initial value of the for loop is performed only once.

(ii) The condition is a Boolean expression that tests and compares the counter to a
fixed value after each iteration, stopping the for loop when false is returned.

(iii) The incrementation /decrementation increases (or decreases) the counter by a


set value.
139
Introduction to Conditional looping statements.
(iii) for loop
Syntax: for (initial value; condition; incrementation or decrementation )
{
statements;
}

140
Introduction to Conditional looping statements.
(iii) for loop

// Print numbers from 1 to 10


#include <stdio.h>
int main() {
int i;
for (i = 1; i < 11; ++i)
{
printf("%d ", i);
}
return 0;
}

141
3. Write a C program to print sum of first n natural numbers using
for loop
#include<stdio.h>
void main()
{
int n,i sum=0;
printf(“Enter the value of n\n”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
sum=sum+i;
}
printf(“Sum of natural numbers=%d\n”,sum);
}
Introduction to Conditional looping statements.
For LOOP While loop
The structure of for loop is –
Structure of while loop is-
for(initial condition;
Command While(condition){statements
number of iterations){//body
;//body}
of the loop }

Iterates for a preset number Iterates till a condition is


Iterations
of times. met.
Initialization in for loop is
Initialization is done every
Initialization done only once when the
time the loop is iterated.
program starts.
Used to obtain the result Used to satisfy the condition
Use only when the number of when the number of
iterations is known. iterations is unknown.143
Introduction to Conditional looping statements.
(iii) for loop

1.i is initialized to 1.
[Link] test expression i < 11 is evaluated. Since 1 less than 11 is true, the body of for loop is
executed. This will print the 1 (value of i) on the screen.
[Link] update statement ++i is executed. Now, the value of i will be 2. Again, the test expression
is evaluated to true, and the body of for loop is executed. This will print 2 (value of i) on the
screen.
[Link], the update statement ++i is executed and the test expression i < 11 is evaluated. This
process goes on until i becomes 11.
[Link] i becomes 11, i < 11 will be false, and the for loop terminates.
144
Introduction to Conditional looping statements.
(iv) Nested for loop
• Nested loop means a loop statement inside another loop statement. That is
why nested loops are also called as “loop inside loop“.

• In nested for loop one or more statements can be included in the body of the
loop.

• In nested for loop, The number of iterations will be equal to the number of
iterations in the outer loop multiplies by the number of iterations in the inner
loop.
145
Introduction to Conditional looping statements.
(iv) Nested for loop
• When the control moves from outer loop to inner loop the control remains
in the inner loop until the inner loop condition fails, once the condition fails
the control continues with the outer loop condition Again when the control
comes to inner loop the inner loop is reset to the initial value.

• The Nested for loop stops execution when the outer for loop condition fails

146
Introduction to Conditional looping statements.
(iv) Nested for loop

Syntax:

147
Introduction to Conditional looping statements.
(iv) Nested for loop

148
Introduction to Conditional looping statements.
(iv) Nested for loop #include <stdio.h>
int main()
{
int a, b;
for(a = 1; a <= 5; a++) Output for
{ inner loop
for(b = 1; b <= 5; b++)
{
printf("%d ", b);
}
printf("\n");
}
return 0;
} 149
Introduction to Conditional looping statements.
(iv) Nested for loop #include <stdio.h>
int main() {
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; ++i) Output for
{ inner loop
for (j = 1; j <= i; ++j)
{
printf("* ");
}
printf("\n");
}
return 0;
}
150
UnConditional looping statements.
• An unconditional statements are the statements which transfer the control or
flow of execution unconditionally to another block of statements. They are
also called jump statements.

• There are four types of unconditional control transfer statements.

(i) break

(ii)continue

(iii) goto

(iv)return
151
UnConditional looping statements.
i) break Statement: A break statement terminates the execution of the loop and
the control is transferred to the statement immediately following the loop. i.e.,
the break statement is used to terminate loops or to exit from a switch.

Syntax :

Jump-statement;

break;

152
UnConditional looping statements.
i) break Statement:

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

}
}
153
UnConditional looping statements.
(ii) continue statement: The continue statement is used to bypass the remainder
of the current pass through a loop.

The loop does not terminate when a continue statement is encountered.

Instead, the remaining loop statements are skipped and the computation
proceeds directly to the next pass through the loop.

154
UnConditional looping statements.
(ii) continue statement:

It is simply written as “continue”. The continue statement tells the compiler “Skip
the following Statements and continue with the next Iteration”.

Syntax :
Jump-statement;
Continue;

155
UnConditional looping statements.
(ii) continue statement:
#include<stdio.h>
int main()
{
int i=0;
for(i=0;i<=4;i++)
{
if(i==3)
continue;
printf("%d\t",i);
}
return 0;
}
156
UnConditional looping statements.
(iii)goto statement :

C supports the “goto” statement to branch unconditionally from one point to


another in the program.

Although it may not be essential to use the “goto” statement in a highly


structured language like “C”, there may be occasions when the use of goto is
necessary.

157
UnConditional looping statements.
(iii)goto statement :

The goto requires a label in order to identify the place where the branch is to be
made. A label is any valid variable name and must be followed by a colon (: ).

The label is placed immediately before the statement where the control is to be
transferred.

The label can be anywhere in the program either before or after the goto label
statement.

158
UnConditional looping statements.
(iii)goto statement :

Syntax:
goto label;
Forward jump Backward jump
............. goto label; ........... label: statement;
............. ............ ............
............. . ............. ………….
label: statement; goto label;
label: statement;
If the label statement is below the goto statement then it is called forward
jump. if the label statement is above the goto statement then it is called
backward jump
159
UnConditional looping statements.
(iii)goto statement :
#include<stdio.h>
#include<stdio.h> int main()
{
void main() printf(“MITE \t”);
{ goto label1;
printf(“MITE \t”); printf(“is \t in\t”);
printf(“is \t in\t”); label1:
printf(“Moodbidri\n”);
printf(“Moodbidri\n”);
Return 0;
} }

160
Write a C Program to check if the entered number is positive Negative or Zero
using goto statement..

161
UnConditional looping statements.
(iv) return statement :

• The return statement terminates the execution of a function and returns


control to the calling function.

• Execution resumes in the calling function at the point immediately


following the call. A return statement can also return a value to the calling
function.
• Syntax :
Jump-statement:

return expression;
162
UnConditional looping statements.
(iv) return statement :

#include <stdio.h>
void print() // User defined Function
{
printf("Welcome to C Programming");
}

int main()
{
// Calling print
print();

return 0;
} 163
3. Write a C program to print sum of first n natural numbers using
for loop
#include<stdio.h>
void main()
{
int n,i sum=0;
printf(“Enter the value of n\n”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
sum=sum+i;
}
printf(“Sum of natural numbers=%d\n”,sum);
} 164
4. Write a C program to print fibonacci series up to n numbers using for
loop

#include<stdio.h> else
void main() printf("%d\n%d\n",fib1,fib2);
{ for(i=3;i<=n;i++)
int n,i,fib1,fib2,fib3=0; {
printf("Enter the number of series to to be genetared:"); fib3=fib1+fib2;
scanf("%d",&n); printf("%d\n",fib3);
fib1=0; fib1=fib2;
fib2=1; fib2=fib3;
if(n==1) }
printf("%d\n",fib1); }
else if(n==2)
printf("%d\n%d\n",fib1,fib2);
165
4. Write a C program to print factorial of a given n numbers using for loop

#include<stdio.h>
Void main()
{
int i,fact=1,number;
printf("Enter a number: ");
scanf("%d",&number);
for(i=1;i<=number;i++)
{
fact=fact*i;
}
printf("Factorial of %d is: %d", number, fact);
}
166
Write a C program to determine eligibility for admission to a professional
course based on the following criteria:
Eligibility Criteria: Marks in Maths >=65 and Marks in Phy >=55 and
Marks in Chem>=50 and Total in all three subjects >=190 or Total in Maths
and Physics >=140.
Input the marks obtained in Physics:65
Input the marks obtained in Chemistry:51
Input the marks obtained in Mathematics:72
Total marks of Maths, Physics and Chemistry: 188
Total marks of Maths and Physics: 137 The candidate is not eligible.
167
168
169

You might also like