Siva CTSD Lab Manual

Download as pdf or txt
Download as pdf or txt
You are on page 1of 46

FACULTY OF ENGINEERING & TECHNOLOGY

BACHELOR OF TECHNOLOGY

Computational Thinking for Structure Design -1


(303105104)
1st SEMESTER
COMPUTER SCIENCE & ENGINEERING DEPARTMENT

Laboratory Manual

COMPUTATIONAL THINKING FOR STRUCTURE DESIGN -1 PRACTICAL BOOK


Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1

COMPUTER SCIENCE AND ENGINEERING DEPARTMENT

PREFACE

It gives us immense pleasure to present the first edition of Computational Thinking for
Structure Design -1 for the B.Tech. 1st year students for PARUL UNIVERSITY.

The Fundamental of Programming theory and laboratory courses at PARUL UNIVERSITY,


WAGHODIA, VADODARA are designed in such a way that students develop the basic
understanding of the subject in the theory classes and then try their hands on the computer learnt
during the theoretical sessions.
This book is emphatically not focused on “the syntax of C”. Understanding the fundamental
ideals, principals, and techniques is the essence of a good programmer. Only well-designed code has
a chance of becoming part of a correct, reliable, and maintainable system. Also, “the fundamentals”
are what last: they will still be essential after today’s language and tools have evolved or been
replaced.
We acknowledge the authors and publishers of all the books which we have consulted while
developing this Practical book. Hopefully this Computational Thinking for Structure Design -1 will
serve the purpose for which it has been developed.

Enrollment No: Page No:


Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1

Instructions to students

1. Every student should obtain a copy of laboratory Manual.


2. Dress Code: Students must come to the laboratory wearing.
i. Trousers,
ii. half-sleeve tops and
iii. Leather shoes. Half pants, loosely hanging garments and slippers are not allowed.
3. To avoid injury, the student must take the permission of the laboratory staff before handling any
machine.
4. Students must ensure that their work areas are clean and dry to avoid slipping.
5. Do not eat or drink in the laboratory.
6. Do not remove anything from the computer laboratory without permission.
7. Do not touch, connect or disconnect any plug or cable without your lecturer/laboratory
technician’s permission.
8. All students need to perform the practical/program.

Enrollment No: Page No:


Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1

Faculty of Engineering & Technology (FET)

Parul Institute of Engineering & Technology (PIET)


Department of Computer Science & Engineering

CERTIFICATE

This is to certify that Mr./Ms.


UG No. & Enrolment No. has completedall
the practicals of the subject on his/her own and is submitting the lab manual with proper formatting as per the
given instructions. His/Her work is found satisfactory and hence, he/she has successfully completed the term-
work submission of Computational Thinking for Structured Design - 1 (303105104) for the Term & Academic
Year 2024-25 (Odd Semester).

Date of Submission:

Student’s Signature Subject Faculty’s Signature

HoD’s Signature

Enrollment No: Page No:


Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1

INDEX

Class: 1st Sem Subject: - Computational Thinking for Structured Design-1


A.Y. 2024-2025 Subject Code: 303105104

Practical Assessment Table

Sr. Page No. Marks


Practical Title Sign
No. (10)
From To

1 Practical – 1 (Introduction to C Language)

2 Practical – 2 (Basic C Programs with I/O)

3 Practical – 3 (Branching Statements)

4 Practical – 4 (While & Do-While Statements)

5 Practical – 5 (For Loop Programs)

6 Practical – 6 (Nested For Loop Programs)

7 Practical – 7 (1D & 2D Array Programs)

8 Practical – 8 (String Handling Programs)

9 Practical – 9 (User Defined Functions)

Term Work Submission

CTSD - 1

Enrollment No: Page No:


Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1

Practical 1

Introduction to C Language

The basic structure of a C program is divided into 6 parts which makes it easy to read, modify,
document, and understand in a particular format. C program must follow the below-mentioned
outline in order to successfully compile and execute. Debugging is easier in a well-structured C
program.

Sections of the C Program


There are 6 basic sections responsible for the proper execution of a program. Sections are
mentioned below:

