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

C UNIT 2 Notes

Unit II of the document covers operators and expressions in C programming, detailing data input and output statements, various types of operators including arithmetic, relational, logical, bitwise, and assignment operators. It explains standard I/O library functions, formatted and unformatted I/O functions, and provides examples of their usage. Additionally, the document includes sample C programs demonstrating the implementation of these concepts.

Uploaded by

Sinduja Baskaran
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)
20 views

C UNIT 2 Notes

Unit II of the document covers operators and expressions in C programming, detailing data input and output statements, various types of operators including arithmetic, relational, logical, bitwise, and assignment operators. It explains standard I/O library functions, formatted and unformatted I/O functions, and provides examples of their usage. Additionally, the document includes sample C programs demonstrating the implementation of these concepts.

Uploaded by

Sinduja Baskaran
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/ 78

Unit 2 C Progg

UNIT II
OPERATOR AND EXPRESSIONS
Data Input and Output statements – Operators: Arithmetic Operators, Relational
Operators, Logical Operators, Increment and Decrement Operators, Bitwise
Operators, Assignment Operators and Expressions, Precedence and Order of
Evaluation – Decision Making and Branching – Looping statements.

Data Input and Output statements:


In C Language input and output function are available as C compiler
functions or C libraries provided with each C compiler implementation. These
all functions are collectively known as Standard I/O Library function.
Here I/O stands for Input and Output used for different inputting and
outputting statements. These I/O functions are categorized into three processing
functions.
i. Console input/output function (deals with keyboard and monitor),
ii. disk input/output function (deals with floppy or hard disk),
iii. port input/output function (deals with a serial or parallel port).
As all the input/output statements deals with the console, so these are
also Console Input/Output functions. Console Input/Output function access
the three major files before the execution of a C program. These are as follows:

● stdin: This file is used to receive the input (usually is keyboard


file, but can also take input from the disk file).
Unit 2 C Progg

● stdout: This file is used to send or direct the output (usually is a


monitor file, but can also send the output to a disk file or any other
device).
● stderr: This file is used to display or store error messages.

Input Output Statement

Input and Output statement are used to read and write the data in C
programming. These are embedded in stdio.h (standard Input/Output header
file).

Input means to provide the program with some data to be used in the program
and Output means to display data on screen or write the data to a printer or a
file.C programming language provides many built-in functions to read any
given input and to display data on screen when there is a need to output the
result.

There are mainly two of Input/Output functions are used for this purpose. These
are discussed as:

● Unformatted I/O functions


● Formatted I/O functions

Unformatted I/O functions

There are mainly six unformatted I/O functions discussed as follows:

● getchar()
● putchar()
● gets()
● puts()
● getch()
● getche()

getchar()

This function is an Input function. It is used for reading a single character


from the keyboard. It is a buffered function. Buffered functions get the input
from the keyboard and store it in the memory buffer temporally until you press
the Enter key.
Unit 2 C Progg

The general syntax is as:

v = getchar();

where v is the variable of character type. For example:


char n;
n = getchar();

A simple C-program to read a single character from the keyboard is as:

/* To read a single character from the keyboard using the getchar()


function*/
#include <stdio.h>
int main()
{
char n;
n = getchar();
}

putchar()

This function is an output function. It is used to display a single character


on the screen. The general syntax is as:

putchar(v);

where v is the variable of character type.

For example:

char n;
putchar(n);

A simple program is written as below, which will read a single character using
getchar() function and display inputted data using putchar() function:

/*Program illustrate the use of getchar() and putchar() functions*/


#include <stdio.h>
int main()
{
char n;
n = getchar();
putchar(n); }
Unit 2 C Progg

gets()

This function is an input function. It is used to read a string from the


keyboard. It is also a buffered function. It will read a string when you type the
string from the keyboard and press the Enter key from the keyboard. It will
mark null character (‘\0’) in the memory at the end of the string when you press
the enter key. The general syntax is as:

gets(v);

where v is the variable of character type. For example:

char n[20];
gets(n);

A simple C program to illustrate the use of gets() function:

/*Program to explain the use of gets() function*/


#include <stdio.h>
int main()
{
char n[20];
gets(n);
}

puts()

This is an output function. It is used to display a string inputted by gets()


function. It is also used to display a text (message) on the screen for program
simplicity. This function appends a newline (“\n”) character to the output.

The general syntax is as:

puts(v); (or) puts("text line");

where v is the variable of character type.

A simple C program to illustrate the use of puts() function:


Unit 2 C Progg

/*Program to illustrate the concept of puts() with gets() functions*/


#include <stdio.h>
int main()
{
char name[20];
puts("Enter the Name");
gets(name);
puts("Name is :");
puts(name);
}
Output:

Enter the Name


Hello
Name is:
Hello

getch()

This is also an input function. This is used to read a single character from
the keyboard like getchar() function. The character data read by this function is
directly assigned to a variable rather it goes to the memory buffer, the character
data is directly assigned to a variable without the need to press the Enter key.

Another use of this function is to maintain the output on the screen till
you have not press the Enter Key. The general syntax is as:

v = getch();

where v is the variable of character type.

A simple C program to illustrate the use of getch() function:

/*Program to explain the use of getch() function*/


#include <stdio.h>
int main()
{
char n;
puts("Enter the Char");
n = getch();
puts("Char is :");
putchar(n);
Unit 2 C Progg

getch();
}
Output:

Enter the Char


Char is L

getche()

All are same as getch() function execpt it is an echoed function. It means


when you type the character data from the keyboard it will visible on the screen.
The general syntax is as:

v = getche();
where v is the variable of character type.

A simple C program to illustrate the use of getch() function:

/*Program to explain the use of getch() function*/


#include <stdio.h>
int main()
{
char n;
puts("Enter the Char");
n = getche();
puts("Char is :");
putchar(n);
getche();
}

Output:

Enter the Char L


Char is L
Unit 2 C Progg

Formatted I/O functions

