Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

C Programming - Module 2 - 07 Dec 2023

The document discusses various operators in C programming like arithmetic, relational, logical, assignment, increment/decrement and bitwise operators. It also covers operator precedence and type conversion in C. The examples provided explain the usage and working of different operators.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

C Programming - Module 2 - 07 Dec 2023

The document discusses various operators in C programming like arithmetic, relational, logical, assignment, increment/decrement and bitwise operators. It also covers operator precedence and type conversion in C. The examples provided explain the usage and working of different operators.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 95

C Programming

Module 2
Module Coverage
• Operators
• Decision Control statements
• Loop Control statements
Operators
The operators are types of symbols that inform a
compiler for performing some specific logical or
mathematical functions.
The operators serve as the foundations of the
programming languages.
C provides a wide range of operators, which can be
classified into different categories based on their
functionality. Operators are used for performing
operations on variables and values.
In other words, we can say that an operator
operates the operands. For example, ‘+’ is an
operator used for addition in the statemement
c=a+b; here, ‘+’ is the operator known as the
addition operator, and ‘a’ and ‘b’ are operands.
1. Arithmetic Operators: Arithmetic operators are used to perform common
mathematical operations.
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;
}
2. Assignment Operators: An assignment operator is used for assigning a value to
a variable.
Example:
#include <stdio.h>
int main()
{
int a = 5, c;
c = a; // c is 5
printf("c = %d\n", c);
c += a; // c is 10
printf("c = %d\n", c);
c -= a; // c is 5
printf("c = %d\n", c);
c *= a; // c is 25
printf("c = %d\n", c);
c /= a; // c is 5
printf("c = %d\n", c);
c %= a; // c = 0
printf("c = %d\n", c);
return 0;
}
3. 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.
Example:
#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);
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;
}
4. Logical Operators: An expression containing logical operator returns either 0
or 1 depending upon whether expression results true or false. Logical operators
are used to determine the logic between variables or values.
Example:
#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;
}
5. Increment & Decrement Operators: Increment ++ increases the value by 1
whereas decrement -- decreases the value by 1. These two operators are unary
operators, meaning they only operate on a single operand.
Example:

#include <stdio.h>
int main()
{
int a = 10, b = 100;
float c = 10.5, d = 100.5;
printf("++a = %d \n", ++a);
printf("--b = %d \n", --b);
printf("++c = %f \n", ++c);
printf("--d = %f \n", --d);
return 0;
}
6. Bitwise Operators: In the arithmetic-logic unit (which is within the CPU),
mathematical operations like: addition, subtraction, multiplication and division
are done in bit-level. To perform bit-level operations in C programming, bitwise
operators are used.
Example: (Bitwise AND operator &) The output of bitwise AND is 1 if the
corresponding bits of two operands is 1. If either bit of an operand is 0, the result
of corresponding bit is evaluated to 0.

#include <stdio.h>
int main()
{
int a = 12, b = 25;
printf("Output = %d", a & b);
return 0;
}
Example: (Bitwise OR operator |) The output of bitwise OR is 1 if at least one
corresponding bit of two operands is 1.

#include <stdio.h>
int main()
{
int a = 12, b = 25;
printf("Output = %d", a | b);
return 0;
}
7. Conditional Operators: The conditional operator is also known as a Ternary
operator. The conditional statements are the decision-making statements which
depends upon the output of the expression. It is represented by two symbols, i.e.,
'?' and ':'.
As conditional operator works on three operands, so it is also known as the
ternary operator.
The syntax of ternary operator is : testCondition ? expression1 : expression 2;
Example:

#include <stdio.h>
int main()
{
int age;
printf("Enter your age: ");
scanf("%d", &age);
(age >= 18) ? printf("You can vote") : printf("You cannot vote");
return 0;
}
Type Conversion
In C programming, we can convert the value of one data type (int, float, double,
etc.) to another. This process is known as type conversion.
There are two types of conversion in C:
• Implicit Conversion (automatically)
• Explicit Conversion (manually)