a. Documentation
b. Preprocessor Section
c. Definition
d. Global Declaration
e. Main() Function
f. Sub Programs

1. Documentation
This section consists of the description of the program, the name of the program, and the
creation date and time of the program. It is specified at the start of the program in the form of
comments. Documentation can be represented as:

// description, name of the program, programmer name, date, time etc.


/*
description, name of the program, programmer name, date, time etc.
*/
Anything written as comments will be treated as documentation of the program and this will not
interfere with the given code. Basically, it gives an overview to the reader of the program.

2. Preprocessor Section
All the header files of the program will be declared in the preprocessor section of the program.
Header files help us to access other’s improved code into our code. A copy of these multiple
files is inserted into our program before the process of compilation.

Example:

Enrollment No: 24UG032315 Page No:


Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1
#include<stdio.h>
#include<math.h>

3. Definition
Preprocessors are the programs that process our source code before the process of compilation.
There are multiple steps which are involved in the writing and execution of the program.
Preprocessor directives start with the ‘#’ symbol. The #define preprocessor is used to create a
constant throughout the program. Whenever this name is encountered by the compiler, it is
replaced by the actual piece of defined code.
Example:

#define long long ll

4. Global Declaration
The global declaration section contains global variables, function declaration, and static
variables. Variables and functions which are declared in this scope can be used anywhere in the
program.

Example:

int num = 18;

5. Main() Function
Every C program must have a main function. The main() function of the program is written in
this section. Operations like declaration and execution are performed inside the curly braces of
the main program. The return type of the main() function can be int as well as void too. void()
main tells the compiler that the program will not return any value. The int main() tells the
compiler that the program will return an integer value.

Example:

void main()
or
int main()

6. Sub Programs
User-defined functions are called in this section of the program. The control of the program is
shifted to the called function whenever they are called from the main or outside the main()
function. These are specified as per the requirements of the programmer.

Example:

int sum(int x, int y)

Enrollment No: 24UG032315 Page No:


Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1
{
return x+y;
}

List of Format Specifiers in C


The below table contains the most commonly used format specifiers in C

Format Specifier Description

%c For char type.

%d For signed integer type.

%e or %E For scientific notation of floats.

%f For float type.

%g or %G For float type with the current precision.

%i Unsigned integer

%ld or %li Long

%lf Double

%Lf Long double

%lu Unsigned int or unsigned long

%lli or %lld Long long

%llu Unsigned long long

%o Octal representation

%p Pointer

%s String

Enrollment No: 24UG032315 Page No:


Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1
Format Specifier Description

%u Unsigned int

%x or %X Hexadecimal representation

%n Prints nothing

%% Prints % character

Escape Sequence List

The table below lists some common escape sequences in C language.

Escape
Sequence Name Description

\a Alarm or Beep It is used to generate a bell sound in the C program.

\b Backspace It is used to move the cursor one place backward.

It is used to move the cursor to the start of the next logical


\f Form Feed
page.

\n New Line It moves the cursor to the start of the next line.

\r Carriage Return It moves the cursor to the start of the current line.

It inserts some whitespace to the left of the cursor and


\t Horizontal Tab
moves the cursor accordingly.

\v Vertical Tab It is used to insert vertical space.

\\ Backlash Use to insert backslash character.

\’ Single Quote It is used to display a single quotation mark.

\” Double Quote It is used to display double quotation marks.

Enrollment No: 24UG032315 Page No:


Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1
Escape
Sequence Name Description

\? Question Mark It is used to display a question mark.

\ooo Octal Number It is used to represent an octal number.

Hexadecimal
\xhh It represents the hexadecimal number.
Number

\0 NULL It represents the NULL character.

Example:
#include <stdio.h>
int main() {
// printf() displays the string inside quotation
printf("Hello, World!");
return 0;
}

OUTPUT:
Hello world

PROGRAMS FOR PRACTICAL-1


PROGRAM 1.1:-
Print your name
Input:-

Enrollment No: 24UG032315 Page No:


Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1

Output:-