Formatted I/O functions which refers to an Input or Ouput data that has
been arranged in a particular format. There are mainly two formatted I/O
functions discussed as follows:

● scanf()
● printf()

scanf()

The scanf() function is an input function. It used to read the mixed type of
data from keyboard. You can read integer, float and character data by using its
control codes or format codes. The general syntax is as:

scanf("control strings",arg1,arg2,..............argn);

(Or)

scanf("control strings",&v1,&v2,&v3,................&vn);

where arg1,arg2,……….argn are the arguments for reading and


v1,v2,v3,……..vn all are the variables.

The scanf() format code (specifier) is as shown in the below table:

Example Program:

/*Program to illustrate the use of formatted code by using the formatted


scanf() function */

#include <stdio.h>
int main()
{
char n,name[20];
int abc;
float xyz;
printf("Enter the single character, name, integer data and real value");
scanf("\n%c%s%d%f", &n,name,&abc,&xyz);
getch();
Unit 2 C Progg

printf()

This is an output function. It is used to display a text message and to


display the mixed type (int, float, char) of data on screen. The general syntax is
as:

printf("control strings",&v1,&v2,&v3,................&vn);

(Or)

printf("Message line or text line");


Unit 2 C Progg

where v1,v2,v3,……..vn all are the variables.

The control strings use some printf() format codes or format specifiers or
conversion characters. These all are discussed in the below table as:

/*Below the program which show the use of printf() function*/


#include <stdio.h>
int main()
{
int a;
float b;
char c;
printf("Enter the mixed type of data");
scanf("%d",%f,%c",&a,&b,&c);
getch();
}
Unit 2 C Progg

OPERATORS IN C
C operators are one of the features in C which has symbols that can be used to
perform mathematical, relational, bitwise, conditional, or logical
manipulations. Operators are used to perform operations on variables and
values.

C divides the operators into the following groups:

● Arithmetic operators
● Relational Operator
● Logical operators
● Bitwise operators
● Assignment Operators
● Misc Operators

ARITHMETIC OPERATORS

Arithmetic operators are used to perform common mathematical operations.

Operator Name Description Example

+ Addition Adds together two values x+y

- Subtraction Subtracts one value from x-y


another

* Multiplication Multiplies two values x*y

/ Division Divides one value by another x/y


Unit 2 C Progg

% Modulus Returns the division x%y


remainder

++ Increment Increases the value of a ++x


variable by 1

-- Decrement Decreases the value of a --x


variable by 1

// Working of arithmetic operators Example //


#include <stdio.h>
int main()
{
int a = 9, b = 4, c;
c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c = a/b;
printf("a/b = %d \n",c);
c = a%b;
printf("Remainder when a divided by b = %d \n",c);
return 0;
}
Output:

a+b = 13
a-b = 5
a*b = 36
a/b = 2
Remainder when a divided by b=1
Unit 2 C Progg

RELATIONAL OPERATORS
A relational operator checks the relationship between two operands. If the
relation is true, it returns 1; if the relation is false, it returns value 0. Relational
operators are used in decision making and loops.

// Working of relational operators //


#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10;
printf("%d == %d is %d \n", a, b, a == b);
printf("%d == %d is %d \n", a, c, a == c);
printf("%d > %d is %d \n", a, b, a > b);
printf("%d > %d is %d \n", a, c, a > c);
printf("%d < %d is %d \n", a, b, a < b);
Unit 2 C Progg

printf("%d < %d is %d \n", a, c, a < c);


printf("%d != %d is %d \n", a, b, a != b);
printf("%d != %d is %d \n", a, c, a != c);
printf("%d >= %d is %d \n", a, b, a >= b);
printf("%d >= %d is %d \n", a, c, a >= c);
printf("%d <= %d is %d \n", a, b, a <= b);
printf("%d <= %d is %d \n", a, c, a <= c);
return 0;
}
Output:

5 == 5 is 1
5 == 10 is 0
5 > 5 is 0
5 > 10 is 0
5 < 5 is 0
5 < 10 is 1
5 != 5 is 0
5 != 10 is 1
5 >= 5 is 1
5 >= 10 is 0
5 <= 5 is 1
5 <= 10 is 1

LOGICAL OPERATORS:
Logical Operators are used to combine two or more
conditions/constraints or to complement the evaluation of the original condition
in consideration. The result of the operation of a logical operator is a boolean
value either true or false.
Unit 2 C Progg

// Working of logical operators //


#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10, result;
result = (a == b) && (c > b);
printf("(a == b) && (c > b) is %d \n", result);
result = (a == b) && (c < b);
printf("(a == b) && (c < b) is %d \n", result);
result = (a == b) || (c < b);
printf("(a == b) || (c < b) is %d \n", result);
result = (a != b) || (c < b);
printf("(a != b) || (c < b) is %d \n", result);
result = !(a != b);
printf("!(a != b) is %d \n", result);
result = !(a == b);
printf("!(a == b) is %d \n", result);
return 0;
}

Output:
Unit 2 C Progg

(a == b) && (c > b) is 1
(a == b) && (c < b) is 0
(a == b) || (c < b) is 1
(a != b) || (c < b) is 0
!(a != b) is 1
!(a == b) is 0

BITWISE OPERATORS
The Bitwise operators is used to perform bit-level operations on the
operands. The operators are first converted to bit-level and then the calculation
is performed on the operands. The mathematical operations such as addition,
subtraction, multiplication etc. can be performed at bit-level for faster
processing.

// C Program to demonstrate use of bitwise operators


#include <stdio.h>
int main()
{
// p = 5(00000101), q = 9(00001001)
Unit 2 C Progg

unsigned char p = 5, q = 9;
// The result is 00000001
printf(“p = %d, q = %d\n”, p, q);
printf(“p&q = %d\n”, p & q);
// The result is 00001100
printf(“p^q = %d\n”, p ^ q);
// The result is 00001101
printf(“p|q = %d\n”, p | q);
// The result is 11111010
printf(“~p = %d\n”, p = ~p);
// The result is 00000100
printf(“q>>1 = %d\n”, q >> 1);
// The result is 00010010
printf(“q<<1 = %d\n”, q << 1);
return 0;
}
Output:

p = 5, q = 9

p&q = 1

p^q = 12

p|q = 13

~p = 250

q>>1 = 4

q<<1 = 18

ASSIGNMENT OPERATORS
Assignment operators are used to assign value to a variable. The left side
operand of the assignment operator is a variable and right-side operand of the
Unit 2 C Progg

assignment operator is a value. The value on the right side must be of the same
data-type of variable on the left side otherwise the compiler will raise an error.
■ a = 10; b = 20; ch = 'y';
■ (a += b) can be written as (a = a + b)
■ (a -= b) can be written as (a = a - b)
■ (a /= b) can be written as (a = a / b)

Example of the Assignment Operators:

1. A = 5; // use Assignment symbol to assign 5 to the operand A


2. B = A; // Assign operand A to the B
3. B = &A; // Assign the address of operand A to the variable B
4. A = 20 \ 10 * 2 + 5; // assign equation to the variable A

INCREMENT AND DECREMENT OPERATORS IN C

The increment ( ++ ) and decrement ( — ) operators in C are unary


operators for incrementing and decrementing the numeric values by
1 respectively.
The increment operator ( ++ ) is used to increment the value of a
variable in an expression by 1. It can be used on variables of the numeric type
such as integer, float, character, pointers, etc.
Syntax:
// AS PREFIX
++m

// AS POSTFIX
m++

How to use the increment operator?


Unit 2 C Progg

Both pre-increment and post-increment increase the value of the variable


but there is a little difference in how they work.

1. Pre-Increment
In pre-increment, the increment operator is used as the prefix. Also
known as prefix increment, the value is incremented first according to the
precedence and then the less priority operations are done.
Example
result = ++var1;

The above expression can be expanded as


var = var + 1;
result = var;
2. Post-Increment
In post-increment, the increment operator is used as the suffix of the
operand. The increment operation is performed after all the other operations are
done. It is also known as postfix increment.
Example
result = var1++;

The above expression is equivalent


result = var;
var = var + 1;

// C Program to illustrate the increment of both type


#include <stdio.h>
void increment()
{
int a = 5;
int b = 5;
// PREFIX
int prefix = ++a;
printf("Prefix Increment: %d\n", prefix);
// POSTFIX
int postfix = b++;
printf("Postfix Increment: %d", postfix);
Unit 2 C Progg

}
int main()
{
increment();
return 0;
}
Output:
Prefix Increment: 6
Postfix Increment: 5
Decrement Operator in C

The decrement operator is used to decrement the value of a variable in an


expression. In the Pre-Decrement, the value is first decremented and then used
inside the expression. Whereas in the Post-Decrement, the value is first used
inside the expression and then decremented.

Syntax

Just like the increment operator, the decrement operator can also be used in two
ways:
// AS PREFIX
--m
// AS POSTFIX
m—

1. Pre-Decrement Operator

The pre-decrement operator decreases the value of the variable


immediately when encountered. It is also known as prefix decrement as the
decrement operator is used as the prefix of the operand.

Example
result = --m;

which can be expanded to


m = m - 1;
result = m;
Unit 2 C Progg

2. Post-Decrement Operator

The post-decrement happens when the decrement operator is used as the


suffix of the variable. In this case, the decrement operation is performed after all
the other operators are evaluated.

Example
result = m--;

The above expression can be expanded as


result = m;
m = m-1;

// C program to illustrate the decrement operator


#include <stdio.h>
void decrement()
{
int a = 5;
int b = 5;
// PREFIX
int prefix = --a;
printf("Prefix = %d\n", prefix);
// POSTFIX
int postfix = b--;
printf("Postfix = %d", postfix);
}
int main()
{
decrement();
return 0;
}
Output
Prefix = 4
Unit 2 C Progg

Postfix = 5

Differences between Increment And Decrement Operators

Increment Operator Decrement Operator

Increment Operator adds 1 to the Decrement Operator subtracts 1 from


operand. the operand.

The Postfix increment operator The Postfix decrement operator


means the expression is evaluated means the expression is evaluated
first using the original value of the first using the original value of the
variable and then the variable is variable and then the variable is
incremented(increased). decremented(decreased).

Prefix increment operator means the Prefix decrement operator means the
variable is incremented first and variable is decremented first and then
then the expression is evaluated the expression is evaluated using the
using the new value of the variable. new value of the variable.

Generally, we use this in This is also used in decision-making


decision-making and looping. and looping.

Misc Operators ↦ sizeof & ternary


Besides the operators discussed above, there are a few other important operators
including sizeof and ? : supported by the C Language.

Operator Description Example

sizeof() sizeof(a), where a is


Returns the size of a variable.
integer, will return 4.

& &a; returns the actual


Returns the address of a variable.
address of the variable.
Unit 2 C Progg

* Pointer to a variable. *a;

?: If Condition is true ?
Conditional Expression. then value X : otherwise
value Y

Syntax for Sizeof:


sizeof(Expression);

Example:
// C Program To demonstrate sizeof operator
#include <stdio.h>
int main()
{
printf("%lu\n", sizeof(char));
printf("%lu\n", sizeof(int));
printf("%lu\n", sizeof(float));
printf("%lu", sizeof(double));
return 0;
}
Output
1
4
4
8

C Ternary Operator:
Unit 2 C Progg

We use the ternary operator in C to run one code when the condition is
true and another code when the condition is false.
Syntax:

testCondition ? expression1 : expression 2;

Example:
#include <stdio.h>
int main()
{
int age;
// take input from users
printf("Enter your age: ");
scanf("%d", &age);
// ternary operator to find if a person can vote or not
(age >= 18) ? printf("You can vote") : printf("You cannot vote");
return 0; }
Output:

Enter your age: 12


You cannot vote