Implicit conversion is done automatically by the compiler when you assign a value
of one type to another.
Explicit conversion is done manually by placing the type in parentheses () in front
of the value.
Example: (Implicit type conversion)

#include<stdio.h>
int main()
{
// create a double variable
double value = 4150.12;
printf("Double Value: %.2lf\n", value);

// convert double value to integer


int number = value;
printf("Integer Value: %d", number);

return 0;
}
Example: (Explicit type conversion)

#include<stdio.h>
int main()
{
float a = 1.2;

//int b = a; //Compiler will throw an error for this

int b = (int)a + 1;

printf("Value of a is %f\n", a);


printf("Value of b is %d\n",b);

return 0;
}
Operator Precedence in C
The sequence in which operations are carried out in an expression in C is
determined by operator precedence. It specifies which operators are evaluated
first and which are evaluated last when multiple operators are present in an
expression.
Let us consider an example: int x = 5 - 17* 6;
• In C, the precedence of * is higher than - and =.
• Hence, 17 * 6 is evaluated first.
• Then the expression involving - is evaluated as the precedence of - is higher
than that of =.
The associativity of operators determines the direction in which an expression is
evaluated.
For example: b = a;
• Here, the value of a is assigned to b, and not the other way around. It's
because the associativity of the = operator is from right to left.
Also, if two operators of the same precedence (priority) are present, associativity
determines the direction in which they execute.
Let us consider an example: 1 == 2 != 3
• Here, operators == and != have the same precedence. And, their
associativity is from left to right. Hence, 1 == 2 is executed first.
• Thus the expression above is equivalent to: (1 == 2) != 3
Program # 12
Aim: To enhance the program 11 by replacing student details with the marks obtained in Written
Test for the subjects Aptitude, Reasoning and Soft Skills.

/************************************************************************************************************************
File Name: program12.c
Author: vrsyrn
Date & Time : 15/11/2023; 09:15 AM
Description: a program to display the written test marks of a student
************************************************************************************************************************/

Program 12
Output:
Note 12:
• A Variable “no_of_subj” is declared with a data type “int” to store the number
of subjects present in the Written Test. This variable accepts only integer
values and hence it is declared with “int” data type.
• Since we are handling only three subjects for this program, we initiate the
Variable “no_of_subj” with the value 3.
• There are three variables declared in this program to handle the marks
obtained by a Student in three different subjects. Since, all these Variables
holds only integer values, we declare all these variables with the Data Type
“int”.
Program # 13
Aim: To enhance the program 12 by calculating the average of the marks secured by Student in the
written test exam.

/************************************************************************************************************************
File Name: program13.c
Author: vrsyrn
Date & Time : 15/11/2023; 09:30 AM
Description: a program to calculate the average of the marks secured by Student
************************************************************************************************************************/

Program 13
Output:
Note 13:
• There are three variables declared in this program to handle the marks
obtained by a Student in three different subjects. Since, all these Variables
holds only integer values, we declare all these variables with the Data Type
“int”.
• After entering all the three subject marks, we have to calculate Average.
• For storing this Average value, we need a Variable “avg” of data type “float”.
• Since, there is a maximum chance that the Average value would be a decimal
valued one; it is advised to declare these types of Variables with “float” data
type. “int” will not handle decimal values.
• During the execution, we have calculated the Average, and it is stored in the
Variable “avg” with value “63.000000”.
• The fractional part is obtained with all zeroes, in order to calculate the exact
average; we need to implement “Type Casting” i.e. the output value is casted
again with “float” data type which in turn delivers us the exact Average value
(63.666668).
• To store this Value, we declared one more Variable called “exactavg” with
data type “float”.
Program # 14
Aim: To enhance the program 13 by taking student marks from the console and calculate the
average of marks obtained.