PROGRAM 1.2:-
Print full name in 2 lines
Input:-

Output:-

Enrollment No: 24UG032315 Page No:


Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1

PROGRAM 1.3:-
Print your name in the center of the screen

Input:-

Output:-

PROGRAM 1.4:-
Print some patterns using ‘\n &\t’
(Triangle)

Input:-

Enrollment No: 24UG032315 Page No:


Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1

Output:-

PROGRAM 1.5:-
Print some pattern using (‘\n&\t’)
Square

Input:-

Enrollment No: 24UG032315 Page No:


Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1

Output:-

Enrollment No: 24UG032315 Page No:


Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1
Practical 2

Basic C Programs with I/O

C language has standard libraries that allow input and output in a program. The stdio.h or
standard input output library in C that has methods for input and output.

scanf()
The scanf() method, in C, reads the value from the console as per the type specified and store
it in the given address.

Syntax:

scanf("%X", &variableOfXType);
where %X is the format specifier in C. It is a way to tell the compiler what type of data is in a
variable and & is the address operator in C, which tells the compiler to change the real value of
variableOfXType, stored at this address in the memory.

Input and output operations in C are essential for interacting with users and files. To master I/O
operations and integrate them into larger programs and data structures, the C Programming
Course Online with Data Structures covers these fundamentals with practical applications.

printf()
The printf() method, in C, prints the value passed as the parameter to it, on the console screen.

Syntax:

printf("%X", variableOfXType);
where %X is the format specifier in C. It is a way to tell the compiler what type of data is in a
variable and variableOfXType is the variable to be printed.

How to take input and output of basic types in C?


The basic type in C includes types like int, float, char, etc. Inorder to input or output the specific
type, the X in the above syntax is changed with the specific format specifier of that type. The
Syntax for input and output for these are:

Integer:
Input: scanf("%d", &intVariable);
Output: printf("%d", intVariable);
Float:
Input: scanf("%f", &floatVariable);
Enrollment No: 24UG032315 Page No:
Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1
Output: printf("%f", floatVariable);
Character:
Input: scanf("%c", &charVariable);
Output: printf("%c", charVariable);
Please refer Format specifiers in C for more examples.

// C program to show input and output

#include <stdio.h>

int main()
{

// Declare the variables


int num;
char ch;
float f;

// --- Integer ---

// Input the integer


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

// Output the integer


printf("\nEntered integer is: %d", num);

// --- Float ---

//For input Clearing buffer


while((getchar()) != '\n');

// Input the float


printf("\n\nEnter the float: ");
scanf("%f", &f);

// Output the float


printf("\nEntered float is: %f", f);

Enrollment No: 24UG032315 Page No:


Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1
// --- Character ---

// Input the Character


printf("\n\nEnter the Character: ");
scanf("%c", &ch);

// Output the Character


printf("\nEntered character is: %c", ch);

return 0;
}

Output
Enter the integer: 10
Entered integer is: 10

Enter the float: 2.5


Entered float is: 2.500000

Enter the Character: A


Entered Character is: A
How to take input and output of advanced type in C?
The advanced type in C includes type like String. In order to input or output the string type, the X
in the above syntax is changed with the %s format specifier. The Syntax for input and output for
String is:

Input: scanf("%s", stringVariable);


Output: printf("%s", stringVariable);
Example:

// C program to show input and output

#include <stdio.h>

int main()
{

// Declare string variable


// as character array
Enrollment No: 24UG032315 Page No:
Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1
char str[50];

// --- String ---


// To read a word

// Input the Word


printf("Enter the Word: ");
scanf("%s\n", str);

// Output the Word


printf("\nEntered Word is: %s", str);

// --- String ---


// To read a Sentence

// Input the Sentence


printf("\n\nEnter the Sentence: ");
scanf("%[^\n]s", str);

// Output the String


printf("\nEntered Sentence is: %s", str);

return 0;
}

Output
Enter the Word: GeeksForGeeks
Entered Word is: GeeksForGeeks

Enter the Sentence: Geeks For Geeks


Entered Sentence is: Geeks For Geeks

