0% found this document useful (0 votes)
25 views

Unit - II C Fundamentals & Decision Control Statements C Fundamentals

The document discusses C fundamentals including keywords, identifiers, data types, variables, constants, and decision control statements. It defines keywords, identifiers, and various data types. It also covers variable declaration, constants, and decision control statements such as if, if-else, nested if, and switch statements.

Uploaded by

yv210904
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)
25 views

Unit - II C Fundamentals & Decision Control Statements C Fundamentals

The document discusses C fundamentals including keywords, identifiers, data types, variables, constants, and decision control statements. It defines keywords, identifiers, and various data types. It also covers variable declaration, constants, and decision control statements such as if, if-else, nested if, and switch statements.

Uploaded by

yv210904
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
You are on page 1/ 32

Unit – II

C Fundamentals & Decision Control Statements

C Fundamentals:
Keywords – Identifiers – Basic Data Types in C – Variables –
Constants – I/O Operators in C – I/O Statements (scanf, printf)
Decision Control Statements:
Introduction to Decision Control Statements – Conditional
Branching Statements: simple if, if..else, nested if, switch statements –
Programming Examples.

Keywords:
Keywords are predefined reserved words that have a specified meaning
and their meaning cannot be changed. They serve as basic block for program
statements.
We have 32 keywords which are used for high-level programming and 8
reserve words which are used for low-level programming.
32 keywords:

auto double int Struct


break else long Switch
case enum register Typedef
char extern return Union
const float short Unsigned
continue for signed Void
default goto sizeof Volatile
Do if static While

8 Reserve words
asm ada fortran far
huge pascal entry near

Identifiers:
Identifiers refer to the names of the variables, functions and arrays. These
are user-defined names consists of a sequence of letters, digits and a special character
i.e. _ (underscore).
Rules for Identifiers:
• First character can be a letter or _ (underscore).
• Underscore (_) should not be used as an identifier alone. It should be
within the alphabets.
• Identifiers must be from the character set.

1|Page
• Identifiers are case sensitive i.e. HAI, Hai and hai are three different
identifiers.
• Identifiers must not start with a digit, special character or a white space.
• Hyphen ( - ) should not be used in an identifier.
• Always avoid single character as an identifier.
• Identifiers can be of any length, but the number of characters in a variable
that are recognized by a compiler varies.
• Cannot use keywords as an identifiers.
Ex : valid Invalid
add “add”
num1 -num
count_1 count-1

Datatypes:
Data type is the description of nature of data either in numeric form or in
character form. It defines a set of values and the operations that can be performed on
them. C supports different classes of datatypes. They are :

Built-in Data Type or Primary Data Type :

2|Page
• Integer type are defined by the keyword int.
Ex: int a;
• Character type are defined by the keyword char.
Ex: char name;
• Float type are defined by the keyword float.
Ex: float average;
• String type are defined as char str[n];
Ex: char name[5];
Void:
The data type has no values. Void is a data type that which does not return any
value to the calling function.
The memory requirements for each data type will determine the permissible
range of values for that type, which may vary from one compiler to another. The size
and range of these data types differ which are shown below:
DATA TYPE SIZE RANGE
(bytes)
char or signed char 1 -128 to 127
unsigned char 1 0 to 255
int or signed int 2 -32,768 to 32,767
unsigned int 2 0 to 65,535
short int or signed short int 1 -128 to 127
unsigned short int 1 0 to 255
long int or signed long int 4 -2,147,483,648 to 2,147,483,647
unsigned long int 4 0 to 4,294,967,295
float 4 3.4e-38 to 3.4e+38
double 8 1.7e-308 to 1.7e+308
long double 10 3.4e-4932 to 1.1e+4932

User-Defined Data Type:


typedef:
C supports a feature known as “typedef (type definition)“ that allows users to
define an identifier that would represent an existing data type which can later be used
to declare variables. It is represented as
Syntax: typedef type identifier
where type refers to an existing data type and identifier refers to the new
name given to the data type.
Ex: typedef int marks;
Here marks symbolizes int. so that they can be later used to declare
variables as marks section1,section2;
where section1 and section2 are int data type.
Enumerated:
Another user-defined data type is “ enum “ (enumerated) data type. It is defined
as
Syntax: enum identifier {value1, value2, . . . . . valuen};

3|Page
where identifier is user-defined enumerated data type which can be used to
declare variables that can have one of the values enclosed within braces.
Ex: enum Boolean { true, false };
enum Boolean t, f;
t=true;
f=false;
So that the compiler will automatically assigns integer values beginning with 0.
That is the enumeration constant true is assigned 0, false assigned 1.

Variables:
A variable is a data name that is used to store data value in memory location.
Variables are quantities that vary during the program execution. Variables are used
for identification for entering the information or data. It contains the name of a valid
identifier. A variable can be chosen by a programmer in a meaningful way.

Rules for defining variables:


• A variable name may consist of letters, digits and _ (underscore).
• It should not be a keyword.
• White spaces are allowed.
• Both lower case and upper case are significant.
Ex: Hello is different from HELLO and hello.

Declaring the Variables:


• After defining the variable names, they must be declared to the compiler as it
reserves some memory and also specifies what type of data the variable will hold.
• A variable can be used to store a value of any data type.
• Variable must be separated by comma.
• All declarations must be terminated by a semicolon (;).
The syntax for declaring a variable is:
Syntax: data type variable1,variable2, . . . . . variable n;
Ex: int total;
Two types of variable declaration can be done. They are:
• Local Variables
• Global variables
Local Variables:
"Variables that are declared inside a function are called local variables.
Ex: #include <stdio.h>
void main()
{
int a,b,c; these are local variables
}
Global Variables:
Global Variable can be accessed throughout the entire program and may
be used by any piece of code. Global variables are created by declaring them outside
of a function.
4|Page
Ex: #include<stdio.h>
int a; these are global variables
void main()
{
int b,c; these are local variables
}
DATA TYPE KEYWORD
character char
integer int
floating point float
double floating point double
unsigned character unsigned char
signed character signed char
signed short integer signed short int or short
signed long integer signed long int
unsigned integer unsigned int
unsigned short integer unsigned short int
unsigned long integer unsigned long int
extended double floating point long double

Constants:
In a C program we either enter the data for input or to assign the data to some
identifier, there is a need of storage space so that the entered or assigned data can be
processed in a meaningful way. So, the processed data is stored in two forms by the C
program. These two forms are Constants or Variables. Constants are those quantities
whose value does not vary during the program execution of the program i.e. the value
is fixed.
Constants are mainly categorized into two types. Those are:
constant

numeric constant character constant(non-numeric)

integer constant real constant single character constant string constant

Numeric Constant:
These have numeric value with a combination of sequence of digits i.e.
from 0 to 9 as alone or combination of digits with or without decimal point having a
positive or negative sign. These are further classified into two types:
1. Integer Constant
2. Real Constant

5|Page
1. Integer Constant:
Integer numeric constants have integer data combination of 0to 9 without
any decimal point or without precision with positive or negative sign. These are
classified into three types. They are :
1. Decimal Integer Constant
2. Octal Integer Constant
3. Hexadecimal Integer Constant
Decimal Integer Constant:
• Integer constants have integer data combination of digits 0 to 9.
• It may have an optional sign, in case of absence considered as +.
• Commas, blank spaces and period should not be a part of it.
Ex :12, 3, -21 etc…
Octal Integer constant:
• It is a sequence of digits i.e. 0 . . . . 7.
• It may have an optional sign, in case of absence considered as +.
• Commas, blank spaces and period should not be a part of it.
• It should start with a “ 0 “(zero).
Ex : 012,-0213.
Hexadecimal Integer Constant:
• It is a sequence of digits i.e. (0 . . . . 9) (A . . Z) (a . . z).
• It may have an optional sign, incase of absence considered as +.
• Commas, blank spaces and period should not be a part of it.
• It should start with a “ OX or Ox “.
Ex : OX3b, Ox2.
2. Real Constant :
Constants having a decimal point or precision value within it having any
positive or negative sign is called Real numeric Constant. It is also called floating point
constant. Real numeric constants are further classified into two types.
They are:
1. Fractional form
2. Exponential form
Fractional form :
• Must have a decimal point.
• It may have an optional sign, incase of absence considered as +.
• Commas and blank spaces should not be a part of it.
Ex : 3.12,2.3
Exponential form :
This offers a convenient way for writing large and small real constants.
Ex: 3e4, 0.12e3

Character Constant :
Character constants have either a single character or group of characters
or a character with back slash used for special purpose. These are categorized into
three types including the back slash character constant. They are:

6|Page
1. Single Character Constant
2. String Character Constant
3. Backslash Character Constant
1. Single Character Constant :
Any character enclosed within a single quote (‘ ‘) is a Single character
constant. A single character constant may be a single letter, single digit,
or a special character placed within quotes. The maximum length of single
character constant is 1.
Ex : valid invalid
‘n’ ‘nitya’
‘3’ ‘321’
2. String Character Constant :
A string is the combination of characters or group of characters. A string
character constant or a string is enclosed within double quotes (“ “). The
maximum length of string character constant is 255 characters.
Ex : valid invalid
“nitya” “nitya
“hai welcome” hai welcome “
“welcome to 2013”
3. Backslash Character Constant :
These are used in output statements like printf(), puts() etc. The different
types of backslash characters are :
Backslash Meaning
constant
‘\a’ or “\a” Audible bell(to ring a beep)
‘\b’ or “\b” Backspace
‘\n’ or “\n” New line
‘\f’ or “\f” Form feed(move one page to next)used in only printing hard copy.
‘\t’ or “\t” Horizontal tab
‘\v’ or “\v” Vertical tab
‘\r’ or “\r” Carriage return
‘\’’ or “\’” Displays a single quote in output statement
‘\”’ or “\”” Displays a double quote in output statement
‘\?’ or “\?” Displays question mark
‘\0’ or “\0” Null character(tells the end of string which is used in string
handling)