/************************************************************************************************************************
File Name: program14.c
Author: vrsyrn
Date & Time : 15/11/2023; 10:30 AM
Description: a program to calculate the average of marks by taking input from Console
************************************************************************************************************************/

Program 14
Output:
Note 14:
• In this program, the subject marks are taken as input from the console using
scanf() function.
• The scanf() is defined in <stdio.h> header file.
• The calculation of average marks is repeated as same from the previous
program.
• Escape sequences \n and \t are used to format the output on console.
Assignments
21. Write a C Program to input two numbers and perform all arithmetic operations
like sum, difference, product, quotient and modulus of two given numbers.
Example:
Input:
Enter first number: 10
Enter second number: 5
Output:
Sum = 15
Difference = 5
Product = 50
Quotient = 2
Modulus = 0
Assignments

22. Write a C Program to input temperature in Centigrade and convert to


Fahrenheit. Hint: fahrenheit = (celsius * 9 / 5) + 32;

23. Write a C Program to to input number of days from user and convert it to years,
weeks and days.
Hint:
years = (days / 365); // Ignoring leap year
weeks = (days % 365) / 7;
days = days - ((years * 365) + (weeks * 7));
Example:
Assignments
24. Write a C program to input principle, time and rate (P, T, R) from user and find
Simple Interest.
Hint: SI = (principle * time * rate) / 100;
Example:

25. Write a C program to find the square of a given number without using any
mathematical function.

26. Write a C program to input two numbers from user and find maximum between
two numbers using conditional/ternary operator.

27. Write a C program to input three numbers from user and find maximum
between three numbers using conditional/ternary operator.
Assignments

28. Write a C program to input a number from user and check whether number is
even or odd using Conditional/Ternary operator.

29. Write a C program to input a character and check whether the character is
alphabet or not using Conditional/Ternary operator.

30. Write a C program to input two numbers from user and find their power using
pow() function. Hint: power = pow(base, expo);

31. Write a C program to calculate the Gross salary of an employee taking the
Basic, HRA and DA amount from the user.
Hint: Gross = Basic+DA+HRA+PF;
P.F = (Basic*12)/100;
Decision Control Statements
A statement or set of statements that is executed when a particular condition is
True and ignored when the condition is False is called Decision Control
Structure.
The decision to execute a particular section is based on checking a condition.
There come situations in real life when we need to make some decisions and
based on these decisions, we decide what should we do next.
Similar situations arise in programming also where we need to make some
decisions and based on these decisions we will execute the next block of code.
For example, in C if x occurs then execute y else execute z.
There can also be multiple conditions like in C if x occurs then execute p, else if
condition y occurs execute q, else execute r.
This condition of C else-if is one of the many ways of importing multiple
conditions.
If statement:
The if statement is the most simple decision-making statement. It is used to
decide whether a certain statement or block of statements will be executed or
not i.e if a certain condition is true then a block of statements is executed
otherwise not.
Syntax:
if(condition)
{
// Statements to execute if condition is true
}
If we do not provide the curly braces ‘{‘ and ‘}’ after if(condition) then by
default if statement will consider the first immediately below statement to be
inside its block.
Example: Program to display a number if it is negative