EXPRESSIONS IN C:
A C expression is a union of operators and operands. A C expression is
used to calculate a single value that is saved in a variable. The action or
operation to be carried out is indicated by the operator. The objects to which we
apply the operation are known as operands.
Unit 2 C Progg

The below diagram is an example of how a C expression looks like using


the variable, operator, and operands:

Ways of Writing an Expression in C


The C Expressions can be defined by the number of operands, operators, and
their positions. Discussed below are the six ways of writing an expression in the
C Language:

a. Infix
When the operator lies between the operands then the expression is known as an
Infix expression. Below is the representation:
X=A+B
+ operator lies between the two operands A and B.

Y=U+N–O
+ and −− operator lies between the operands, so it is also an infix expression.

b. Postfix
When the operator lies after the operands then the expression is known as a
Postfix expression. Below is the representation:
Unit 2 C Progg

X = AB+
+ operator lies after the two operands A and B.

c. Prefix
When the operator lies before the operands then the expression is known as a
Prefix expression. Below is the representation:
X = +AB
+ operator lies before the two operands A and B.

Postfix and Prefix expressions can't be used directly while coding a program.
These expressions are generally used by the compilers during the compilation
process of a program as there is no issue of operator precedence or associativity
with postfix and prefix expressions.

d. Unary
When the expression contains only one operand and one operator then the
expression is known as a Unary expression. Below is the representation:
A++
--A
++B
B --
++ and -- are the increment and decrement operators that can lie before
and after a single operand in a unary expression. We will see more about it later
in the article using a C program.

e. Binary
When the expression contains two operands and only one operator then
the expression is known as a Binary expression. Below is the representation:
A+B
A/B
A%B
Unit 2 C Progg

An operator from +, -, *, /, %, etc. operators can lie between the operands


in a Binary expression. We will see more about it later in the article using a C
program.
f. Ternary
When the expression contains three operands and two operators then the
expression is known as a Ternary expression. We use the ternary operator (?: ?:)
in the ternary/conditional expressions, below is the representation:
X = (A > B) ? A : B
The above ternary expression is evaluated as, if A is greater than B, then
assign A to X, else assign B to X.

Example C Program for an expression:


#include<stdio.h>
int main()
{
// declaring variables to write different expressions using the same variables
int a, b, c, d;
int u1, u2, b1, b2, i1, i2, t1;
printf("Enter 4 values: ");
// taking 4 input values from the user
scanf("%d %d %d %d", &a, &b, &c, &d);
printf("\nNow, a = %d, b = %d, c = %d, d = %d\n", a, b, c, d);
// unary expressions in C language
u1 = a++; // post increment, so 2 will be assigned to u1 then
a will increment to 3
u2 = --b; // pre decrement, so first b will decrease by 1 to 2,
and 2 will be assigned to u2
printf("Unary Expression: u1 = %d u2 = %d\n", u1, u2);
printf("Now, a = %d, b = %d, c = %d, d = %d\n", a, b, c, d);
// Binary Expressions in C language
Unit 2 C Progg

// these expressions can also be considered infix expressions


b1 = a + b; // (3 + 2 = 5)
b2 = c - d; // (4 - 6 = -2)

printf("Binary Expression: b1 = %d b2 = %d\n", b1, b2);


// Infix Expressions or Primary Expressions in C language
i1 = a + (4 * b); // 3 + (4 * 2) = 11
i2 = (a + b) * (c + d); // (3 + 2) * (4 + 6)
printf("Infix Expression: i1 = %d i2 = %d\n", i1, i2);
// Ternary Expressions in C language
t1 = (5 > 3) ? 1 : 0; // 1 will be stored in t1
printf("Ternary Expression: t1 = %d\n", t1);
// we can also execute statements using the ternary expressions
(a > b) ? printf("a = %d is big", a) : printf("b = %d is big", b);
// 3 > 2
return 0;
}

Input:
Enter 4 values: 2 3 4 6

Output:
Now, a = 2, b = 3, c = 4, d = 6
Unary Expression: u1 = 2 u2 = 2
Now, a = 3, b = 2, c = 4, d = 6
Binary Expression: b1 = 5 b2 = -2
Infix Expression: i1 = 11 i2 = 50
Ternary Expression: t1 = 1
Unit 2 C Progg

a = 3 is big

PRECEDENCE AND ORDER OF EVALUATION


The precedence and associativity of C operators affect the grouping and
evaluation of operands in expressions. An operator's precedence is meaningful
only if other operators with higher or lower precedence are present. Expressions
with higher-precedence operators are evaluated first.
Precedence can also be described by the word "binding." Operators with a
higher precedence are said to have tighter binding.

Precedence and associativity of C operators


Unit 2 C Progg

In the first expression, the bitwise-AND operator (&) has higher


precedence than the logical-OR operator (||), so a & b forms the first operand of
the logical-OR operation.
In the second expression, the logical-OR operator (||) has higher
precedence than the simple-assignment operator (=), so b || c is grouped as the
right-hand operand in the assignment. Note that the value assigned to a is either
0 or 1.
The third expression shows a correctly formed expression that may
produce an unexpected result.
The logical-AND operator (&&) has higher precedence than the
logical-OR operator (||), so q && r is grouped as an operand. Since the logical
operators guarantee evaluation of operands from left to right, q && r is
evaluated before s--.
However, if q && r evaluates to a nonzero value, s-- is not evaluated,
and s is not decremented. If not decrementing s would cause a problem in your
program, s-- should appear as the first operand of the expression, or s should be
decremented in a separate operation.

DECISION MAKING AND BRANCHING


Unit 2 C Progg

In C, decision-making statements are technology structures


enabling programmers to make decisions based on specific conditions or
criteria.

The decision-making statements in c are as follows.

● If statements
● If-else statements
● Nested-if statements
● Switch statements
● Nested switch statements

If statement

‘If’ is the most powerful decision-making statement in C language. Thus,


it is used to control the execution of statements. ‘If’ is used along with an
expression. It is a two-way branching or decision-making statement.

Syntax :

if(test expression)
{
Statements;
}
Unit 2 C Progg