Operators:
C supports a rich set of operators. An operator is a symbol that tells the
computer to perform certain mathematical or logical manipulations. C is classified into
number of categories.
They are:

7|Page
1. Arithmetic Operators.
2. Relational Operators.
3. Logical Operators.
4. Conditional Operators.
5. Bitwise Operators.
6. Comma Operator.
7. Assignment Operator.
8. Increment and Decrement Operators.
1. Arithmetic Operators :
Arithmetic operators are used for arithmetic operations like addition,
subtraction, division etc.. They are mainly 5 arithmetic operators used in C language.
They are :
1. * Multiplication
2. / Division
3. % Modulus
4. + Addition
5. - Subtraction
Ex : a=8, b=4 then a + b = 12
a–b=4
a * b = 32
a/b=2
a%b=0
Arithmetic Operators are further classified into 3 types.
They are :
1. Integer Arithmetic Expression
2. Real or Float Arithmetic Expression
3. Mixed mode Arithmetic Expression
1. Integer Arithmetic Expression:
When both operands are of integer type then such type of expression
using arithmetic operators is called Integer Arithmetic Expression.
Ex : 3+2, 3-2, etc.
2. Real or Float Arithmetic Expression :
When both the operands are of real type then such type of
expression using arithmetic operators is called Real or Float Arithmetic
Expression.
Ex : 1.2+2.1, 3.2*1.2 etc…
3. Mixed mode Arithmetic Expression :
When one operand is of integer type and other is of real type then
such expression using arithmetic operators is called Mixed
mode Arithmetic Expression.
Ex : 1.2+3 , 3*1.2 , etc.

8|Page
2. Relational Operator:
Relational Operators are used to create a relationship among the
operands. They are used for comparison purpose. It is in the form as
Operand1 operator operand2;
The value of a relational expression is either 1 or 0 depending on relation
either true or false. These are used in mostly decision making and branching
statements, and looping statements. C supports 6 relational operators.
They are:
1. < Less Than
2. > Greater Than
3. <= Less than and equal to
4. >= Greater than and equal to
5. == Equal to
6. != Not equal to
Ex: If a=5 b=3, then the various relational expressions would be as follows:
Relational Expression Result
a>b true
a<b false
a<=b false
a>=b false
a==b false
a!=b true

3. Logical Operators:
The logical operators are used to combine or construct compound
conditional expressions and also to negate expressions. These are used in decision-
making statement and some looping statements like if, switch ,while , etc. These
statements have either true(1) or false(0). C supports 3 types of logical operators.
They are :
1. Logical AND (&&)
2. Logical OR (||)
3. Logical NOT (!)
1. Logical AND (&&):
In Logical AND operator if both operands(expressions)are true then the result
will be true i.e. 1 otherwise the result will be false i.e. 0. The general syntax for
logical AND operator using the symbol && is i.e. op1 && op2
The truth table for Logical AND operator is shown below
Op1 Op2 Op1 && Op2
0 0 0
1 0 0
0 1 0
1 1 1

9|Page
2. Logical OR (||) :
In Logical OR operator if any one of the operand (expression)is true then the
result will be true i.e. 1 otherwise the result will be false i.e. 0. The general syntax
for logical OR operator using the symbol || is i.e. op1 || op2
The truth table for Logical OR operator is shown below
Op1 Op2 Op1|| Op2
0 0 0
1 0 1
0 1 1
1 1 1

3. Logical NOT (!) :


The logical NOT operator gives the negation of an operand(expression). The
general syntax for Logical NOT operator using the symbol ! is i.e. !op

Op !Op

1 0
0 1

4. Conditional Operator (? :):


Conditional operators are also called Ternary operator. These operators are
used instead of “ if ” statement.
The syntax for conditional operator is:
exp1 ? exp2 : exp3 ;
Here first the expression exp1 will be computed which is a conditional
expression. If exp1 is true then exp2 will be executed. But if exp1 is false then
exp3 will be executed.
Ex: c=(a>b)?a-b:a+b;
if a=5 and b=4 then according to the conditional operator
c=(5>4)?5-4:5+4;
c=1 ( as 5 is greater than 4 so exp2 is executed i.e. 5-4=1 )

5. Bitwise Operator:
Bitwise operators are specially used for low level programming. These operators
are used for the manipulation of binary data i.e. bits. These operators should not be of
float or double type. C supports 6 types of Bitwise operators.
They are :
1. Bitwise AND ( & )
2. Bitwise OR (| )
3. Bitwise Exclusive OR ( ^ )
4. Bitwise Shift Left ( << )
5. Bitwise Shift Right ( >> )
6. Bitwise Complement(bitwise NOT) ( ~ )