#include <stdio.h>
int main()
{
int number;
printf("Enter an Integer value: ");
scanf("%d", &number);
if (number < 0)
{
printf("\nYou entered a negative Integer: %d \n", number);
}
printf("The if statement is easy.");
return 0;
}
If-else statement:
The if statement alone tells us that if a condition is true it will execute a block
of statements and if the condition is false it won’t. But what if we want to do
something else when the condition is false? Here comes the C else statement.
We can use the else statement with the if statement to execute a block of code
when the condition is false.
Syntax:
if (condition)
{
// Executes this block if condition is true
}
else
{
// Executes this block if condition is false
}
Example: Program to check whether an integer is odd or even
#include <stdio.h>
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d", &number);
if (number%2 == 0)
{
printf("\n %d is an even integer.",number);
}
else
{
printf("\n %d is an odd integer.",number);
}
return 0;
}
Nested If-else statement:
A nested if in C is an if statement that is the target of another if statement.
Nested if statements mean an if statement inside another if statement. Yes, both
C and C++ allow us to nested if statements within if statements, i.e, we can
place an if statement inside another if statement.
Syntax:
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
else
{
// Executes when condition2 is false
}
}
Example: Program to relate two integers using =, > or < symbol
#include <stdio.h>
int main()
{
int number1, number2;
printf("Enter two integers:\n ");
scanf("%d %d", &number1, &number2);
if (number1 >= number2)
{
if (number1 == number2)
{
printf("Result: %d = %d",number1,number2);
}
else
{
printf("Result: %d > %d", number1, number2);
}
}
else
{
printf("Result: %d < %d",number1, number2);
}
return 0;
}
If-else ladder statement: Syntax:

The if...else statement executes two if (test expression1)


{
different codes depending upon
// statement(s)
whether the test expression is true
}
or false. else if(test expression2)
Sometimes, a choice has to be made {
// statement(s)
from more than 2 possibilities.
}
The if...else ladder allows you to else if (test expression3)
check between multiple test {
expressions and execute different // statement(s)
statements. }
.
.
else
{
// statement(s)
}
Example: Program to relate two integers using =, > or < symbol

#include <stdio.h>
int main()
{
int number1, number2;
printf("Enter two integers:\n ");
scanf("%d %d", &number1, &number2);
if(number1 == number2)
{
printf("Result: %d = %d",number1,number2);
}
else if (number1 > number2)
{
printf("Result: %d > %d", number1, number2);
}
else
{
printf("Result: %d < %d",number1, number2);
}
return 0;
}
Switch statement: Syntax:
The switch case statement is an switch (expression)
alternative to the if else if ladder that {
can be used to execute the conditional case value1:
code based on the value of the variable statements;
specified in the switch statement. case value2:
statements;
The switch block consists of cases to be ....
executed based on the value of the ....
switch variable. ....
default:
statements;
}
Example: Program to create a simple calculator
#include <stdio.h> case '*':
int main() printf("%d * %d = %%d",n1, n2, n1*n2);
{ break;
char operation;
int n1, n2; case '/':
printf("Enter an operator (+, -, *, /):\n"); printf("%d / %d = %df",n1, n2, n1/n2);
scanf("%c", &operation); break;
printf("Enter any two Integers:\n"); default:
scanf("%d %d",&n1, &n2); printf("Error! operator is not correct");
switch(operation) }
{ return 0;
case '+': }
printf("%d + %d = %d",n1, n2, n1+n2);
break;

case '-':
printf("%d - %d = %d",n1, n2, n1-n2);
break;
Program # 15
Aim: To enhance the program 14 and check whether the student is eligible for evaluating his Grade
based on the marks Average.
/************************************************************************************************************************
File Name: program15.c
Author: vrsyrn
Date & Time : 16/11/2023; 10:00 AM
Description: a program to calculate the Grade of a student based on his marks Average
************************************************************************************************************************/

Program 15
Output:
Note 15:
• In this program, the if-else decision control statement is used.
• After entering the Screening test marks by user, the Average of marks is
calculated using Arithmetic operators.
• The minimum cut off for a student to be eligible for Grade evaluation is 50%.
• Any student who secure less than 50% in screening test is not eligible for Grade
evaluation.
• This condition is succesfully implemented using if-else block.
• The test condition is written inside if statement i.e. if(avg>=50) and only those
inputs which pass this condition are taken forward to evaluate Grade.
• Any input which get failed in the if case, the else block is executed.
Program # 16
Aim: To enhance the program 15 to display the Grade obtained by a Student based on the Average
Marks secured in the Written Test.
/************************************************************************************************************************
File Name: program16.c
Author: vrsyrn
Date & Time : 16/11/2023; 10:30 AM
Description: a program to calculate the Grade of a student based on his marks Average
************************************************************************************************************************/