Flow Diagram:

Example:

#include <stdio.h>
int main ()
{

/* local variable definition */


int a = 10;

/* check the boolean condition using if statement */

if( a < 20 ) {
/* if condition is true then print the following */
printf("a is less than 20\n" );
}
printf("value of a is : %d\n", a);
return 0;
}

Output:

a is less than 20
value of a is: 10
Unit 2 C Progg

If-else Statements:

An if statement can be followed by an optional else statement, which executes


when the Boolean expression is false.

Syntax

The syntax of an if...else statement in C programming language is −

if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}
else
{
/* statement(s) will execute if the boolean expression is false */
}

If the Boolean expression evaluates to true, then the if block will be executed,
otherwise, the else block will be executed.

Flow Diagram:

Example:

#include <stdio.h>
Unit 2 C Progg

int main ( )
{
/* local variable definition */
int a = 100;

/* check the boolean condition */


if( a < 20 ) {
/* if condition is true then print the following */
printf("a is less than 20\n" );
} else {
/* if condition is false then print the following */
printf("a is not less than 20\n" );
}
printf("value of a is : %d\n", a);
return 0;
}

Output:

a is not less than 20;


value of a is : 100

NESTED-IF STATEMENTS:

It is always legal in C programming to nest if-else statements, which means you


can use one if or else if statement inside another if or else if statement(s).

Syntax

The syntax for a nested if statement is as follows −

if( boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
if(boolean_expression 2) {
/* Executes when the boolean expression 2 is true */
}
}
Unit 2 C Progg

Example:

#include <stdio.h>

int main () {

/* local variable definition */


int a = 100;
int b = 200;

/* check the boolean condition */


if( a == 100 ) {

/* if condition is true then check the following */


if( b == 200 ) {
/* if condition is true then print the following */
printf("Value of a is 100 and b is 200\n" );
}
}

printf("Exact value of a is : %d\n", a );


printf("Exact value of b is : %d\n", b );
Unit 2 C Progg

return 0;
}

Output:

Value of a is 100 and b is 200


Exact value of a is : 100
Exact value of b is : 200

NESTED IF ELSE STATEMENS


A nested if-else statement is an if statement inside another if statement.
The general syntax of nested if-else statement in C is as follows:
if (condition1)
{
/* code to be executed if condition1 is true */
if (condition2) {
/* code to be executed if condition2 is true */
}
else
{
/* code to be executed if condition2 is false */
}
} else
{
/* code to be executed if condition1 is false */
}

Example:

#include <stdio.h>
int main()
{
int num;
printf("Enter a number: ");
scanf("%d", &num);

if (num > 0)
{
printf("%d is positive.\n", num);
}
Unit 2 C Progg

else
{
if (num < 0)
{
printf("%d is negative.\n", num);
}
else
{
printf("%d is zero.\n", num);
}
}
return 0;
}

Output:

Enter a number: 10
10 is positive.
Enter a number: -5
-5 is negative.
Enter a number: 0
0 is zero.
Unit 2 C Progg

SWITCH STATEMENTS:

A switch statement allows a variable to be tested for equality against a


list of values. Each value is called a case, and the variable being switched on is
checked for each switch case.

Syntax

switch(expression) {

case constant-expression :
statement(s);
break; /* optional */

case constant-expression :
statement(s);
break; /* optional */

/* you can have any number of case statements */


default : /* Optional */
statement(s);
}
Flow Diagram:

Example:
Unit 2 C Progg

#include <stdio.h>
int main ( ) {
/* local variable definition */
char grade = 'B';
switch(grade) {
case 'A' :
printf("Excellent!\n" );
break;
case 'B' :
case 'C' :
printf("Well done\n" );
break;
case 'D' :
printf("You passed\n" );
break;
case 'F' :
printf("Better try again\n" );
break;
default :
printf("Invalid grade\n" );
}
printf("Your grade is %c\n", grade );
return 0;
}

Output:
Well done
Your grade is B

NESTED SWITCH STATEMENTS

It is possible to have a switch as a part of the statement


sequence of an outer switch. Even if the case constants of the inner and outer
switch contain common values, no conflicts will arise.
Syntax:
switch(ch1) {
case 'A':
printf("This A is part of outer switch" );
Unit 2 C Progg

switch(ch2)
{
case 'A':
printf("This A is part of inner switch" );
break;
case 'B': /* case code */
}
break;
case 'B': /* case code */
}

Flow Diagram

Example:

#include <stdio.h>
int main () {
/* local variable definition */
int a = 100;
Unit 2 C Progg

int b = 200;
switch(a) {
case 100:
printf("This is part of outer switch\n", a );
switch(b) {
case 200:
printf("This is part of inner switch\n", a );
}
}
printf("Exact value of a is : %d\n", a );
printf("Exact value of b is : %d\n", b );

return 0;
}

Output:

This is part of outer switch


This is part of inner switch
Exact value of a is : 100
Exact value of b is : 200

BRANCHING STATEMENTS
A branch is an instruction in a computer program that can
cause a computer to begin executing a different instruction sequence and thus
deviate from its default behavior of executing instructions in order. Common
branching statements include,
● break,
● continue,
● return,
● goto

break

The break is used in one of two ways; with a switch to make it act like a
case structure or as part of a looping process to break out of the loop. The
following gives the appearance that the loop will execute 8 times, but the break
statement causes it to stop during the fifth iteration.

counter = 0;
Unit 2 C Progg

While counter < 8


Output counter
If counter == 4
break
counter += 1

continue

The following gives the appearance that the loop will print to the monitor
8 times, but the continue statement causes it not to print number 4.

For counter = 0, counter < 8, counter += 1


If counter == 4
continue
Output counter

return

The return statement exits a function and returns to the statement where
the function was called.

Function Documenting
statements
Return <optional return value>

goto

The goto structure is typically not accepted in good structured


programming. However, some programming languages allow you to create a
label with an identifier name followed by a colon. You use the command
word goto followed by the label.