Enrollment No: 24UG032315 Page No:


Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1

PROGRAMS FOR PRACTICAL-2


PROGRAM 2.1:-
Adding two numbers

Input:-

Output:-

PROGRAM 2.2:-
Finding average of 3 numbers
Input:-

Enrollment No: 24UG032315 Page No:


Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1

Output:-

Enrollment No: 24UG032315 Page No:


Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1
PROGRAM 2.3.1:-
Finding area of triangle
Input:-

Output:-

Enrollment No: 24UG032315 Page No:


Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1
PROGRAM 2.3.2:-
Finding area of circle

Input:-

Output:-

Enrollment No: 24UG032315 Page No:


Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1
PROGRAM 2.4:-

Swapping two numbers using third variable


Input:-

Output:-

Enrollment No: 24UG032315 Page No:


Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1

PROGRAM 2.5:-
Swapping two numbers without using third variable

Input:-

Output:-

Enrollment No: 24UG032315 Page No:


Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1
Practical 3

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.[1] Common branching statements include break,
continue, return, and goto.

Discussion
Branching statements allow the flow of execution to jump to a different part of the program.
The common branching statements used within other control structures include: break,
continue, return, and goto. The goto is rarely used in modular structured
programming. Additionally, we will add to our list of branching items a pre-defined function
commonly used in programming languages of: exit.

Examples 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;

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

Enrollment No: 24UG032315 Page No:


Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-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 DoSometing
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;
exit

Although exit is technically a pre-defined function, it is covered here because of its


common usage in programming. A good example is the opening a file and then testing
to see if the file was actually opened. If not, we have an error that usually indicates that
we want to prematurely stop the execution of the program. The exit function terminates
the running of the program and in the process returns an integer value back to the
operating system. It fits the definition of branching which is to jump to some other
Enrollment No: 24UG032315 Page No:
Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1
Key Terms

branching statements
Allow the flow of execution to jump to a different part of the program.
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.

3.1 Find the maximum of 2 numbers.


#include<stdio.h>
int main() {
int num1, num2;
printf("enter two integers:");
scanf("%d %d", &num1, &num2);
if (num1 > num2){
printf("maximum:%d\n", num1);
if (num2 > num1)
printf("maximum:%d\n", num2);
}
return 0;
}
Output:

3.2 Find the maximum of 3 numbers using nested if.


#include<stdio.h>
int main() {
Enrollment No: 24UG032315 Page No:
Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1
int num1, num2, num3;
printf("enter three integers:");
scanf("%d %d %d", &num1, &num2, &num3);
if (num1 > num2){ if (num1 > num3)
printf("maximum:%d\n", num1);
else
printf("maximum:%d\n", num3);
} else{ if (num2 > num3)
printf("maximum:%d\n", num2);
else
printf("maximum:%d\n", num3);
}
return 0;
}
Outtput:

. 3.3 Find the maximum of 3 numbers using else if else ladder.

#include<stdio.h>
int main() {
int num1, num2, num3;
printf("enter three integers:");
scanf("%d %d %d", &num1, &num2, &num3);
if (num1 > num2){ if (num1 > num3)
Enrollment No: 24UG032315 Page No:
Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1
printf("maximum:%d\n", num1);
else
printf("maximum:%d\n", num3);
} else{ if (num2 > num3) printf("maximum:%d\n", num2);
else
printf("maximum:%d\n", num3);
}
return 0;
}
Output:

3.4 Generate electricity bill based on usage of units.


#include <stdio.h>
int main() {
float units, bill;
printf("Enter the number of electricity units consumed: ");
scanf("%f", &units);
if (units <= 100) { bill = units * 1.0; }
else if (units <= 300) {
bill = (100 * 1.0) + ((units - 100) * 1.5);
} else {
bill = (100 * 1.0) + (200 * 1.5) + ((units - 300) * 2.0);
} bill += 50; bill += bill * 0.05;
printf("Total electricity bill: Rs. %.2f\n", bill);

return 0; }

Enrollment No: 24UG032315 Page No:


Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1
Output:

3.5 Create calculator using switch case.