Program 16
Output:
Note 16:
• To evaluate Grade of a student, the “Average Marks” obtained by the student
is needed as input.
• We already have the Average score of a student in the Variable “avg”.
• A Variable “grade” is declared with the Data type “char”.
• A Grade of a student would be normally a character (A/B/C/D/E/F), so int and
float cannot handle such data; that is why we need “char” data type, which
can hold a single character.
• The Format Specifier for handling “char” is “%c”.
• Now, in order to evaluate Grade of a student, we have to develop few Test
Conditions, based on which the “Grade” of a student is derived.
Note 16:
• Following are the Test conditions:
a. If the Average Score is greater than or equal to 90, then the Grade is
“A”
b. If the Average Score is greater than or equal to 80 and less than 90,
then the Grade is “B”
c. If the Average Score is greater than or equal to 70 and less than 80,
then the Grade is “C”
d. If the Average Score is greater than or equal to 60 and less than 70,
then the Grade is “D”
e. If the Average Score is greater than or equal to 50 and less than 60,
then the Grade is “E”
f. Any Student not falling in the above said conditions would be awarded
with the Grade “F”
Note 16:
• These Test-Conditions can be programmed in C using “Decision Control”
statements like “if”, “else” and “else if” condition statements.
a. If – if statement is the most simple decision making statement. It is
used to decide whether a certain statement or block of statements will
be executed or not
b. Else – We can use the else statement with if statement to execute a
block of code when the condition is false.
c. Else if – else-if statements in C is like another if condition, it's used in a
program when if statement is having multiple decisions.
• Once the “Grade is evaluated, it is stored in the Variable “grade” and the
same is displayed on the terminal with the help of Format Specifier “%c”.
Program # 17
Aim: To enhance the program 16 to display a message to the user after entering his Grade through
console.
/************************************************************************************************************************
File Name: program17.c
Author: vrsyrn
Date & Time : 16/11/2023; 11:30 AM
Description: a program to display a message to the user after entering his Grade
************************************************************************************************************************/

Program 17
Output:
Note 17:
• To display a message or to run a block of code depending on the character
input, we use switch statement.
• The input to this switch block is “Grade” obtained by a student in this
program.
• Once the user enters his grade, the switch statement compares this input with
all cases defined in it. If there is a match, then the corresponding statements
defined in that case are executed.
• If the input does not match with any of the conditions defined in all cases of
switch, then the default case is executed. The statements written inside
default case are executed.
• All keywords are case sensitive in C, for example switch, case and default. Any
change in the key word will throw us an error.
Program # 18
Aim: To enhance the program 17 to display student marks, average, grade and also a message to
the console.
/************************************************************************************************************************
File Name: program18.c
Author: vrsyrn
Date & Time : 16/11/2023; 12:30 AM
Description: a program to display student marks, average, grade and also a message to console
************************************************************************************************************************/

Program 18
Output:
Note 18:
• Integrating the programs 15, 16 and 17 to display the student marks, average,
grade and a message.
• The syntax and the order of integration is to be properly developed.
Program # 19
Aim: To enhance the program 18 to display Student details, Screening test performance, Grade
evaluation and Message to the console.
/************************************************************************************************************************
File Name: program18.c
Author: vrsyrn
Date & Time : 16/11/2023; 12:30 AM
Description: a program to display Student details, Screening test performance, Grade evaluation
and Message
************************************************************************************************************************/

Program 19
Output:
Note 19:
• Integrating all the previous programs to display Student details, Screening test
performance, Grade evaluation and Message to the console.
• The syntax and the order of integration is to be properly developed.
Assignments
32. Write a C program that accepts three numbers and find the largest of three
using if statement.

33. Write a C program that reads an integer between 1 and 7 and print the day of
the week in English using switch statement.