some lines of code;


goto label; // jumps to the label
some lines of code;
some lines of code;
some lines of code;
label: some statement; // Declared label
some lines of code;

Key Terms

branching statements
Allow the flow of execution to jump to a different part of the program.
Unit 2 C Progg

break
A branching statement that terminates the existing structure.

continue
A branching statement that causes a loop to stop its current iteration and
begin the next one.

exit
A predefined function used to prematurely stop a program and return to
the operating system.

goto
An unstructured branching statement that causes the logic to jump to a
different place in the program.

return
A branching statement that causes a function to jump back to the function
that called it.

LOOPING STATEMENTS
Loops in programming are used to repeat a block of code until
the specified condition is met. A loop statement allows programmers to execute
a statement or group of statements multiple times without repetition of code.
Unit 2 C Progg

for Loop

The for loop in C programming is a repetition control structure that


allows programmers to write a loop that will be executed a specific number of
times. for loop enables programmers to perform n number of steps together in a
single line.

Syntax:
for (initialize expression; test expression; update expression)
{
body of for loop
}
Example:
for(int i = 0; i < n; ++i)
{
printf("Body of for loop which will execute till n");
}
In for loop, a loop variable is used to control the loop. Firstly we initialize the
loop variable with some value, then check its test condition. If the statement is
true then control will move to the body and the body of for loop will be
executed. Steps will be repeated till the exit condition becomes true. If the test
condition will be false then it will stop.
● Initialization Expression: In this expression, we assign a loop
variable or loop counter to some value. for example: int i=1;
● Test Expression: In this expression, test conditions are performed. If
the condition evaluates to true then the loop body will be executed and
then an update of the loop variable is done. If the test expression
becomes false then the control will exit from the loop. for example,
i<=9;
● Update Expression: After execution of the loop body loop variable is
updated by some value it could be incremented, decremented,
multiplied, or divided by any value.

// C program to illustrate for loop


#include <stdio.h>
int main()
Unit 2 C Progg

{
int i = 0;
for (i = 1; i <= 5; i++)
{
printf( "Hello World\n");
}
return 0;
}

Output
Hello World
Hello World
Hello World
Hello World
Hello World

While Loop

While loop does not depend upon the number of iterations. In for loop the
number of iterations was previously known to us but in the While loop, the
execution is terminated on the basis of the test condition. If the test condition
will become false then it will break from the while loop else body will be
executed.
Syntax:
initialization_expression;
while (test_expression)
{
// body of the while loop
update_expression;
}
Unit 2 C Progg

Example:
// C program to illustrate while loop //
#include <stdio.h>
int main()
{
// Initialization expression
int i = 2;
// Test expression
while(i < 5)
{ // loop body
printf( "Hello World\n");
// update expression
i++;
}
return 0; }
Output
Hello World
Hello World
Unit 2 C Progg

DO-WHILE LOOP

The do-while loop is similar to a while loop but the only difference lies in
the do-while loop test condition which is tested at the end of the body. In the
do-while loop, the loop body will execute at least once irrespective of the test
condition.

Syntax:
initialization_expression;
do
{
// body of do-while loop
update_expression;
} while (test_expression);

// C program to illustrate do-while loop //


#include <stdio.h>
int main()
{
// Initialization expression
int i = 2;
do
Unit 2 C Progg

{ // loop body
printf( "Hello World\n");
// Update expression
i++;
// Test expression
} while (i < 1);
return 0; }
Output
Hello World
UNIT – II PROGRAMS WITH ALGORITHM AND FLOW CHART

1. GENERATE FIBONACCI SERIES

Algorithm to Generate Fibonacci Series

1. Start
2. Declare Variables:
o i: Integer to count the number of terms
o a: Integer to hold the first Fibonacci number (initialized to 0)
o b: Integer to hold the second Fibonacci number (initialized to 1)
o show: Integer to hold the current Fibonacci number
o num_terms: Integer to hold the number of terms to print
3. Initialize:
o Set a = 0
o Set b = 1
o Set show = 0
o Set i = 2 (since the first two terms are already known)
4. Input: Prompt the user to enter the number of terms (num_terms) of the Fibonacci series to
be printed.
5. Output: Print the first two terms (a and b).
6. Loop: While i < num_terms:
o Set show = a + b
o Update a = b
o Update b = show
o Increment i by 1
o Print the value of show
7. End
PROGRAM:

#include <stdio.h>

int main() {
int i, a, b, show, num_terms;

// Initialize variables
a = 0; // First Fibonacci number
b = 1; // Second Fibonacci number
show = 0; // Current Fibonacci number
i = 2; // Start counting from the third term

// Input: Number of terms


printf("Enter the number of terms: ");
scanf("%d", &num_terms);

// Print first two terms


if (num_terms >= 1) {
printf("%d\n", a); // Print first term
}
if (num_terms >= 2) {
printf("%d\n", b); // Print second term
}

// Generate and print the Fibonacci series


while (i < num_terms) {
show = a + b; // Calculate the next term
printf("%d\n", show); // Print the current Fibonacci number
a = b; // Update a to the previous term
b = show; // Update b to the current term
i++; // Increment the count
}

return 0;
}
2. FINDING THE ROOTS OF QUADRATIC EQUATION

ALGORITHM:

Step 1: Start
Step 2: Read the variable a, b, c.
Step 3: Compute d= b*b - 4*a*c.
Step 4: Test the condition, d is greater than 0 using IF statement.
Step 4.1: Calculate: r1= (-b + sqrt(d)) / (2*a).
Step 4.2: Calculate: r2= (-b - sqrt(d)) / (2*a).
Step 4.3: Print the roots r1 and r2.
Step 5: Else, test the condition, d is equal to 0 using IF statement.
Step 5.1: Calculate: r1=r2 = -b / (2*a).
Step 5.2: Print the roots r1 and r2.
Step 6: Else, compute real and imaginary as
Step 6.1: Calculate: real = -b / (2*a).
Step 6.2: Calculate imag = sqrt(-d)/(2*a).
Step 6.3: Print the real and imag.
Step 7: Stop
PROGRAM