#include<stdio.h>
int main() {
char operator;
double num1, num2;
printf("enter an operator (+, -, *, /):");
scanf("%c", &operator);
printf("enter two numbers:");
scanf("%lf %lf", &num1, &num2);
switch (operator) {
case '+':
printf("result:%.2lf\n", num1 + num2);
break;
case '-':
printf("result:%.2lf\n", num1 - num2);
break;
case '*':
printf("result:%.2lf\n", num1 * num2);
break;
case '/':
if (num1 != 0)
printf("result:%.2lf\n", num1 / num2);
return 0;
}
}

Output:

Enrollment No: 24UG032315 Page No:


Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1

3.6 Generate student’s result based on percentage.


#include<stdio.h>
int main() {
int marks;
printf("Enter your marks ");
scanf("%d",&marks);
if(marks<50)
{
printf("Grade F");
}
else if(marks>=50 && marks<60)
{
printf("Grade D");
}
else if(marks>=60 && marks<70)
{
printf("Grade C");
}
else if(marks>=70 && marks<80)
{
printf("Grade B");
}
else if(marks>=80 && marks<90)
{
printf("Grade A");
} else
{
printf("Grade A+");
} return 0;
}

Output:
Enrollment No: 24UG032315 Page No:
Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1

3.7 Find area of rectangle, circle and square using switch case.
#include <stdio.h>
#include <math.h>

int main() {
int choice;
float area;
printf("Select the shape to calculate the area:\n");
printf("1. Rectangle\n");
printf("2. Circle\n");
printf("3. Square\n");
printf("Enter your choice (1-3): ");
scanf("%d", &choice);

switch (choice) {
case 1: { float length, width;
printf("Enter the length of the rectangle: ");
scanf("%f", &length);
printf("Enter the width of the rectangle: ");
scanf("%f", &width);
area = length * width;
printf("The area of the rectangle is: %.2f\n", area);
break; }

case 2: {
float radius;
printf("Enter the radius of the circle: ");
scanf("%f", &radius);
area = M_PI * radius * radius;
printf("The area of the circle is: %.2f\n", area);
break; }
case 3: {
float side;
printf("Enter the side length of the square: ");
scanf("%f", &side);
area = side * side;
printf("The area of the square is: %.2f\n", area);
break; }
default:
Enrollment No: 24UG032315 Page No:
Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1
printf("Invalid choice! Please select a valid option.\n");
break;
}

return 0;
}

Output:

Conclusion:

Enrollment No: 24UG032315 Page No:


Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1

Practical 4

While & Do-While Statements.