34. Write a C program that find the greatest of two numbers using if-else
statements.

35. Write a C program to print whether the given number is positive or negative
using if-else statement.

36. Write a C program to check the equivalence of two numbers entered by the
user using if-else statement.
Assignments
37. Write a C program to check whether the given character is a lower case letter
or not using if-else statement.

38. Write a C program to convert the lower case letter to upper case letter.

39. Write a C program to check whether the entered input is an alphabet or not
using if-else statement.

40. Write a C program to check whether a entered number is even or odd using if-
else statement.

41. Write a C program to determine whether two numbers in a pair are in


ascending or descending order using if-else statement.
Assignments
42. Write a C program that reads two numbers and divides one by the other, specify
"Division not possible" if that is not possible using if-else statement.

43. Write a C program that reads in two numbers and determine whether the first
number is a multiple of the second number using if-else statement.

44. Write a C program that will examine two inputted integers and return true if
either of them is 50 or if their sum is 50 using if-else statement.

45. Write a C program to check whether the person is a senior citizen or not using
if-else statement.

46. Write a C program to return True if the entered positive number by the user is a
multiple of three or five or else return False using if-else statement.
Assignments
47. Write a C program to return True if any one of the two entered integers falls
within the range of 100 to 200 or else return False using if-else statement.

48. Write a C program to check whether it is possible to add two integers to get the
third integer from three entered integers using if-else statement.

49. Write a C program to verify if a character user entered is a vowel or a


consonant using if-else statement.

50.Write a C program to determine if the character entered is an alphabetic or


numeric character using if-else-if statements.
51.Write a C program to check whether number is EVEN or ODD using switch
statement.
52. Write a C program to print number between 1 to 10 in character format using
switch-case.
Loop Control Statements
Loops in programming are used to repeat a block of code until the specified
condition is met. It is known as iteration also.
A loop statement allows programmers to execute a statement or group of
statements multiple times without repetition of code.
The looping simplifies the complex problems into the easy ones. It enables us to
alter the flow of the program so that instead of writing the same code again and
again, we can repeat the same code for a finite number of times.
For example, if we need to print the first 10 natural numbers then, instead of
using the printf statement 10 times, we can print inside a loop which runs up to
10 iterations.
There are mainly two types of loops in C Programming:
• Entry Controlled loops
• Exit Controlled loops
Entry Controlled loops: In Entry
controlled loops the test condition is
checked before entering the main
body of the loop.
Eg: for Loop and while Loop

Exit Controlled loops: In Exit


controlled loops the test condition is
evaluated at the end of the loop
body. The loop body will execute at
least once, irrespective of whether
the condition is true or false.
Eg: do-while Loop
for Loop:
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");
}
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.
Example (for loop) :

#include <stdio.h>
int main()
{
int i = 0;
for (i = 1; i <= 10; i++)
{
printf( "Hello World\
n");
}
return 0;
}
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:
while (testExpression)
{
// the body of the loop
}
The while loop evaluates the testExpression inside the parentheses(). If
testExpression is true, statements inside the body of while loop are executed.
Then, testExpression is evaluated again. The process goes on until testExpression
is evaluated to false. If testExpression is false, the loop terminates (ends).
Flow diagram (while loop) Example (while loop)

#include <stdio.h>
int main()
{
int i = 1;
while(i <= 10)
{
printf( "Hello World\n");
i++;
}
return 0;
}
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:
do
{
// body of do-while loop
update_expression;
} while (test_expression);
Flow diagram (do-while loop) Example (do-while loop)