#include <stdio.h>
#include <math.h> /* This is needed to use sqrt() function.*/
#include <conio.h>
void main()
{
float a, b, c, d, r1,r2, real, imag;
clrscr();
printf("\nPRG TO FIND THE ROOTS OF A QUADRATIC EQUATION");
printf("\n---------------------------------------------------------------------");
printf("Enter the coefficients a, b and c: ");
scanf("%f%f%f",&a,&b,&c);
d=b*b-4*a*c; /*calculating the value of d */
if (d>0) /*Checking real solution is possible or not */
{
r1= (-b+sqrt(d))/(2*a); / *finding the root of quadratic equation
*/ r2= (-b-sqrt(d))/(2*a);
printf("Roots are: %.2f and %.2f. They are real and distinct.", r1 , r2);
}
else if (d==0)
{
r1 = r2 = -b/(2*a);
printf("Roots are: %.2f and %.2f. They are real and equal.", r1, r2);
}
else
{
real= -b/(2*a);
imag = sqrt(-d)/(2*a);
printf("Roots are: %.2f+%.2fi and %.2f-%.2fi. They are complex.", real, imag,
real, imag);
}
getch();
}
OUTPUT:
3. ARMSTRONG NUMBER

ALGORITHM:

Step 1: Start
Step 2: Read the variable N
Step 3: Assign N1=N;
Step 4: Set a loop using the condition WHILE(N1!=0), if the condition true
Step 4.1: REM=N1%10;
Step 4.2: NUM=NUM+REM*REM*REM;
Step 4.3: N1=N1/10;
Step 5: Else, check the condition IF(NUM=N), if the condition true
Step 5.1 PRINT “Armstrong Number”
Step 5.2 Else PRINT “Not Armstrong Number”
Step 6: Stop
PROGRAM:

#include <stdio.h>
#include <conio.h>
void main()
{
int n, n1, rem, num=0;
clrscr();
printf("\nPRG TO CHECK WHETHER A GIVEN NO. IS ARMSTRONG NO. OR
NOT");
printf("\n-------------------------------------------------------------------------------------");
printf("Enter a positive integer: ");
scanf("%d", &n);
n1=n;
while(n1!=0)
{
rem=n1%10;
num=num+(rem*rem*rem);
n1=n1/10;
}
if(num==n)
printf("%d is an Armstrong number.",n);
else
printf("%d is not an Armstrong number.",n);
getch();
}
4. MENU DRIVEN PROGRAM

ALGORITHM:

Step 1: Start
Step 2: Declare the variables
Step 3: Show the choices and get the choice from the user
Step 4: Pass the choice in to switch case
Step 5: In case 1,
Step 5.1: Calculate Addition=a+b
Step 5.3: Print Addition
Step 6: In case 2,
Step 6.1: Calculate Subtraction=a-b
Step 6.2: Print Subtraction
Step 7: In case 3,
Step 7.1: Calculate multiplication=a*b
Step 7.2: Print multiplication
Step 8: In case 4,
Step 8.1: Calculate Division=a/b
Step 8.2: Print Division
Step 9: In case 5,
Step 8.1: Calculate modulo division =a%b
Step 8.2: Print modulo division
Step 10: Check the Choice. If CH=!6 then go to step 3 else got to step 11.
Step 11: Stop
PROGRAM:

#include<stdio.h>
void main()
{
int ch, a, b;
float add,sub,mul,div,mod; clrscr();
do
{
printf("\n*****Menu****");
printf("\n1.addition\n2.subtraction\n3.multiplication\n4.division\n5.Modulo division\n");
printf("\nEnter the choice:");
scanf("%d",&ch);
if((ch>=0)&&(ch<=5))
{
printf("Enter the values:\n");
printf("A=");
scanf("%d",&a);
printf("B=”);
scanf("%d",&b);
}
switch(ch)
{
case 1:
add=a+b;
printf("\nAddition=%d",add);
break;
case 2:
sub=a-b;
printf("\nsubtraction=%d",sub);
break;
case 3:
mul=a*b;
printf("\nmultiplication=%d",mul);
break;
case 4:
div=a/b;
printf("\ndivision=%f",div);
break;
case 5:
mod=a%b;
printf("\nmodulo division=%d",mod);
break;
default:
printf("wrong choice");
break;
exit(0);
}
}
while (ch<6);
getch();
}
FLOW CHART
OUTPUT
5. GENERATING PRIME NUMBERS BETWEEN A GIVEN RANGES

ALGORITHM:

Step 1: Start
Step2: Declare variables
Step 3: Get two intervals LOWER, UPPER
Step 4: Set a FOR LOOP that traces the iteration till the upper limit.
Step 4.1: Initialize the counter value as n=LOWER+1, condition as n<UPPER. Assign
the flag value as PRIME=1.
Step 5: Set a FOR LOOP to check whether the number is prime or not.
Step 5.1.a: Initialize the counter value as i=2, condition as i<n.
Step 5.1.b: Extract the remainder of number ‘n’ by dividing with counter value ‘i’.
Step 5.1.c: If the remainder is 0 then set the flag PRIME value to 0 and go to Step 4.1,
Increment the counter value by 1 as ‘n++’.
Step 5.1.d: Else, Increment the counter value by 1 and do the step 5 to 5.1.c.
Step 5.2: Check the flag value.
Step 5.2.a: If the flag value is 1 then print the number as PRIME.
Step 6: Stop
PROGRAM:

#include<stdio.h>
void main()
{
int i, prime, up, low, n;
clrscr();
printf("\n--------------------------------------------------------------------------------------");
printf("\n\nPROGRAM TO FIND THE PRIME NUMBERS BETWEEN A GIVEN
RANGE");
printf("\n\n------------------------------------------------------------------------------------");
printf("\n\n\t ENTER THE LOWER LIMIT...: ");
scanf("%d",&low);
printf("\n\n\t ENTER THE UPPER LIMIT...: ");
scanf("%d",&up);
printf("\n\n\t PRIME NUMBERS ARE...: ");
for(n=low+1; n<up; n++)
{
prime = 1;
for(i=2; i<n; i++)
{
if(n%i == 0)
{
prime = 0;
break;
}
}
if(prime)
printf("\n\n\t\t\t%d",n);
}
printf("\n\n---------------------------------------------------------------------------------");
getch();

}
6. GENERATING SINE SERIES

Formula of Sine Series:

ALGORITHM:

Step 1: Start
Step2: Declare the variables
Get ANGLE X, TERMS
Step3: N
Step4: Calculate variables as
Z=X;
X=X*(3.14/180);
SUM=X;
T=X;
Step5: Set a FOR LOOP that traces the iteration till the upper limit.
Step 5.1: Initialize the counter value as i=2, condition as I<=N
Step5.2: Calculate T=T*(-X*X)/((2*I-1)*(2*I-2))
Step 5.3: SUM=SUM+T;
Step 5.4: Increment the counter value by 2 as ‘I+2’. Check the
condition I<=N, If it is true then go to step 5.2.
Step 5.5: Else, PRINT SUM
Step 6: Stop
PROGRAM:

#include<stdio.h>
#include<math.h>
#include<conio.h>
void main()
{
int i,n;
float x,y,z,sum,t;
clrscr();
printf("\t\t PROGRAM TO PRINT SINE SERIES\t\t\n");
printf("\t\t ---------------------------------------------t\t\n");
printf("\n ENTER THE ANGLE:");
scanf("%f", &x);
printf("\n ENTER THE NUMBER OF TERMS:");
scanf("%d", &n);
z=x;
x=x*(3.14/180);
sum=x;
t=x;

for(i=2; i<=n; i=i+2)


{
t=t*(-x*x)/((2*i-1)*(2*i-2));
sum=sum+t;
}
printf("\n\n THE VALUE OF SIN(%5.2f) IS %5.2f\n", z,
sum); getch();
}
7. REVERSING THE DIGITS OF A NUMBER

ALGORITHM:

Step 1: Start
Step2: Declare the variables
Step 3: Read input N
Step 4: Set a loop using WHILE until N != 0. If the condition is true then
Step 4.1: REVERSE = REVERSE * 10;
Step 4.2: REVERSE = REVERSE + N%10;
Step 4.3: N = N/10;
Step 5: If condition fails, then PRINT REVERSE
Step 6: Stop
PROGRAM:

#include<stdio.h>
#include<conio.h>
void main()
{
int n, reverse = 0;
clrscr();
printf("REVERSAL OF A GIVEN NUMBER\n");
printf("--------------------------------------\n");
printf("ENTER A NUMBER TO REVERSE: \n");
scanf("%d",&n);
while (n != 0)
{
reverse = reverse * 10;
reverse = reverse + n%10;
n = n/10;
}
printf("REVERSE OF ENTERED NUMBER IS: %d\n", reverse);
getch();
}
EXTRA PROGRAMS:

1. Factorial of a Number

Calculates the factorial of a given number using a loop.

#include <stdio.h>

int main() {
int num, i;
long long factorial = 1;

printf("Enter a number: ");


scanf("%d", &num);

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


factorial *= i;
}

printf("Factorial of %d = %lld\n", num, factorial);


return 0;
}

OUTPUT:

Enter a number: 5
Factorial of 5 = 120

2. Pattern Printing

Prints a simple pattern using nested loops.

#include <stdio.h>

int main() {
int rows;

printf("Enter number of rows: ");


scanf("%d", &rows);

for (int i = 1; i <= rows; i++) {


for (int j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}

return 0;
}
OUTPUT

Enter number of rows: 4

*
**
***
****

3. Check whether a given number is Palindrome or not

#include <stdio.h>

int main() {
int num, originalNum, reversedNum = 0, remainder;

// Input: Get the number from the user


printf("Enter an integer: ");
scanf("%d", &num);

originalNum = num; // Store the original number for comparison

// Reverse the number


while (num != 0) {
remainder = num % 10; // Get the last digit
reversedNum = reversedNum * 10 + remainder; // Build the reversed number
num /= 10; // Remove the last digit
}

// Check if the original number and reversed number are the same
if (originalNum == reversedNum) {
printf("%d is a palindrome.\n", originalNum);
} else {
printf("%d is not a palindrome.\n", originalNum);
}

return 0;
}

OUTPUT:

Enter an integer: 121


121 is a palindrome.

Enter an integer: 123


123 is not a palindrome.
4. Find GCD of Two Numbers

Calculates the Greatest Common Divisor (GCD) using the Euclidean algorithm.

#include <stdio.h>

int main() {
int a, b;

printf("Enter two integers: ");


scanf("%d %d", &a, &b);

while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}

printf("GCD is %d\n", a);


return 0;
}

OUTPUT:

Enter two integers: 48 18


GCD is 6

5. Count Vowels and Consonants in a String

#include <stdio.h>

int main() {
char ch;
int vowels = 0, consonants = 0;

printf("Enter characters (press '.' to stop):\n");


while (1) {
ch = getchar(); // Read a character
if (ch == '.') {
break; // Exit on dot
}
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
vowels++;
} else {
consonants++;
}
}
}
printf("Vowels: %d, Consonants: %d\n", vowels, consonants);
return 0;
}
OUTPUT:

Enter characters (press '.' to stop):


Hello World.

Vowels: 3, Consonants: 7

6. Sum of Digits of a Number

#include <stdio.h>

int main() {
int num, sum = 0, remainder;

printf("Enter an integer: ");


scanf("%d", &num);

while (num != 0) {
remainder = num % 10; // Get last digit
sum += remainder; // Add last digit to sum
num /= 10; // Remove last digit
}

printf("Sum of digits: %d\n", sum);


return 0;
}

OUTPUT:

Enter an integer: 9999


Sum of digits: 36

You might also like