While and do-while loops are commonly used looping statements in C, C++ and Java
programming languages. Both loops allow repetitive execution of a block of code as
long as the given condition remains true. The key difference between while and do
while loo[ lies in the time when the condition is checked. o In a while loop, the
condition is checked before the loop body executes. So the body may not execute
even once if the condition is false from the beginning. o On the other hand, in a do
while loop the body is guaranteed to execute at least once because the condition is
checked after executing the body. o This ensures the body runs at least once before
checking if the loop needs to be repeated.
o A while loop is an entry controlled loop as it evaluates the condition at the start of
each iteration, before executing the loop body. If the condition is false initially, the
body will not execute even once.
o On the other hand, a do-while loop is an exit controlled loop that first executes the
body and then evaluates the condition at the end of each iteration. This ensures the
body is guaranteed to execute at least once no matter whether the condition is true
or false originally.
o In terms of syntax, a while loop condition does not use a semicolon while do-while
condition is followed by a semicolon.
o Position-wise as well, the condition comes at the beginning for while loop and at the
end for do-while loop, after the body.
o Due to guaranteed execution of the body, do-while is preferred when it is important
for the code block to run at least once irrespective of the condition.
In contrast, while loop is preferred when there is a possibility the code block needs not
run even once based on condition result.
Enrollment No: 24UG032315 Page No:
Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1

What is While Loop?

A while loop is a control flow statement that allows repetitive execution of


code as long as the given condition is true. The condition is evaluated
before executing the loop body.

Syntax of While Loop


while (boolean condition)
{
loop statements…
}

What is Do While Loop?

A do while loop is similar to a while loop with one difference. It checks the
condition at the end of the loop body. This ensures the body executes at
least once regardless of the condition.

In both, the condition determines if the loop repeats. But while checks
first, do-while checks last, ensuring the body runs once no matter what in
do-while.

Syntax of Do While Loop do

{
statements…
}
while (condition);
Enrollment No: 24UG032315 Page No:
Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1

4.1 Print the sum of first 10 numbers.


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

Output:

4.2 Print the sum of odd and even numbers between 51 and 550.
#include <stdio.h>
int main() { int i, sum_even = 0, sum_odd = 0;
for (i = 51; i <= 550; i++) { if (i % 2 == 0) { sum_even += i;
} else { sum_odd += i;
}
}
printf("Sum of even numbers from 51 to 550: %d\n", sum_even);
printf("Sum of odd numbers from 51 to 550: %d\n", sum_odd); return 0;
}

Output:

4.3 Reverse a given number.


#include<stdio.h>
int main() { int num, reversed_num = 0;
printf("enter a number:");
scanf("%d", &num);
while (num != 0) { int remainder = num % 10;
reversed_num = reversed_num * 10 + remainder;
num = num / 10;
Enrollment No: 24UG032315 Page No:
Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1
}
printf("reversed number is:%d\n", reversed_num);
}

Output:

4.4 Check whether given number is palindrome


#include <stdio.h>
int main() {
int n, reversed = 0, remainder, original;
printf("Enter an integer: ");
scanf("%d", &n);
original = n;
while (n != 0) { remainder = n % 10;
reversed = reversed * 10 + remainder;
n /= 10;
}
if (original == reversed)
printf("%d is a palindrome.", original); else return 0;
}
Output:

4.5 Check whether given number is Armstrong.


#include <stdio.h>
int main()
{ int num, originalNum, remainder, result = 0;
printf("Enter a three-digit integer: ");
scanf("%d", &num);
originalNum = num;
while (originalNum != 0) { remainder = originalNum % 10;
result += remainder * remainder * remainder;
originalNum /= 10;
}
if (result == num)
printf("%d is an Armstrong number.", num);
else
Enrollment No: 24UG032315 Page No:
Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1
printf("%d is not an Armstrong number.", num);

return 0;
}

Output:

Conclusion:

Practical 5
For loop programs

In C programming, loops are responsible for performing repetitive tasks using a short code block that executes until the
condition
holds true. In this article, we will learn about for loop in C.

for Loop in C
The for loop in C Language provides a functionality/feature to repeat a set of statements a defined number of times. The for
loop is in
itself a form of an entry-controlled loop.

Unlike the while loop and do…while loop, the for loop contains the initialization, condition, and updating statements as part of
its
syntax. It is mainly used to traverse arrays, vectors, and other data structures.

Syntax of for Loop


f or(initialization; check/test expression; updation)
{
// body consisting of multiple statements
}
Structure of for Loop
The for loop follows a very structured approach where it begins with initializing a condition then checks the condition and in the
end
executes conditional statements followed by an updation of values.

Initialization: This step initializes a loop control variable with an initial value that helps to progress the loop or helps in checking
the
condition. It acts as the index value when iterating an array or string.

Check/Test Condition: This step of the for loop defines the condition that determines whether the loop should continue
executing or
not. The condition is checked before each iteration and if it is true then the iteration of the loop continues otherwise the loop is
terminated.

Body: It is the set of statements i.e. variables, functions, etc that is executed repeatedly till the condition is true. It is enclosed
within
curly braces { }.

Enrollment No: 24UG032315 Page No:


Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1

Updation: This specifies how the loop control variable should be updated after each iteration of the loop. Generally, it is the
incrementation (variable++) or decrementation (variable–) of the loop control variable.
How for Loop Works?
The working of for loop is mentioned below:

Step 1: Initialization is the basic step of for loop this step occurs only once during the start of the loop. During Initialization, variables are
declared, or already existing variables are assigned some value.
Step 2: During the Second Step condition statements are checked and only if the condition is the satisfied loop we can further process
otherwise loop is broken.
Step 3: All the statements inside the loop are executed.
Step 4: Updating the values of variables has been done as defined in the loop.
Continue to Step 2 till the loop breaks.
Flowchart of for Loop
c for loop flowchart
C for Loop Flow Diagram

Example of for loop


The following program illustrates how to use for loop in C:

// C program to demonstrate for loop


#include <stdio.h>
int main()
{
int gfg = 0;

// 'gfg' <= 5 is the check/test expression


// The loop will function if and only if 'gfg' is less
// than 5
//'gfg++' will increments it's value by this so that the
// loop can iterate for further evaluation

// conditional statement
for (gfg = 1; gfg <= 5; gfg++)
{
// statement will be printed
printf("GeeksforGeeks\n");
}

// Return statement to tell that everything executed


// safely
return 0;
}
Output
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
Nested for loop in C
C provides the feature of a nested loop where we can place a loop inside another loop.

Syntax
for( .. ; .. ; .. ){
for( .. ; .. ; .. ){
....
}
Enrollment No: 24UG032315 Page No:
Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1
}
To know more about nested for loop refer to Nested for loop in C.
Special Conditions
1. for loop without curly braces
You already know about for loop and its syntax, when we declare a for loop without curly braces, the loop executes only one statement
which is written just after it, and the statement can not be declarative.

Example

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

// for loop without curly braces


for (i = 1; i <= 10; i++)
printf("%d ", i);
printf("\nThis statement executes after for loop end!!!!"); // Statement print only once

return 0;
}
Output
1 2 3 4 5 6 7 8 9 10
This statement executes after for loop end!!!!
2. Infinite for Loop/NULL Parameter Loop
This is also a kind of for loop where the input parameters are not available or do not exist by virtue of which the loop iterates/runs
endlessly.