#include <stdio.h>
int main()
{
int i = 2;
do
{
printf( "Hello World\n");

i++;
} while (i < 1);
return 0;
}
Nested Loops in C:
C supports nesting of loops. Nesting of loops is the feature in C that allows the
looping of statements inside another loop.
A nested loop means a loop statement inside another loop statement. That is
why nested loops are also called “loop inside loops”.
Any number of loops can be defined inside another loop, i.e., there is no
restriction for defining any number of loops.
The nesting level can be defined at n times. You can define any type of loop
inside another loop; for example, you can define 'while' loop inside a 'for' loop.
The nesting of loops can be done with all three loops like Nested for loop,
Nested while loop and Nested do-while loop.
Nested for Loop:

Syntax:
for ( initialization; condition; increment )
{
for ( initialization; condition; increment )
{

// statement of inside for loop


}
// statement of outer for loop
}
Nested while Loop:

Syntax:
while (condition)
{
while (condition)
{
// statement of inside while loop
}
// statement of outer while loop
}
Nested do-while Loop:

Syntax:
do
{
do
{
// statement of inside loop
} while(condition);
// statement of outer loop
} while(condition);

Note: There is no rule that a loop must be nested inside its


own type. In fact, there can be any type of loop nested inside
any type and to any level.
break statement in C:
The break is a keyword in C which is used to bring the program control out of the
loop. The break statement is used inside loops or switch statement. The break
statement breaks the loop one by one, i.e., in the case of nested loops, it breaks
the inner loop first and then proceeds to outer loops.
#include <stdio.h>
int main()
{
int i;
for (i = 0; i < 10; i++)
{
if (i == 4)
break;
printf("%d\n", i);
}
}
continue statement in C:
The continue statement breaks one iteration (in the loop), if a specified
condition occurs, and continues with the next iteration in the loop.

#include <stdio.h>
int main()
{
int i;
for (i = 0; i < 10; i++)
{
if (i == 4)
continue;
printf("%d\n", i);
}
}
goto statement in C:
The goto statement is known as jump statement in C.
As the name suggests, goto is used to transfer the program control to a
predefined label.
The goto statment can be used to repeat some part of the code for a particular
condition. It can also be used to break the multiple loops which can't be done by
using a single break statement.
However, using goto is avoided these days since it makes the program less
readable and complicated. Use of goto statement is highly discouraged in any
programming language because it makes difficult to trace the control flow of a
program, making the program hard to understand and hard to modify.
#include <stdio.h>
int main()
{
printf(" Statement 1\n\n");
goto Label3;
printf(" Statement 2\n\n");
Label3: printf(" Statement 3\n\n");
printf(" Statement 4\n\n");
return 0;
}
Assignments
53. Write a C program that prints all Even numbers between 1 and 25 using for
loop.
54. Write a C program that prints all Odd numbers between 1 and 25 using for loop.

55. Write a C program that prints the first 10 numbers starting from one together
with their squares and cubes using for loop.

56. Write a C program to print the multiplication table of a number entered by the
user using for loop.

57. Write a C program to print the characters from a to z and A to Z using for loop.

58. Write a C program to find factorial of a number using for loop.

59. Write a C program to find sum of even numbers between 1 to n using for loop.
Assignments
60. Write a C program to find sum of odd numbers between 1 to n using for loop.

61. Write a C program to find sum of digits of a given number using while loop.

62. Write a C program to find power of a number using for loop using for loop.

63. Write a C program to find all factors of a number using for loop.

64. Write a C program to print ODD numbers from 1 to N using while loop.

65. Write a C program to print EVEN numbers from 1 to N using while loop.

66. Write a C program to print your name N times using do-while loop.

67. Write a C program to print numbers from 1 to 4 within a for loop of printing
numbers from 1 to 10 using Break statement.
Assignments
68. Write a C program to print numbers from 1 to 10 using a for loop except
printing number 4 using Continue statement.

69. Write a C program to take input from the user until he/she enters zero.

70. Write a C program to print sum of only ODD numbers between 0 and 10 using
Continue statement.

71. Write a C program that prints whether the entered number is a positive or
negative integer using Goto statement.

72. Write a C program that prints Table from 1 to 10 for any entered number using
Goto statement.

You might also like