10 | P a g e
1. Bitwise AND (&):
AND operator is a binary operator which needs two operands to operate.
AND operator operates by adding the individual bits of two operands one by one. If
both operand has 1 at same position then the result is 1 otherwise the result is 0.
Ex : Let a = 00101010
b = 10011001
then c = a & b = 00001000
2. Bitwise OR (|):
OR operator is a binary operator which operates on two operands. If any one
of the bit value is 1 then it results to 1 otherwise 0.
Ex : Let a = 00101010
b = 10011001
then c = a | b = 10111011
3. Bitwise Exclusive OR (^):
Exclusive OR is a binary operator which operates on two operands. This
operator returns 1 if one operand has the bit value 1 and the other has 0 at same
position or vice-cersa otherwise it returns 0.
Ex : Let a = 00101010
b = 10011001
then c = a ^ b = 10110011
4. Bitwise Shift Left (<<):
Bitwise shift left operator transfer the bits of data to left side. The left operand
is the data and the right operand is the no. of times the shift operation is to be done.
Here the most significant bit will be discarded and the least significant bit will come
out to be 0. The syntax is: op << n
Ex: x = 0100 1001 1100 1011
X << 3 = 0100 1110 0101 1000
5. Bitwise Shift Right (>>):
Bitwise shift right operator transfers the bits of data to right side. The
left operand is the data and the right operand is the no. of times the shift operation is
to be done. Here the least significant bit will be discarded and the most significant bit
will come out to be 0. The syntax is op >> n
Ex: x = 0100 1001 1100 1011
X >> 3 = 0000 1001 0011 1001
6. Bitwise Complement (bitwise NOT)(~) :
One’s complement operator is a unary operator which is similar
to NOT. It converts 0 to 1 and 1 to 0.
Ex : Let a = 5
it’s binary equivalent is a= 00000101
~a= 11111010

6. Comma Operator:
When number of statements occur in a C program having a relationship
between expressions, then we can write all expressions or statements in a single
expression using the comma operator.
11 | P a g e
Mostly the comma operator is used in looping statements like while, do-while
and for.
Ex: a=12;
b=10;
c=a+b;
So, the above statement can be written as c=(a=12,b=10,a+b);

Type Operator or Casting:


Type operator is used for conversion purpose or casting purpose. So it is also
called convert operator. This operator converts float type data into integer form and
vice-versa. It is also used for casting a value and process to convert from one form to
another is called Casting.
The syntax is:
(type) v or e;
Where v is variable and e is an expression.
Ex: int a,b;
float c;
a=5;
b=2;
c=a/b;
If we divide a by b, then result stored in the C variable be 2.0. But by using the type
operator, we can get the float value as:
c=(float)a/b;

7. Assignment Operator:
Assignment operators are used for assigning an expression or value to
a variable. Assignment operators are further divided into two types. They are
• Simple Assignment Operator
• Shorthand Assignment Operator
(or)
Arithmetic Assignment Operator
Simple Assignment Operator:
Simple assignment operator is = (equal to).
Syntax: v=constant value (or) variable (or) expression;
Ex: a=3;
b=c;
Shorthand Assignment (or) Arithmetic Assignment Operator:
These operators have = (equal to) sign with all arithmetic operators.
Syntax: v arithmetic operator = constant value or expression;
where v is the variable and expression can be an arithmetic expression i.e.+,-,/,*,%.
Ex: Simple Assignment Shorthand Assignment
i=i+1; i+=1;
a=a*b+c; a*=b+c;
b=b%c; b%=c;

12 | P a g e
8. Increment/Decrement Operator:
These operators are also called unary operators. Another name for
increment and decrement operators is counter operator. Increment Operator (++ ) are
used for incrementing the value by 1 and Decrement Operator( -- ) is used for
decrementing the value by 1. These operators are further divided into types. They are
• Prefix Increment/Decrement
• Postfix Increment/Decrement
Prefix Operator :
In the prefix increment operator first of all value will be incremented and then
incremented value will be assigned to a variable. Similarly in the prefix decrement
operator first of all the value will be decremented and then decremented value be
assigned to the variable. They are represented as :
++v; prefix increment
--v; prefix decrement where v is the variable.
Postfix Operator:
In the postfix increment operator first of all value will be assigned to a variable
and then value will be incremented. Similarly in the postfix decrement operator first of
all the value will be
assigned to a variable and then value will be decremented.
They are represented as:
v++; postfix increment
v--; postfix decrement where v is the variable.

Ex: x=7 x=7


Y=++x y=x++
After processing: After processing:
Value of y is 8 value of y=7
Value of y is 8 value of x=8
x=7 x=7
Y=--x y=x--
After processing: After processing:
Value of y is 6 value of y=7
Value of y is 6 value of x=6

Order of Operators Precedence:


Order of precedence means the rank in which all the operators
operate in a C expression. The order of precedence and associatively between these
operators is shown below:
Operator Description Associatively Rank
() Parenthesis Left to right 1
[] Square bracket Left to right 1
+ Unary plus Right to left 2
- Unary minus Right to left 2
++ increment Right to left 2
13 | P a g e
-- Decrement Right to left 2
! Logical negation Right to left 2
~ One’s compliment Right to left 2
* indirection Right to left 2
& Address Right to left 2
Size of Size of an object Right to left 2
(type) Type cast Left to right 2
* multiplication Left to right 3
/ Division Left to right 3
% modulus Left to right 3
+ Addition Left to right 4
- subtraction Left to right 4
<< Left shift Left to right 5
>> Right shift Left to right 5
< Less than Left to right 6
<= Less than or equal to Left to right 6
> Greater than Left to right 6
>= Greater than or equal to Left to right 6
== equality Left to right 7
!= inequality Left to right 7
& Bitwise AND Left to right 8
^ Bitwise XOR Left to right 9
| Bitwise OR Left to right 10
&& Logical AND Left to right 11
|| Logical OR Left to right 12
?! Conditional operator Right to left 13
= Assignment operator Right to left 14
, Comma operator Left to right 15

Formatted I/O Functions:


Formatted I/O functions are used to take various inputs from the user and
display multiple outputs to the user. These types of I/O functions can help to display
the output to the user in different formats using the format specifiers.
The formatted I/O functions supported by C are printf() and scanf().
printf():

Syntax:
printf("<message>");
printf("<control string>", argument list separated with commas);

This is an output statement. To output data on to a screen, we use the standard


output library function, represented by the word "printf" followed by the open and
closing parentheses (). It is used to display the value of a variable or a message on
the screen.

14 | P a g e
Example:
• printf("This is C statement"); printf("The number is % d", a);
• printf("The number % d is equal to % d", 10,10);
• printf("The number % d is not equal to % d", x,y);
scanf():
This is an input statement. Data can be stored in the variables after accepting
the values from the user through the keyword, by using a standard library function
for input operation. This allows a program to get user input from the keyboard. This
means that the program gets input values for variables from users.
Syntax:
scanf("<format code>",list of address of variables separated by commas);

Example:
scanf("% d", &a);
scanf("% d % c % f", &a, &b, &c);
Ex: 1. To print a message "Hello World" on the screen using printf()
/*Program to print a message "Hello World" */
#include<stdio.h>
#include<conio.h>
main()
{
clrscr();
printf("Hello World");
}
Output:
Hello World
Ex: 2. To Initialize int, char, float data types
/*Program to initialize int, char, float data types*/
#include<stdio.h>
#includ<conio.h>
main()
{
int n=78; float j=3.0; char x='y';
clrscr();
printf("Integer=%d\t Float Value=%f\t Character=%c", n, j, x);
}
Ex: 3. To accept the values of int, float, char data types and display them.
/*Program to accept values of int, char, float data types */
#include<stdio.h>
#include<conio.h>
main()
{
char x; int num; float j; clrscr();
/*Accept the values for data types from user*/
printf("Enter Character: ");
15 | P a g e
scanf("%c",&x);
printf("Enter Integer Value: ");
scanf("%d",&num);
printf("Enter Float Value: ");
scanf("%f",&j);
/*Display the accepted values*/
printf("Integer=%d\t Float Value=%f\t Character=%c", num, j, x);
}
Output:
Enter Character: a (press Enter)
Enter Integer Value: 20 (press Enter)
Enter Float Value: 100 (press Enter)
Integer=20 Float Value=100.0 Character=a

Control Statements:
A program is not a linear sequence of instructions. According to the logic, it
may diverge, repeat code or take decisions. The structure of a program which decides
the order of program statements execution is called “Control Structure or Control
Statements”.

Branching or Decision Control Statements:


It is called as decision-making statement. These are used when a condition
arises in a statement. The various branching statements are:
1. if statement
2. switch statement
3. conditional control statement
1. if statement:
The “if “statement is a decision making statement which can handle
conditions and a group of statements. These are categorized into 4 types.
They are
1. simple if statement
2. if-else statement
3. nested if statement
4. else-if or ladder if statement
1. Simple if statement:
When only one condition occurs in a statement , then simple “if” statement
is used. The flow chart and the syntax of “ if “ statement are shown below :
16 | P a g e
Flowchart:

Syntax :
if(condition)
{
Statement-1;
}
Statement-2;
➢ Here first of all condition will be checked.
➢ If the condition is true, then the statement-1 block will be executed and
after execution of this block, statement-2 will be executed.
➢ If the condition is false then the statement-2 will be executed directly.
Ex: #include<stdio.h>
#include<conio.h>
void main()
{
float per;
char res[5];
clrscr();
printf(“Enter the percentage:”);
scanf(“%f”,&per);
if(per>=35)
{
printf(“\n Result is pass”);
}
printf(“\n Entered percentage is %s”,per);
getch();
}
2. if-else statement:
This statement contains a single condition with two different blocks of
statements. The flowchart and the syntax of “ if-else “ statement is shown below
Flowchart:

17 | P a g e
Syntax: if(condition)
{
true statement-1;
}
else
{
false statement-2;
}
Statement-3;
➢ In this if-else statement, first the condition will be checked.
➢ If the condition is true then the true statement-1 will be executed and after that
statement-3 will be executed.
➢ But if the condition is false then the false statement-2 will be executed and then
the statement-3 will be executed.
Ex: #include<stdio.h>
#include<conio.h>
void main()
{
int a,b,max;
clrscr();
printf(“Enter the values of a and b:”);
scanf(“%d%d”,&a,&b);
if(a>b)
{
max=a;
}
else
{
max=b;
}
printf(“\n Maximum value is :%d”,max);
getch();
}
3. Nested if Statement :
When an if statement occurs within another if statement, such type of if
statement is called “ nested if “ statement. The flowchart and the syntax of nested-if
statement is shown below:
Flowchart:

18 | P a g e
Syntax :
if(condition-1)
{
if(condition-2)
{
True statement-1;
}
else
{
False statement-1;
}
}
else
{
if(condition-3)
{
True statemet-2;
}
else
{
False statement-2;
}
}
statement-3;
➢ In this first the condition-1 will be checked.
➢ If the condition is true, then further condition-2 will be checked.
➢ If condition-2 is true, then true statement-1 will be executed and after that
statement-3 will be executed.
➢ But if the condition-2 is false, then false statement-1 will be executed and then
statement-3 will be executed.
➢ If the condition-1 is false, then condition-3 will be checked.
➢ If condition-3 is true then the true statement-2 will be executed and after that
statement-3 will be executed.
➢ But if the condition-3 is false then the false statement-2 will be executed and
then statement-3 will be executed.
Ex: #include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,max;
clrscr();
printf(“Enter the values of A B and C:”);
scanf(“%d%d%d”,&a,&b,&c);

19 | P a g e
if(a>b)
{
if(a>c)
{
max=a;
}
else
{
max=c;
}
}
else
{
if(b>c)
{
max=b;
}
else
{
max=c;
}
}
printf(“\n Maximum value is %d”,max);
getch();
}
4. else-if or Ladder if statement:
In this, first condition will be checked, if it is true then the corresponding
statements will be executed otherwise further next condition will be checked and this
process will continue till the end of the condition. The flowchart and the syntax of else-
if is shown below:
Flowchart:

20 | P a g e
Syntax:
if(condition-1)
{
statement-1;
}
else if(condition-2)
{
statement-2;
}
else if(condition-3)
{
statement-3;
}
-----------------
else if(condition-n)
{
statement-n;
}
else
{
default statement;
}
statement-x;
Ex: void main()
{
int code;
clrscr();
printf(“Enter the code(1-3):”);
scanf(“%d”,&code);
if(code==1)
{
printf(“PINK”);
}
else if(code==2)
{
printf(“RED”);
}
else if(code==3)
{
printf(“BLUE”);
}
else
{
printf(“\n Invalid code”);
}

21 | P a g e
printf(“\n End of the program”);
getch(); }

switch statement:
Whenever we want to check more possible conditions for a single variable
a no. of statements are necessary. C has a built-in multiway decision statement known
as a “ switch “ statement. The switch statement tests the value of a given expression
against a list of case values and when a match is found, a block of statements
associated with that case is executed.
In switch case statement, no case can have two equal values. Default may
appear at any place and not compulsory. The flowchart and syntax of switch statement
is shown below :
Flowchart:

Syntax : switch(expression)
{
case value-1: block-1;
break;
case value-2: block-2;
break;
case value-3: block-3;
break;

case value-n: block-n;


break;
default : block n+1;
}
statement-x;
Ex:
#include<stdio.h>
#include<conio.h>

22 | P a g e
void main()
{
int a,b,c,choice;
clrscr();
printf(“Enter values of a and b:”);
scanf(“%d%d”,&a,&b);
printf(\n1.ADDITION\n2.SUBTRACTION\n3.MULTIPLICATION\n
4.DIVISION \n5.MODULO DIVISION”);
printf(“\n select ur choice:”);
scanf(“%d”,&choice);
switch(choice)
{
case 1:c=a+b;
break;
case 2:c=a-b;
break;
case 3:c=a*b;
break;
case 4:c=a/b;
break;
case 5:c=a%b;
break;
default:printf(“\n Enter only a valid choice”);
}
printf(“\nResult is = %d”,c);
getch();
}

Conditional control statement ( ? : ) :