Example

// C program to demonstrate infinite Loop


#include <stdio.h>

int main()
{
int gfg = 0;
for (;;) // condition 1,2 and 3 are not entered
{
printf("GeeksforGeeks to Infinite");
}
// Return statement to tell that everything executed
// safely
return 0;
}
Output:

GeeksforGeeks to InfiniteGeeksforGeeks to InfiniteGeeksforGeeks to InfiniteGeeksforGeeks to InfiniteGeeksforGeeks to Infinite.....


Advantages of for Loop
There are certain advantages of using for loops in C as mentioned below:

Provides code reusability


Code size decreases
Traversing in data structures like array and string becomes easy.
Disadvantages of for Loop
Despite so many advantages of for loops it even has certain disadvantages:

Can’t skip any element while traversing


Enrollment No: 24UG032315 Page No:
Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1
Only a single condition is followed
Conclusion
In this article, the points we learned about for loops are mentioned below:

It is an Entry-Controlled Loop
It can iterate from an adequate number to an infinite number according to the situation.
It requires 3 conditions parameters i.e. check expression, conditional statement, and urinary operators for updation.
Its workflow is an initialization, check/test, and then updation.
FAQs on for loops in C
1. What is a loop?
Answer:

The repetition of statements multiple times in a particular order is defined as a loop.

PROGRAMS FOR PRACTICAL-5


PROGRAM 5.1:-

Generate fibbonacci series upto n=5


Input:-

Output:-
Enrollment No: 24UG032315 Page No:
Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1

PROGRAM 5.2:-
Generate fibbonacci series upto N numbers
Input:-

Enrollment No: 24UG032315 Page No:


Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1
Output:-

PROGRAM 5.3:-
Generate a multiplication table for any given number

Input:-

Output:-

Enrollment No: 24UG032315 Page No:


Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1

PROGRAM 5.4:-

Generate result sheet for 5 students using for loop

Input:-

Enrollment No: 24UG032315 Page No:


Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1

Output:-

Enrollment No: 24UG032315 Page No:


Faculty of Engineering & Technology
303105104 - Computational Thinking for Structured Design-1

Enrollment No: 24UG032315 Page No:

You might also like