The conditional control statement is based on conditional operator,
that which executes fast in a single line. It takes the combination of “ ? and : “ for using
the conditional statement.
The syntax is:
exp1?exp2:exp3;
This is a substitute of “if-else” statement that which uses a single condition.
Similarly, the nesting conditional control statement syntax is:
exp1?(exp2?exp3:exp4):exp5;
➢ In the above nested conditional control statement ,first exp1 will be executed
and if it is true, then exp2 will be checked.
➢ If exp2 is true then the exp3 will be executed, otherwise exp4 will be executed.
➢ But if exp1 is false, then only the exp5 will be executed.
➢ This is the substitute of nested-if statement.
Ex:/*program to calculate salary depending basic pay*/
#include<stdio.h>
#include<conio.h>

23 | P a g e
void main()
{
int sal,bp;
clrscr();
printf(“Enter basic pay:”);
scanf(“%d”,&bp);
sal=(bp!=1000)?((bp<1000)?bp+100:4*bp+200):2000;
printf(“\n sal=%d”,sal);
getch();
}

Programming Examples:
1. Simple if:
/* program for printing minimum value*/
#include <stdio.h>
#include<conio.h>
void main()
{
int x = 20;
int y = 22;
clrscr();
if (x<y)
{
printf("Variable x is less than y");
}
getch();
}
/* program printing non-zero value as true*/
#include<stdio.h>
#include<conio.h>
void main()
{
int present = 1;
clrscr();
if (present)
printf("There is someone present in the classroom \n");
getch();
}

24 | P a g e
2. if-else:
/* program to check even or odd */
#include<stdio.h>
#include<conio.h>
void main()
{
int number;
clrscr();
printf("Enter a number: ");
scanf("%d",&number);
if(number%2==0)
{
printf("%d is an even number",number);
}
else
{
printf("%d is an odd number",number);
}
getch();
}

Leap Year:
A year is said to be leap year, if the year is exactly divisible by 4 but and
not divisible by 100. Year is also a leap year if it is exactly divisible by 400.
/* program to check leap year or not */
#include <stdio.h>
#include<conio.h>
void main()
{
int year;
clrscr();
printf("Enter year : ");
scanf("%d", &year);
if(((year % 4 == 0) && (year % 100 !=0)) || (year % 400==0))
{
printf("LEAP YEAR");
}
else
{
printf("COMMON YEAR");
}
getch();
}

25 | P a g e
/*program to check whether the given number is of multiple of 3 or not*/
#include<stdio.h>
#include<conio.h>
void main()
{
int number;
clrscr();
printf("Enter a number: ");
scanf("%d",&number);
if(number%3==0)
{
printf("%d is multiple of 3",number);
}
else
{
printf("%d is not multiple of 3",number);
}
getch();
}
/*Program to check whether a person is eligible to vote or not*/
#include <stdio.h>
#include<conio.h>
void main()
{
int age;
clrscr();
printf("Enter your age?");
scanf("%d",&age);
if(age>=18)
{
printf("\n Your age is %d and You are eligible to vote...",age);
}
else
{
printf("\n Your age is %d so sorry ... you can't vote",age);
}
getch();
}

26 | P a g e
3.Nested if:
#include<stdio.h>
#include<conio.h>
void main()
{
int num=1;
if(num<10)
{
if(num==1)
{
printf("The value is:%d\n",num);
}
else
{
printf("The value is greater than 1");
}
}
else
{
printf("The value is greater than 10");
}
getch();
}

4. Else-if or Ladder-if:
#include<stdio.h>
#include<conio.h>
void main()
{
int a, b;
printf("Please enter the value for a and b:");
scanf("%d%d", &a,&b);
if (a > b)
{
printf("\n a is greater than b");
}
else if (b > a)
{
printf("\n b is greater than a");
}
else
{
printf("\n Both are equal");
}
getch(); }
27 | P a g e
/*program to check eligibility for scholarship*/
#include <stdio.h>
#include<conio.h>
void main()
{
int Totalmarks;
clrscr();
printf("Please Enter your Total Marks\n" );
scanf( "%d", &Totalmarks );
if (Totalmarks >= 540)
{
printf("You are eligible for Full Scholarship\n");
printf("Congratulations\n");
}
else if (Totalmarks >= 480)
{
printf("You are eligible for 50 Percent Scholarship\n");
printf("Congratulations\n");
}
else if (Totalmarks >= 400)
{
printf("You are eligible for 10 Percent Scholarship\n");
printf("Congratulations\n");
}
else
{
printf("You are Not eligible for Scholarship\n");
printf("We are really Sorry for You\n");
}
getch();
}

Quadratic Equation:
1. Input coefficients a,b,c of quadratic equation from user.
2. Find discriminant of the given equation, using formula
discriminant = (b*b) - (4*a*c).
3. Compute roots based on the nature of discriminant.
If discriminant > 0 then,
root1 = (-b + sqrt(discriminant)) / (2*a) and
root2 = (-b - sqrt(discriminant)) / (2*a).
4. If discriminant == 0 then, root1 = root2 = -b / (2*a).
5. Else if discriminant < 0 then, there are two distinct complex roots where
root1 = -b / (2*a) and root2 = -b / (2*a).
6. Imaginary part of the root is given by imaginary = sqrt(-discriminant) / (2*a).

28 | P a g e
/* program to find all roots of a quadratic equation*/
#include <stdio.h>
#include<conio.h>
#include <math.h> /* Used for sqrt() */
void main()
{
float a, b, c;
float root1, root2, imaginary;
float discriminant;
clrscr();
printf("Enter values of a, b, c of quadratic equation (aX^2 + bX + c): ");
scanf("%f%f%f", &a, &b, &c);
/* Find discriminant of the equation */
discriminant = (b * b) - (4 * a * c);
/* Find the nature of discriminant */
if(discriminant > 0)
{
root1 = (-b + sqrt(discriminant)) / (2*a);
root2 = (-b - sqrt(discriminant)) / (2*a);
printf("Two distinct and real roots exists: %.2f and %.2f", root1, root2);
}
else if(discriminant == 0)
{
root1 = root2 = -b / (2 * a);
printf("Two equal and real roots exists: %.2f and %.2f", root1, root2);
}
else if(discriminant < 0)
{
root1 = root2 = -b / (2 * a);
imaginary = sqrt(-discriminant) / (2 * a);
printf("Two distinct complex roots exists: %.2f + i%.2f and %.2f - i%.2f",
root1, imaginary, root2, imaginary);
}
getch();
}

Electricity bill generation:


1. Input unit consumed by customer in some variable say unit.
2. If unit consumed less or equal to 50 units. Then amt = unit * 0.50.
3. If unit consumed more than 50 units but less than 100 units, Which is given
by amt = 25 + (unit-50) * 0.75.
4. Similarly check rest of the conditions and calculate total amount.
5. After calculating total amount. Calculate the surcharge amount i.e.
sur_charge = total_amt * 0.20. Add surcharge amount to net amount. Which is
given by net_amt = total_amt + sur_charge.
29 | P a g e
/* C program to calculate total electricity bill */
#include <stdio.h>
#include<conio.h>
void main()
{
int unit;
float amt, total_amt, sur_charge;
clrscr();
/* Input unit consumed from user */
printf("Enter total units consumed: ");
scanf("%d", &unit);
/* Calculate electricity bill according to given conditions */
if(unit <= 50)
{
amt = unit * 0.50;
}
else if(unit <= 150)
{
amt = 25 + ((unit-50) * 0.75);
}
else if(unit <= 250)
{
amt = 100 + ((unit-150) * 1.20);
}
else
{
amt = 220 + ((unit-250) * 1.50);
}
/* Calculate total electricity bill after adding surcharge */
sur_charge = amt * 0.20;
total_amt = amt + sur_charge;
printf("Electricity Bill = Rs. %.2f", total_amt);
getch();
}

30 | P a g e
Salary generation:
Gross salary is the final salary computed after the additions
of DA, HRA and other allowances. The formula for DA and HRA is
da = basic_salary * (DA/100)
If DA = 80% then the statement becomes da = basic_salary * (80/100). Which can
also be written as DA = basic_salary * 0.08. Likewise you can also derive a formula
for HRA.
Step by step descriptive logic to find gross salary of an employee.
1. Input basic salary of employee. Store it in some variable say basic_salary.
2. If basic_salary <= 10000 then, hra = basic_salary * 0.8 and da = basic_salary *
0.2.
3. Similarly check basic salary and compute hra and da accordingly.
4. Calculate final gross salary using formula gross_salary = basic_salary + da + hra

/* C program to calculate gross salary of an employee */


#include <stdio.h>
#include<conio.h>
void main()
{
float basic, gross, da, hra;
/* Input basic salary of employee */
printf("Enter basic salary of an employee: ");
scanf("%f", &basic);
/* Calculate D.A and H.R.A according to specified conditions */
if(basic <= 10000)
{
da = basic * 0.8;
hra = basic * 0.2;
}
else if(basic <= 20000)
{
da = basic * 0.9;
hra = basic * 0.25;
}
else
{
da = basic * 0.95;
hra = basic * 0.3;
}
/* Calculate gross salary */
gross = basic + hra + da;
printf("GROSS SALARY OF EMPLOYEE = %.2f", gross);
getch();
}

31 | P a g e
Switch case:
/*C program to print day of week using switch case */
#include <stdio.h>
#include<conio.h>
void main()
{
int week;
clrscr();
/* Input week number from user */
printf("Enter week number(1-7): ");
scanf("%d", &week);
switch(week)
{
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
case 4:
printf("Thursday");
break;
case 5:
printf("Friday");
break;
case 6:
printf("Saturday");
break;
case 7:
printf("Sunday");
break;
default:
printf("Invalid input! Please enter week number between 1-7.");
}
getch();
}

32 | P a g e

You might also like