ES101 CP Lab Manual

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

Laboratory Manual

for
Computer Programming (ES101)
Bachelor of Technology
2024 – 2025 (1st Semester)
(Common to All Branches)

Instructor In-charge : Dr. Santosh Kumar Sahoo


Instructors : Mr. K Brahmanaidu
Dr. Dilip Kumar Murala
Dr. Srinivasa Rao D

Department of Computer Science and Engineering


Department of Artificial Intelligence and Data Science
Faculty of Science and Technology (IcfaiTech)

Donthanapally, Shankarapalli Road, Hyderabad - 501203, Telangana, India.


General Instructions to the Students
 Before entering the Computer Laboratory, the student must carry the following things
(MANDATORY)
1. Identity card issued by the University
2. Class notes
3. Lab observation book and Rough Book
 They must sign in the register provided when attending the lab session without fail
 Come to the laboratory in time. Those who are late more than 10 minutes, will not be
allowed to attend the lab
 Maintain 75% attendance otherwise will not be allowed for the Lab Exams
 All students must follow the prescribed Dress Code and Shoes while in the laboratory
 Foods, drinks are NOT allowed
 All bags must be kept in the designated place
 Don’t use pen drives, mobile phones, internet and any other tools in the desktop computer
without permission of lab faculty
 Don’t remove or disconnect cables or hardware parts and don’t personalize the computer
setting
 Don’t run programs that will continue to execute after left
 Don’t download or install any programs, games or music on computer in Lab
 Shut down the computer and arrange chairs properly while leaving the lab

Introduction About Lab Experiments


 Read the Laboratory Manual carefully before coming to the laboratory and be sure about
what you are supposed to do.
 Listen to the Instructor while demonstrating the experiments. Write the programs in the
computer when the experiments are assigned and then show and explain with output to
the instructors for evaluation.
 For each program you should add comments (i.e. text between /* ... */ delimiters) above
each function in the code, including the main function and where necessary in the
program.
 Provide proper indentation/margin for easy/better understanding of the program
 The program should be interactive, general and properly documented with real Input/
Output data

FST, IFHE, Hyderabad


2
 It is your responsibility to create a separate directory to store all the programs, so that you
can access easily
 One Rough record and one Fair record are needed to record the experiments conducted in
the laboratory. Rough records are needed to be certified immediately on completion of
the experiment. Fair records are due at the beginning of the next lab period. Fair records
must be submitted as neat, legible, and complete
 The fair record should be a new long exercise book of minimum 100 pages
 In the fair record, the index page should be filled properly by writing the Serial No.,
Corresponding experiment number with experiment name (e.g 2.4 Calculation of total,
average and percentage of marks of five subjects), date on which the experiment was
done and the page number. Please refer to the Appendix-I.
 Put your signature at end page of every day of lab experiments in the record. Keep one
blank page in between two consecutive weeks of experiments to write the week number.
It is recommended to write the experiment names and output/result in black in pen and
solution/program in blue in pen
 The experiment name should be written in the page in capital letters

FST, IFHE, Hyderabad


3
Syllabus
Week No. List of experiments Dates Page
No.
Week-1 Lab-1: 09
1.1 Understanding of Ubuntu WSL Operating system on
(Ubuntu) windows
1.2 Ubuntu Commands: ls with options, cat with options, mkdir, 19 - 23
pwd, cd, rm, cp and mv command August
Lab-2: 2024* 18
1.3 Nano editor, Creating a file, Saving the file, Exit the Editor,
Creating your resume file and modifying it by adding some new
achievements, Creating a C-Program File, Compiling using gcc
& Getting Output using ./a.out
Week-2 Lab-1: 20
2.1 Write a C program to display "Welcome to IFHE" on the
(Data screen.
Types) 2.2 Write a C program to display Your Name, Address and City 26 - 30
in different lines. August
Lab-2: 2024* 22
2.3 Write a C program to find the area of a circle. (Hints: Area=
PI * r2)
2.4 Write a C program to enter marks of five subjects and
calculate total, average and percentage of marks.
2.5 Write a C program to convert days into years, weeks and
days.
Week-3 Lab-1: 27
3.1 Write a C program to convert the temperature in degree
(Operators) Centigrade into Fahrenheit and vice versa. (Formula: C= (F-
32)/1.8) 02 – 06
3.2 You are given total time in seconds. Convert it into Hour: Sept.
Min: Second format. 2024*
Lab-2: 31
3.3 Write a simple program that prints the results of all the
operators available in C (including pre/post increment, bitwise
and/or/not, etc.). Read required operand values from standard
input
3.4 Write a C program to find out whether the character pressed
through the Keyboard is a digit or not (Use conditional operator
only).
3.5 Write a C program to swap variable values of two variables
using following techniques.
a) Using a third variable b) Without using third
variable
1. Lab Evaluation (Viva + Execution) = 01 Marks

FST, IFHE, Hyderabad


4
Week-4 Lab-1: 40
4.1 Write a C program to determine whether input number is Odd
(if or Even. Display appropriate message. (use if else statement) 09 – 13
statements) 4.2 Write a C program to find the maximum of given three Sept.
numbers. (using if statement and nested if statement separately) 2024*
Lab-2: 47
4.3 Write a program to read marks from keyboard and your
program should display equivalent grade according to
following table (if else ladder)
Marks Grade
100 – 80 Distinction
79 – 60 First Class
59 – 40 Second Class
< 40 Fail
4.4 Write a C program to input month number and print total
number of days in month using switch...case
4.5 Write a C program for designing a calculator using menu
driven Program
2. Lab Evaluation (Viva + Execution) = 01 Marks
Week-5 Lab-1: 58
5.1 Write a C program to find the sum of first 100 natural
numbers. 23 – 27
(for Loop) 5.2 Write a C program to find factorial of a given number Sept.
5.3 Write a C program to find the sum of odd numbers and even 2024*
numbers between 1 to N (N is a given input number).
Lab-2: 62
5.4 Write a C program to display the first 100 prime numbers.
5.5 Write a C program to construct the following patterns
a) 1 b) *
12 **
123 ***
1234 ****
12345 *****
5.6 Write a C program for calculator to include the following in
the menu
a. To convert decimal to binary.
b. To convert decimal to hexadecimal.
3. Lab Evaluation (Viva + Execution) = 01 Marks
30th Sept.
Mid Lab Exam (Lab Test-1) to
04th Oct.
2024*

FST, IFHE, Hyderabad


5
Week-6 Lab-1: 69
6.1 Write a C program to count the frequency of digits in a given
(while loop) number. (Frequency means number of occurrence of the digit
in the given number) 07 – 11
6.2 Write a C program to find the sum of digits of the accepted Oct.
number. 2024*
Lab-2: 72
6.3 Write a C program to check whether the given number is
palindrome or not.
6.4 Write a C program to input a number and find sum of first
and last digit of the number using for loop (e.g Input 5642,
Output=7)
6.5 Write a C program to print the given number in word form
of digits.
(Ex input : 123, output is ONE TWO THREE )
Week-7 Lab-1: 77
7.1 Write a C program to find sum of two numbers using
(functions) function without argument and with return value
7.2 Write a program to find square of a number using function
with argument and with return value 14 – 18
7.3 Write a C program to find the Fibonacci numbers using a Oct.
recursive function 2024*
Lab-2: 81
7.4 Write a C program to find sum and average of n numbers in
the array.
7.5 Write a C program to find both the largest and smallest
number in a list of integers.
7.6 Write a C program to perform addition of two 3 x 3 matrices
4. Lab Evaluation (Viva + Execution) = 01 Marks
Week-8 Lab-1: 85
8.1 Write a C program to perform multiplication of two 3x3
matrices.
(Array and 8.2 Write a C program to input elements in an array and find the 28 Oct.
Pointer) sum using pointer as well as display array using pointer. –
Lab-2: 01 Nov. 89
8.3 Write a C program to swap values of two variables using 2024*
pointers.
8.4 Write a C program to allocate a block of memory using
Dynamic Memory Allocation functions and perform the
following.
i) accept and store the numbers
ii) find the minimum and maximum of the numbers
iii) find the average of the numbers
5. Lab Evaluation (Viva + Execution) = 01 Marks

FST, IFHE, Hyderabad


6
Week-9 Lab-1: 92
9.1 Write a C program to store and print the roll no., name, age,
address and marks of n students using structure.
(Structure 9.2 Write a C Program to enter the marks of 5 students in 3 04 – 08
and Union) courses Python, DAA, and JAVA (each out of 100) using a Nov.
structure named Marks having elements roll no., name, 2024*
Python_marks, DAA_marks and JAVA_marks and then display
the percentage of each student.
Lab-2: 98
9.3 Write a C program that uses functions and structures to
perform the followings.
i) Reading a complex number
ii) Displaying the complex number
iii) Addition of two complex numbers
iv) Multiplication of two complex numbers
9.4 Write a program to add two distances in inch-feet using
structure. The values of the distances are to be taken from the
user. Display the sum.
9.5 Implement the above program 9.1 using a union.
6. Lab Evaluation (Viva + Execution) = 01 Marks
Week-10 Lab-1: 103
10.1 Write a C program to perform the following operations
without using string handling functions.
(String i) length of a given string ii) string copy
Handling) 10.2 Write a C program to perform the following operations
without using string handling functions
i) compare two strings ii) concatenate two strings 11 – 15
Lab-2: Nov. 109
10.3 Write a C program to perform the following operations 2024*
using string handling functions.
i) length of a given string ii) string copy
iii) compare two strings iv) concatenate two strings
10.4 Write a C program to count the number of lines, characters
and words in a given text of a given string without using string
handling functions.
10.5 Write a C program to convert a given string from lowercase
to uppercase without using string handling functions.
7. Lab Evaluation (Viva + Execution) = 01 Marks

FST, IFHE, Hyderabad


7
Week-11 Lab-1: 113
11.1 Write a C program to read input characters from user and
write it to file. After that read the content of the same file and
(File display on screen. 18 – 22
Handling) 11.2 Write a C program to implement copy command with the Nov.
use of Command line arguments. Like “mycopy source.txt 2024*
destination.txt” should copy content of source file to
destination file.
Lab-2: 116
11.3 Write a C program to write integer numbers to a file. Read
them back and find the average of all numbers.
11.4 Write a program to copy one file to another. While doing
so replace all lowercase characters with their equivalent
uppercase characters.
11.5 Write a C program to merge two files into a third file.

End Lab Exam (Lab Test-2) 25 – 29


Nov. 2024*

Laboratory Evaluation
Component Duration Weightage Date(s) Syllabus Remarks
Mid Lab Exam (Lab 1 Hour 10% 30th Sept. - 04th Lab Week 1 – 10 Marks
Test-1) Oct. 2024* Week 5
End Lab Exam (Lab 1 Hour 10% 25th – 29nd Nov. Lab Week 6 – 10 Marks
Test-2) 2024* Week 11
*Tentative (subject to change as per requirements)
 Every Week has two laboratory classes i.e lab-1 and lab-2. The experiments are
numbered with 1.1, 1.2 and so on etc where the first digit is the week number and second
digit is the assignment number.
 In the 1st lab (Lab-1) of the week, viva voce will be taken. There will be maximum 4
questions related to the sessions conducted in the both theory and lab classes. The student
will execute at least two experiments in this lab. In the 2nd lab (Lab-2) the students will
complete execution of all remaining experiments. The maximum marks for viva voce and
program completion for each lab session is 01 (One).
 There will be two Lab Evaluation Components each of 10 (3+5+2) marks with the
following divisions:
1. Viva voce (Continuous during any 3 lab sessions before Mid Lab and End Lab
Exam separately) – 3 Marks
2. Programming Test in Mid Lab and End Lab Exam separately – 5 Marks
3. Observation Copy - 2 Marks

FST, IFHE, Hyderabad


8
Week-1 Lab-1

1.1 Understanding of Ubuntu WSL Operating system on windows


1.2 Ubuntu Commands: ls with options, cat with options, mkdir, pwd, cd, rm, cp and mv
command

1.1 Understanding of Ubuntu WSL Operating system on windows


Solution:
What is Windows Subsystem for Linux (WSL)?
 Windows Subsystem for Linux (WSL) is a compatibility layer developed by Microsoft
for Windows Computers to run Linux applications, utilities, and commands in the
computer using a Command prompt or terminal.
 This eliminates the need for a Dual boot computer or Virtual Machine setup and saves
computing resources. To use WSL, we must use Windows 10 and higher versions.
 The supported Linux distributions are Ubuntu, Arch, Fedora, Kali, and others.

Features of Windows Subsystem for Linux (WSL)


1. Linux binary execution:
 WSL allows users to run native Linux binaries on a Windows machine directly.
 There is no need for Virtual machines or emulators.
 This enables access to the large ecosystem of Linux applications, tools, and utilities
while using a Windows Operating system.
2. Linux Bash Shell:
 WSL provides a Bash Shell in the Windows Terminal layout and Linux command
line tools.
 Users can use the same Linux commands to interact with the Linux environment
using the terminal.
 The utilities provided includes, file manager, text processor, package manager, and
more.
3. Linux File System:
 Windows Subsystem for Linux creates a file system with its directory in the
Secondary Memory (Hard Drive) and can be managed using the command line utility.
 The Linux file system can be managed by both Windows and Linux. Users can
perform Create, Read, Update, Delete operations on the file system.
4. Support for Multiple Linux Distributions:
 WSL supports multiple Linux Distributions to use in windows machine.
 The supported distributions are Ubuntu, Arch, OpenSUSE, Debian, Kali, and more.
 Users can choose the preferred distribution form Microsoft store and install in the
windows environment to create a Linux system within.

FST, IFHE, Hyderabad


9
Steps to Install and Setup Windows Subsystem for Linux
Step 1: Check System Requirements
 Before we move ahead with installing WSL, we need to make sure that our computer
supports WSL. The recommended configuration is, x64 bit processor
 Windows 10 version 2004 (Build 19041 and higher) or Windows 11
 To check it, click on Start and search for “System information” and check for OS
name, Version and System Type.

Fig-1: check System Requirements


Step 2: Enable WSL
 Once the requirements are matched, search for Windows Features and a box will
open, find out Virtual Machine Platform and Windows Subsystem for
Linux and tick it to enable.

Fig-2: Enable WSL


 Click on OK and Restart the computer.

FST, IFHE, Hyderabad


10
Step 3: Install WSL
 Open PowerShell or Windows Command Prompt in administrative mode by
clicking Run as administrator and execute the following command.
wsl --install
Output:

Fig-3: Install WSL


 Update wsl [if required] using the following
wsl --update
Output:

Fig-4: Update WSL

FST, IFHE, Hyderabad


11
 As you can see it has started installing the necessary features and enabling them for
use. Furthermore, you can see that It’s installing Ubuntu as the default Linux/Ubuntu
distro for WSL.
Step 4: Choose Linux Distribution
 Once WSL is installed, it’s the time to choose the suitable Ubuntu distro for you to
use. Open Microsoft Store and search for ubuntu. You will get all the available
Ubuntu operating systems. Choose the one that suits your requirement and click on
Install. [e.g Ubuntu 24.04 LTS is chosen here]

Fig-5: Choose Linux Distribution


Step 5: Set up WSL
 Once installed, you will get the icon for the Ubuntu as an application. Click on the
application icon and your Ubuntu Machine will start in form of a Terminal.
Step 6: Set up Username and Password
 Set up the Username and Password for the instance and you are good to go. Now
you can execute all your Linux commands here in the terminal itself.

Fig-6: Set up username and password

FST, IFHE, Hyderabad


12
Fig-7: Set UP WSL
 Now the Ubuntu is ready to use by use.
Step 7: Installation of gcc Compiler
 You can install gcc compiler for compilation of C programs using the following
command
sudo apt install gcc

Fig-8: Set UP gcc Compiler

FST, IFHE, Hyderabad


13
Fig-9: Success of Set UP gcc Compiler

FST, IFHE, Hyderabad


14
1.2. Ubuntu Commands: ls with options, cat with options, mkdir, pwd, cd, rm,
cp and mv command
Solution:
Ubuntu:
 Ubuntu is one of the most popular distributions of Linux, known for its user-friendly
interface and robust features. Whether you’re a beginner or an experienced user,
understanding basic Ubuntu commands is essential for navigating and managing your
system efficiently.
 Some of the basic commands are as follows:
1. ls Command with options
 ls is a Linux shell command that lists directory contents of files and directories.
 It provides valuable information about files, directories, and their attributes.
Syntax of `ls` command in Linux
ls [option] [file/directory]
o ‘ls’ will display the contents of the current directory. By default, ‘ls’ lists files and
directories in alphabetical order.
Commonly Used Options in `ls` command in Linux
Options Description

known as a long format that displays detailed information about files and
-l directories.

-a Represent all files Include hidden files and directories in the listing.

Sort files and directories by their last modification time, displaying the most
-t recently modified ones first.

-S Sort files and directories by their sizes, listing the largest ones first.

-d List directories themselves, rather than their contents.

2. cat command with options


 it’s a versatile companion for various file-related operations, allowing users to view,
concatenate, create, copy, merge, and manipulate file contents.
Basic Syntax of `cat` Command
cat [OPTION] [FileName]
Here,
[OPTION]: represents various command-line options
[FileName]: the name of the file(s) to be processed. Let’s explore some of the common
uses of ‘cat’ along with examples.

FST, IFHE, Hyderabad


15
a. cat command to create a new file
Syntax:
cat > [FileName]
Example:
cat > icfai.txt
This is my first file in Ubuntu
I am a student of IFHE
I live in Hyderabad.
^+d
o Type the command "cat >ifhe.txt" and press 'enter'. You will be directed to the
next line. Type the above three lines and then save your file, go to the next line,
press 'ctrl+d' and your file will be saved.

b. How to View the Content of a Single File


Syntax:
cat FileName

Example: If our FileName = icfai.txt


cat icfai.txt
3. mkdir command
 The mkdir stands for 'make directory'. With the help of mkdir command, we can create a
new directory wherever we want in our computer.
Syntax:
mkdir <dirname>
Example:
mkdir cprogram
 Now we can see the directory is created or not by using ls command
ls
4. pwd command
 pwd stands for Print Working Directory. It writes the complete path name of the working
directory to standard output
Syntax:
pwd
Example:
pwd
Output:
/home/lab211
5. cd command
 cd command is used to change the current working directory ( i.e., in which the current
user is working). The “cd” stands for ‘change directory.’
Syntax:
cd <dirname>

FST, IFHE, Hyderabad


16
Example:
cd cprogram
 Now we can see your present directory
pwd
Output:
/home/lab211/cprogram
6. rm command
 The rm means remove. This command is used to remove a file.
Syntax:
rm FileName
Example:
rm icfai.txt
Result: The icfai.txt file will be deleted and can be checked using ls
7. cp command
 cp means copy. cp command is used to copy a file or a directory
Syntax:
cp <existing FileName> <new FileName>
Example:
cp icfai.txt fst.txt
Result: fst.txt will be created as a duplicate file of icfai.txt
8. mv command
 mv command is used to move existing file or directory from one location to another.
 It is also used to rename a file or directory.
Syntax:
mv [options] [Source-File] [Destination-File]
Example:
mv fst.txt myfst.txt
Result: The fst.txt file will be renamed as myfst.txt

FST, IFHE, Hyderabad


17
Week-1 Lab-2

1.3 Nano editor, Creating a file, Saving the file, Exit the Editor, Creating your resume file and
modifying it by adding some new achievements, Creating a C-Program File, Compiling using
gcc & Getting Output using ./a.out

1.3 Nano editor, Creating a file, Saving the file, Exit the Editor, Creating your
resume file and modifying it by adding some new achievements, Creating a C-
Program File, Compiling using gcc & Getting Output using ./a.out

Solution:

Nano Editor:
 Nano is a command-line text editor that comes pre-installed with most Linux
distributions.
 Nano provides essential editing features, making it ideal for quick edits, creating
configuration files, or writing scripts directly in the terminal.
Create and Open a New File in Nano Editor:
 To Create a new file
Syntax:
nano newFileName
Example:
nano myresume.txt
 Note: After creating a file, type your resume in the editor then save the file
 To save the file (type the following command)
ctrl+o
Then press enter key
 To exit from the editor
ctrl+x
o If there are unsaved changes, Nano will ask if you want to save before exiting.

FST, IFHE, Hyderabad


18
Steps Involved in C-Program Development: -
 To develop the program in C-Language and translate it into machine level language
following steps have to be practiced:
Step-1 : Open a new file with .c extension using nano editor and then save & exit
nano prg1.c
Step-2 : Compile the program using gcc compiler
gcc prg1.c
[ If nothing will come then compile successful otherwise correct the errors and compile again till
successful]
Step-3 Execute the program
 By default, a.out executable file is created from the current compiled file
 To run and get the output type the following command
./a.out

Coding Guidelines Using C-Programming Language: -


 It should be remembered to comment/document the code properly.
 C is a case sensitive language. Most of the program statements are in lower case. All
keywords and library functions are in lower case.
 Always indent the body (bodies) of a statement a uniform amount from the first character
of the statement. An indented code can be read, edited easily.
 All statements must necessarily terminate with a semicolon (;).
 The statements which should be terminated-
 All printf() function, scanf() function, or any other function calls.
 All declarations like variables, constants, function, structures must be
terminated by semicolon.
 All expressions must be terminated by the semicolon (;).
 The statements which should not be terminated-
 Header files include statements.
 Macro definition statements.
 If statements, loop statements, function header with the function
definitions.

FST, IFHE, Hyderabad


19
Week-2 Lab-1
Assignments:

2.1 Write a C program to display "Welcome to IFHE" on the screen.


2.2 Write a C program to display Your Name, Address and City in different lines.

2.1 Write a C program to display "Welcome to IFHE" on the screen.


Solution:

Algorithm
Step-1 : Display "Welcome to IFHE"
Step-2 : Stop

Flowchart

Program File : Prg21.c


#include <stdio.h>
int main() {
// Print the welcome message to the screen
printf("Welcome to IFHE\n");
return 0;
}

Output:

FST, IFHE, Hyderabad


20
2.2 Write a C program to display Your Name, Address and City in different
lines.
Solution:
Algorithm
Step-1 : Display "Name: ICFAI"
Step-2 : Display “Address: Donthanapally”
Step-3 : Display “City: Hyderabad”
Step-4 : Stop

Flowchart:

Program File : Prg22.c


#include <stdio.h>
int main() {
// Print the name, address, and city on separate lines
printf("Name : ICFAI\n");
printf("Address: Donthanapally \n");
printf("City : Hyderabad\n");
return 0;
}

Output:
Name : ICFAI
Address: Donthanapally
City : Hyderabad

[You can give your name and address]

FST, IFHE, Hyderabad


21
Week-2 Lab-2

2.3 Write a C program to find the area of a circle. (Hints: Area= PI * r2)
2.4 Write a C program to enter marks of five subjects and calculate total, average and percentage
of marks.
2.5 Write a C program to convert days into years, weeks and days.

2.3 Write a C program to find the area of a circle. (Hints : Area= PI * r2)
Solution:

Algorithm
Start-1 : Declare variables: radius and area
Step-2 : Initialize PI=3.14159
Step-3 : Read radius
Step-4 : Compute area = PI * radius * radius
Step-5 : Display area
Step-6 : Stop

FST, IFHE, Hyderabad


22
Flowchart

Program File : Prg23.c


#include <stdio.h>
#define PI 3.14 // PI is a macro
int main() {
double radius, area;

// Ask the user to enter the radius of the circle


printf("Enter the radius of the circle: ");
scanf("%lf", &radius);

// Calculate the area of the circle


area = PI * radius * radius;

// Display the result


printf("The area of the circle with radius %.2f is %.2f\n", radius, area);

return 0;
}

Output:
Enter the radius of the circle: 4
The area of the circle with radius 4.00 is 50.27

FST, IFHE, Hyderabad


23
2.4. Write a C program to enter marks of five subjects and calculate total,
average and percentage of marks.
Solution:
Algorithm:
Step-1 : Read marks to sub1, sub2, sub3, sub4, sub5
Step-2 : Compute
total = sub1 + sub2 + sub3 + sub4 + sub5;
average = total / 5.0;
percentage = (total / 500.0) * 100;
Step-3 : Display total, average, percentage
Step-4 : Stop

Flowchart:
Start

Read marks to sub1, sub2, sub3, sub4, sub5

Compute
total = sub1 + sub2 + sub3 + sub4 + sub5;
average = total / 5.0;
percentage = (total / 500.0) * 100;

Display total, average, percentage

Stop

Program File : Prg24.c

#include <stdio.h>total, average and percentage */


/* Calculate
int main()
{
float sub1, sub2, sub3, sub4, sub5;
float total, average, percentage;
/* Input marks of all five subjects */
printf("Enter marks of five subjects: \n");
scanf("%f%f%f%f%f", &sub1, &sub2, &sub3, &sub4, &sub5);

FST, IFHE, Hyderabad


24
total = sub1+sub2+sub3+sub4+sub5;
average = total / 5.0;
percentage = (total / 500.0) * 100;
/* Print all results */
printf("Total marks = %.2f\n", total);
printf("Average marks = %.2f\n", average);
printf("Percentage = %.2f", percentage);
return 0;
}

Output:
Enter marks of five subjects:
78
95
63
42
86
Total marks = 364.00
Average marks = 72.80
Percentage = 72.80

2.5. Write a C program to convert days into years, weeks and days.
Solution:

Algorithm
Step-1 : Read days
Step-2 : Compute
years = days/365; // Calculate years
weeks = (days % 365)/7; // Calculate weeks
days = days - ((years*365) + (weeks*7)); //remaining days
Step-3 : Display years, weeks, days
Step-4 : Stop

FST, IFHE, Hyderabad


25
Flowchart:

Program File: Prg25.c


#include <stdio.h>
int main()
{
int days, years, weeks;
printf("Enter total number of days : ");
scanf("%d",&days);
printf(“%d days equivalent to : \n”,days);
// Converts days to years, weeks and days
years = days/365; // Calculate years
weeks = (days % 365)/7; // Calculate weeks
days = days - ((years*365) + (weeks*7)); // Calculate remaining days

// Print the results


printf("Years: %d\n", years);
printf("Weeks: %d\n", weeks);
printf("Days: %d \n", days);

return 0;
}

Output-1: Output-2:
Enter total number of days : 1329 Enter total number of days : 500
1329 days equivalent to : 500 days equivalent to :
Years: 3 Years: 1
Weeks: 33 Weeks: 19
Days: 3 Days: 2

FST, IFHE, Hyderabad


26
Week-3 Lab-1

1. Basic Viva Voce Questions and Answers

1. What is variable?
Ans:
A variable is a quantity whose value is not fixed. The value of the variable can be changed
throughout the program. It is the memory location where we store value in the computer.
Now a=5 later a can be 10 and so on.
2. What is int data type?
Ans:
An integer type variable can store zero, positive, and negative values without any decimal. In
C language, the integer data type is represented by the int keyword, and it can be both signed
or unsigned. A variable can be declared as int using int a=5.
3. What are operators in C?
Ans:
Operators in C are symbols that perform operations on variables and values. They include
arithmetic operators (e.g., +, -, *, /), relational operators (e.g., ==, !=, >, <), logical operators
(e.g., &&, ||, !), bitwise operators (e.g., &, |, ^), assignment operators (e.g., =, +=, -=), and
others.
4. What is the difference between = and == in C?
Ans:
In C, = is an assignment operator used to assign a value to a variable, while == is a relational
operator used to compare two values for equality. For example, x = 5 assigns the value 5 to
Assignments:
the variable x, whereas x == 5 checks if x is equal to 5 and returns a boolean result (true or
false).

Assignments:
3.1 Write a C program to convert the temperature in degree Centigrade into Fahrenheit and vice
versa. (Formula: C= (F-32)/1.8)
3.2 You are given total time in seconds. Convert it into Hour: Min: Second format.

FST, IFHE, Hyderabad


27
3.1 Write a C program to convert the temperature in degree Centigrade into
Fahrenheit and vice versa. (Formula: C= (F-32)/1.8)
Solution:

Algorithm:
Step-1 : Read temperature in celsius
Step-2 : Compute fahrenheit = (celsius * 9 / 5) + 32
Step-3 : Display Fahrenheit
Step-4 : Stop

Flowchart:

FST, IFHE, Hyderabad


28
Program: prg31.c
/**
* C program to convert temperature from degree celsius to fahrenheit
*/

#include <stdio.h>

int main()
{
float celsius, fahrenheit;

/* Input temperature in celsius */


printf("Enter temperature in Celsius: ");
scanf("%f", &celsius);

/* celsius to fahrenheit conversion formula */


fahrenheit = (celsius * 9 / 5) + 32;

printf("%.2f Celsius = %.2f Fahrenheit", celsius, fahrenheit);

return 0;
}

Output:
Enter temperature in Celsius: 42
42.00 Celsius = 107.60 Fahrenheit

3.2 You are given total time in seconds. Convert it into Hour: Min: Second
format.
Solution:

FST, IFHE, Hyderabad


29
Algorithm:
Step-1 : Read sec
Step-2 : Compute
hr = ( sec / 3600 )
min = ( sec - ( 3600 * hr ) ) / 60
sec = ( sec - ( 3600 * hr ) - ( min * 60 ) )
Step-3 : Display hr, min, sec
Step-4 : Stop

Flowchart Start

Read sec

Compute
hr = ( sec / 3600 )
min = ( sec - ( 3600 * h ) ) / 60
second = ( sec - ( 3600 * h ) - ( m * 60 ) )

Display hr , min , sec

Program: prg32.c Stop

#include <stdio.h>
int main() {
int sec, hr, min; // Declare variables for seconds, hours, minutes, and seconds

// Prompt user for input seconds and store in 'sec'


printf("Input seconds: ");
scanf("%d", &sec);

// Calculate hours, minutes, and remaining seconds


hr = (sec/3600);
min = (sec -(3600*hr))/60;
sec = (sec -(3600*hr)-(min*60));

// Print the time in format Hours:Minutes:Seconds


printf("Hours:Minutes:Seconds - %d:%d:%d\n",hr,min,sec);
return 0;
}

Output:
Input seconds: 10584
Hours:Minutes:Seconds - 2:56:24

FST, IFHE, Hyderabad


30
Week-3 Lab-2

Assignments:
3.3 Write a simple program that prints the results of all the operators available in C (including
pre/post increment, bitwise and/or/not, etc.). Read required operand values from standard input.
3.4 Write a C program to find out whether the character pressed through the Keyboard is a digit
or not (Use conditional operator only).
3.5 Write a C program to swap variable values of two variables using following techniques.
a) Using a third variable b) Without using third variable

3.3 Write a simple program that prints the results of all the operators available
in C (including pre/post increment, bitwise and/or/not, etc.). Read required
operand values from standard input.
Solution:
Algorithm:
Step-1 : Read two numbers to variables a and b.
Step-2 : Compute result using all relational, logical, increment, decrement, Bitwise operations
Step-3 : Display the result during calculation
Step-4 : Stop

Flowchart
Start

Read a and b

Compute the result doing all the relational, logical,


increment, decrement, Bitwise operations and display the
result.

Display the result during calculation

Stop

FST, IFHE, Hyderabad


31
Program File : Prg33.c

#include <stdio.h>
int main() {
int a, b;
// Read two integers from standard input
printf("Enter two integers (a and b): ");
scanf("%d %d", &a, &b);

// Arithmetic Operators
printf("Arithmetic Operators:\n");
printf("a + b = %d\n", a + b);
printf("a - b = %d\n", a - b);
printf("a * b = %d\n", a * b);
printf("a / b = %d\n", a / b);
printf("a %% b = %d\n", a % b); // Use %% to print the % character

// Relational Operators
printf("\nRelational Operators:\n");
printf("a == b = %d\n", a == b);
printf("a != b = %d\n", a != b);
printf("a > b = %d\n", a > b);
printf("a < b = %d\n", a < b);
printf("a >= b = %d\n", a >= b);
printf("a <= b = %d\n", a <= b);

// Logical Operators
printf("\nLogical Operators:\n");
printf("a && b = %d\n", a && b);
printf("a || b = %d\n", a || b);
printf("!a = %d\n", !a);
printf("!b = %d\n", !b);

// Bitwise Operators
printf("\nBitwise Operators:\n");
printf("a & b = %d\n", a & b);
printf("a | b = %d\n", a | b);
printf("a ^ b = %d\n", a ^ b);
printf("~a = %d\n", ~a);
printf("~b = %d\n", ~b);

// Shift Operators
printf("\nShift Operators:\n");
printf("a << 1 = %d\n", a << 1); // Left shift by 1
printf("a >> 1 = %d\n", a >> 1); // Right shift by 1

FST, IFHE, Hyderabad


32
// Increment and Decrement Operators
printf("\nIncrement/Decrement Operators:\n");
printf("++a = %d\n", ++a); // Pre-increment
printf("a++ = %d\n", a++); // Post-increment
printf("--a = %d\n", --a); // Pre-decrement
printf("a-- = %d\n", a--); // Post-decrement

// Ensure variables are reset to their original values


a += 1; // Reset a to its original value after post-increment/decrement

return 0;
}

Output:
Enter two integers (a and b): 15
6

Arithmetic Operators:
a + b = 21
a-b=9
a * b = 90
a/b=2
a%b=3

Relational Operators:
a == b = 0
a != b = 1
a>b=1
a<b=0
a >= b = 1
a <= b = 0

Logical Operators:
a && b = 1
a || b = 1
!a = 0
!b = 0

Bitwise Operators:
a&b=6
a | b = 15
a^b=9
~a = -16
~b = -7

FST, IFHE, Hyderabad


33
Shift Operators:
a << 1 = 30
a >> 1 = 7

Increment/Decrement Operators:
++a = 16
a++ = 16
--a = 16
a-- = 16

3.4 Write a C program to find out whether the character pressed through the
Keyboard is a digit or not (Use conditional operator only).
Solution:

ASCII value ranges-


For capital alphabets : 65 – 90
For small alphabets : 97 – 122
For digits : 48 – 57

Algorithm:
Step 1 : Read a Character to variable c
Step 2 : Compute isDigit = ( ( c > = ' 0 ' ) & & ( c < = ' 9 ' ) ) ? 1 : 0
Step 3 : If isDigit = 1 then
Display “Digit”
Else
Display “Not a Digit”
End of if block
Step 4: Stop

FST, IFHE, Hyderabad


34
Flowchart:
Start

Read a character to c

Compute isDigit = ( ( c > = ' 0 ' ) & & ( c < = ' 9 ' ) ) ? 1 : 0

N
isDigit==1 ?

Display “Digit” Display “Not a Digit”

Stop

Program File : prg34.c

#include <stdio.h>
int main() {
char ch;
// Read a character from the user
printf("Enter a character: ");
scanf(" %c", &ch);
// Check if the character is a digit
(ch >= '0' && ch <= '9') ? printf("The character '%c' is a digit.\n", ch)
: printf("The character '%c' is not a digit.\n", ch);
return 0;
}

Output-1: Output-2: Output-3:


Enter a character: 5 Enter a character: 0 Enter a character: k
The character '5' is a digit. The character '0' is a digit. The character 'k' is not a digit.

FST, IFHE, Hyderabad


35
3.5 Write a C program to swap variable values of two variables using following
techniques.
a) Using a third variable b) Without using third variable
Solution:
a) Using a third variable

Algorithm:
Step 1: Read First Number to a
Step 2: Read Second Number to b
Step 3: Display “Before Swap” a and b
Step 4: Set temp =a
Set a = b
Set b = temp
Step 5: Display “After Swap” a and b
Step 6: Stop

Swapping of two different colours

FST, IFHE, Hyderabad


36
Program File : Prg351.c

#include <stdio.h>
int main()
{
int a,b,temp;
printf("Enter First Number : ");
scanf("%d",&a);
printf("Enter Second Number : ");
scanf("%d",&b);
printf("Before Swap a = %d and b = %d \n",a,b);
temp = a;
a = b;
b = temp;
printf("After Swap a = %d b = %d",a,b);
return 0;
}
Output

FST, IFHE, Hyderabad


37
Enter First Number : 5
Enter Second Number : 10
Before Swap a = 5 and b = 10
After Swap a = 10 b = 5

b) Without using variable

Algorithm:
Step 1 : Read First Number to a
Step 2 : Read Second Number to b
Step 3 : Display “Before Swap” a and b
Step 4 : Compute
a=a+b
b=a-b
a=a-b
Step 5 : Display “After Swap” a and b
Step 6 : Stop

Program File : Prg352.c


#include <stdio.h>
int main()
{
int a,b,temp;

printf("Enter First Number : ");


scanf("%d",&a);

FST, IFHE, Hyderabad


38
printf("Enter Second Number : ");
scanf("%d",&b);

printf("Before Swap a = %d and b = %d \n",a,b);


a=a+b;
b = a-b;
a = a-b;

printf("After Swap a = %d b = %d",a,b);


return 0;
}

Output:
Enter First Number : 5
Enter Second Number : 10
Before Swap a = 5 and b = 10
After Swap a = 10 b = 5

FST, IFHE, Hyderabad


39
Week-4 Lab-1

2. Basic Viva Voce Questions and Answers

1. What are the types of if statements?


Ans:
There are 4 types of if statements as below
1. Simple if Statement
2. if-else Statement
3. Nested if Statement
4. if-else-if Ladder
2. How to check a number is even or odd? Which type of if is better for this purpose?
Ans:
If the number is divisible by (2 i.e num % 2 == 0) then the number is an Even otherwise Odd. The if else
statement
4.1 Write aisCbetter for this
program to purpose.
find the maximum of given three numbers.
3. In the if else statement, when the else part will be executed?
Ans:
In the if else statement, the else part will be executed when its if condition is false only.
4. What is the difference between if else ladder and switch statement?
Ans:
if-else-if ladder statement controls the statements to be executed on the basis of given conditions
whereas switch statement tests the value of variable or expression against a series of different cases
or values and when a match is found, then the block of code is executed otherwise the default case is
executed.

Assignments:

4.1 Write a C program to determine whether input number is Odd or Even. Display appropriate
message. (use if else statement)

4.2 Write a C program to find the maximum of given three numbers. (using if statement and
nested if statement separately)

FST, IFHE, Hyderabad


40
4.1 Write a C program to determine whether input number is Odd or Even.
Display appropriate message. (use if else statement)
Solution:

Algorithm:
Step 1: Read num
Step 2: If (num mod 2 = 0) then
Display “Even”
Else
Display “Odd”
Endif
Step 3: Stop

Flowchart:
Start

Read num

N
is num module 2 = 0?

Display “Even” Display “Odd”

Stop

FST, IFHE, Hyderabad


41
Program File : Prg41.c

#include <stdio.h>
int main() {
int num;
//Input the Number
printf("Enter an integer: ");
scanf("%d", &num);
//Check the number is Even or Odd
if (num % 2 == 0) {
printf("%d is Even.\n", num);
} else {
printf("%d is Odd.\n", num);
}
return 0;
}

Output-1:
Enter an integer: 25
25 is Odd.
Output-2:
Enter an integer: 8
8 is Even.

4.2 Write a C program to find the maximum of given three numbers. (using if
statement and nested if statement separately)
Solution:
i) Using if statement
Algorithm:
Step-1 : Read a, b and c
Step-2 : If (a > = b and a > = c) then
Display a
Endif
Step-3 : If (b >= a and b >= c)
Display b
Endif
Step-4 : If (c >= a and c >= b)
Display c
Endif
Step-5 : Stop

FST, IFHE, Hyderabad


42
Flowchart:
Start

Read a, b and c

Y
is (a>b and a>c) ?

N Display a

Y
is (b>a and b>c) ?

Display b N

Y
is (c>a and c>b) ?

N Display c

Stop

FST, IFHE, Hyderabad


43
Program File : Prg421.c

//Using simple if
#include <stdio.h>
int main() {
int a, b, c;

printf("Enter three different numbers: ");


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

// if a is greater than both b and c, then a is the largest


if (a >= b && a >= c)
printf("%d is the largest number.", a);

// if b is greater than both a and c, then b is the largest


if (b >= a && b >= c)
printf("%d is the largest number.", b);

// if c is greater than both a and b, then c is the largest


if (c >= a && c >= b)
printf("%d is the largest number.", c);

return 0;
}

Output-1:
Enter three different numbers: 94
45
67
94 is the largest number

Output-2:
Enter three different numbers: 12
58
32
58 is the largest number

FST, IFHE, Hyderabad


44
ii) Using nested if statement
Algorithm:
Step-1: Read a, b and c
Step-2: If (a > b) then
Goto Step-3
Else
Goto Step-4
Endif
Step-3: If (a > c) then
Display a
Else
Display c
Endif
Step-4 : If(b > c) then
Display b
Else
Display c
Endif
Step-5 : Stop

FST, IFHE, Hyderabad


45
Program File : Prg422.c

#include <stdio.h>
int main() {
int a, b, c;
printf("Enter three numbers: ");
scanf("%d%d%d", &a, &b, &c);

// outer if statement
if (a >= b) { // inner if...else
if (a >= c)
printf("%d is the largest number.", a);
else
printf("%d is the largest number.", c);
}
// outer else statement
else { // inner if...else
if (b >= c)
printf("%d is the largest number.", b);
else
printf("%d is the largest number.", c);
}
return 0;
}

Output-1:
Enter three numbers: 23
54
69
69 is the largest number.
Output-2:
Enter three numbers: 100
50
200
200 is the largest number.

FST, IFHE, Hyderabad


46
Week-4 Lab-2
Assignment:

4.3 Write a program to read marks from keyboard and your program should display
equivalent grade according to following table (if else ladder)
Marks Grade
100 – 80 Distinction
79 – 60 First Class
59 – 40 Second Class
< 40 Fail

4.4 Write a C program to input month number and print total number of days in month
using switch...case

4.5 Write a C program for designing a calculator using menu driven Program.

4.3 Write a program to read marks from keyboard and your program should
display equivalent grade according to following table (if else ladder)
Marks Grade
100 – 80 Distinction
79 – 60 First Class
59 – 40 Second Class
< 40 Fail
Solution:

Algorithm:
Step-1 : Read marks
Step-2 : If (marks > 100 OR marks < 0) then
Display “Your Input is out of Range"
Step-3 : Else if (marks >= 80) then
Display “You got Distinction"
Step-4 : Else if (marks >= 60) then
Display “You got First Class"
Step-5 : Else if (marks >= 40) then
Display “You got Second Class"
Else
Display “You got Fail"
Endif
Step-5 : Stop

FST, IFHE, Hyderabad


47
Start
Flowchart:

Read marks

Is (marks > 100


N
OR marks < 0)
?

Is N
(marks >=80)
?

Display “Output of Range” Y

Is N
(marks >= 60)
?

Display “Distinction”
Y

Is
(marks >= 40)
? N

Display “First Class”


Y

Display “Second Class”

Display “Fail”

Stop

FST, IFHE, Hyderabad


48
Program File : Prg43.c

#include<stdio.h>
int main() {
int marks;
printf("\n Enter Marks between 0-100 :");
scanf("%d", &marks);
if (marks > 100 || marks < 0) {
printf("\n Your Input is out of Range");
}
else if (marks >= 80) {
printf("\n You got Distinction");
}
else if (marks >= 60) {
printf("\n You got First Class");
}
else if (marks >= 40) {
printf("\n You got Second Class");
}
else {
printf("\n You got Fail");
}
return 0;
}

Output-1:
Enter Marks between 0-100 :85
You got Distinction
Output-2:
Enter Marks between 0-100 :12
You got Fail
Output-3:
Enter Marks between 0-100 :56
You got Second Class
Output-4:
Enter Marks between 0-100 :105
Your Input is out of Range

FST, IFHE, Hyderabad


49
4.4 Write a C program to input month number and print total number of days
in month using switch...case
Solution:
Algorithm:
Step-1 : Read the month as a number.
Step-2 : Using switch statement when value of month is one of 4, 6, 9, 11 then corresponding to
switch case
Set days=30
Step-3 : If month is one of these value 1, 3, 5, 7, 8, 10, 12 then corresponding to switch case
Set days=31
Step-4 : If month value is 2 then corresponding to switch case
Set days=28
Step-5 : Else the default condition for the switch case then
Set days=0
EndCase
Step-6 : If (days = 0) then
Display “Invalid Month”
Else
Display days
Endif
Step-7 : Stop

FST, IFHE, Hyderabad


50
Start

Read month

Is month = 4 or Y
Set days = 30
6 or 9 or 11 ?

Is month = 1
or 3 or 5 or 7
Set days = 31
or 8 or 10 or Y
12?
?

Is Y Set days = 28
month = 2 ?

Set days = 0

Y
Is days = 0 ? Display “Invalid Month”

Display days

Stop

FST, IFHE, Hyderabad


51
Program File : Prg44.c

#include <stdio.h>

int main()
{
int month;
int days;

printf("Enter month: ");


scanf("%d",&month);

switch(month)
{
case 4:
case 6:
case 9:
case 11:
days=30;
break;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
days=31;
break;

case 2:
days=28;
break;

default:
days=0;
break;
}

if(days)
printf("Number of days in %d month is: %d\n",month,days);
else
printf("You have entered an invalid month!!!\n");

return 0;

FST, IFHE, Hyderabad


52
Output
First run:
Enter month: 3
Number of days in 3 month is: 31

Second run:
Enter month: 2
Number of days in 2 month is: 28

Third run:
Enter month: 11
Number of days in 11 month is: 30

Fourth run:
Enter month: 13
You have entered an invalid month!!!

4.5 Write a C program for designing a calculator using menu driven Program.
Solution:
Algorithm:
Step 1: Declare local variables num1, num2, opt. For example, where n1 and n2 take two
numeric values, res will store results and opt variable define the operator symbols.
Step 2: Print the Choice (1. Addition, 2. Subtraction, 3. Multiplication, 4. Division, 5. Modulo
Division, 6. Exit)
Step 3: Enter the Choice
Step 4: Read two numbers, num1 and num2
Step 5: Switch case jump to an operator selected by the user
Step 6: Display the operation result
Step 8: Stop

FST, IFHE, Hyderabad


53
Start

Read num1, num2, opt

Y
Is opt = 1 ? Display num1 + num2

Is opt = 2 ? Display num1 - num2

Is opt = 3 ? Display num1 * num2

N Y

Y
Is opt = 4 ? Display num1 / num2

Y
Is opt = 5 ? Display num1 mod num2

Display”Invalid Option”

Stop

FST, IFHE, Hyderabad


54
Program File : Prg45.c
#include <stdio.h>
int main() {
int num1,num2,opt;
printf("Enter the first Integer :");
scanf("%d",&num1);
printf("Enter the second Integer :");
scanf("%d",&num2);
do{
printf("\nInput your option :\n");
printf("1-Addition.\n2-Substraction.\n3-Multiplication.\n4-Division.\n5.-Modulo
Division.\n6.-Exit.\n");
scanf("%d",&opt);
switch(opt) {
case 1:
printf("Addition of %d and %d is: %d\n",num1,num2,num1+num2);
break;

case 2:
printf("Substraction of %d and %d is: %d\n",num1,num2,num1-num2);
break;

case 3:
printf("Multiplication of %d and %d is: %d\n",num1,num2,num1*num2);
break;

case 4:
if(num2==0) {
printf("The second integer is zero. Divide by zero.\n");
}
else {
printf("The Division of %d and %d is :
%d\n",num1,num2,num1/num2);
}
break;
case 5:
if(num2==0) {
printf("The second integer is zero. Devide by zero.\n");
}
else {
printf("The modulo Division of %d and %d is :
%d\n",num1,num2,num1%num2);
}
break;
case 6:
break;

default:
printf("Input correct option\n");

FST, IFHE, Hyderabad


55
break;
}
}while(opt!=6);
return(0);
}

Output:
Enter the first Integer :15
Enter the second Integer :6

Input your option :


1-Addition.
2-Substraction.
3-Multiplication.
4-Division.
5.-Modulo Division.
6.-Exit.
1
The Addition of 15 and 6 is: 21

Input your option :


1-Addition.
2-Substraction.
3-Multiplication.
4-Division.
5.-Modulo Division.
6.-Exit.
2
The Substraction of 15 and 6 is: 9

Input your option :


1-Addition.
2-Substraction.
3-Multiplication.
4-Division.
5.-Modulo Division.
6.-Exit.
3
The Multiplication of 15 and 6 is: 90

Input your option :


1-Addition.
2-Substraction.
3-Multiplication.
4-Division.
5.-Modulo Division.
6.-Exit.
4
The Division of 15 and 6 is : 2

Input your option :


1-Addition.
2-Substraction.
3-Multiplication.

FST, IFHE, Hyderabad


56
4-Division.
5.-Modulo Division.
6.-Exit.
5
The modulo Division of 15 and 6 is : 3

Input your option :


1-Addition.
2-Substraction.
3-Multiplication.
4-Division.
5.-Modulo Division.
6.-Exit.
6

FST, IFHE, Hyderabad


57
Week-5 Lab-1

3. Basic Viva Voce Questions and Answers

1. How many types of loops are there in C language?

Answer:

Three types of loops are there in C. These are the while loop, the do-while loop, and the for loop.

2. Differentiate between for loop and a while loop? What are it uses?
Answer:

For executing a set of statements fixed number of times we use for loop whereas when the number
of iterations to be performed is not known in advance we use while loop.

3. What is the use of a do-while loop?

Answer:

We use the do-while loop in C when we want the loop to execute at least once. If the test condition is
false, the for loop and while loop do not run even once.

4. Differentiate "break" and "continue" statements?

Answer:

We use the “break” statement to exit from the loop as soon as the flow of control goes to this
statement. The “continue” statement is used to omit the current iteration and jump to the next
iteration of the loop.

Assignments:

5.1 Write a C program to find the sum of first 100 natural numbers.
5.2 Write a C program to find factorial of a given number
5.3 Write a C program to find the sum of odd numbers and even numbers between 1 to N (N is
a given input number).

FST, IFHE, Hyderabad


58
5.1 Write a C program to find the sum of first 100 natural numbers.
Solution:
Algorithm:
Step-1 : Initilize i=0 and sum = 0
Step-2 : READ n
Step-3 : Repeat Step-4 and Step-5 until i<=n
Step-4 : Compute sum = sum + i
Step-5 : Compute i = i + 1
Step-6 : Display sum
Step-7 : Stop

Program File : Prg51.c


#include <stdio.h>
int main() {
int i,sum = 0;
// Loop to calculate the sum of the first 100 natural numbers
for (i = 1; i <= 100; i++) {
sum += i;
}
// Print the result
printf("The sum of the first 100 natural numbers is: %d\n", sum);
return 0;
}

Output:
The sum of the first 100 natural numbers is: 5050

FST, IFHE, Hyderabad


59
5.2 Write a C program to find factorial of a given number.
Solution:
Algorithm:
Step-1 : Initialize i=1 and fact=1
Step-2 : READ n
Step-3 : If n < 0 then
Display “Factorial of a negative number doesn ' t exist” and goto Step-8
Endif
Step-4 : Repeat Step-5 and Step-6 until i<=n
Step-5 : Compute fact = fact * i
Step-6 : Compute i = i + 1
Step-7 : Display fact
Step-8 : Stop

Program File : Prg52.c

#include <stdio.h>
int main() {
int n, i;
unsigned long fact = 1;
printf("Enter an integer: ");
scanf("%d", &n);
// shows error if the user enters a negative integer
if (n < 0)
printf("Error! Factorial of a negative number doesn't exist.");
else {
for (i = 1; i <= n; i++) {
fact *= i;
}
printf("Factorial of %d = %lu", n, fact);
}
return 0;
}

Output-1:
Enter an integer: 5
Factorial of 5 = 120
Output-1:
Enter an integer: 12
Factorial of 12 = 479001600

FST, IFHE, Hyderabad


60
5.3 Write a C program to find the sum of odd numbers and even numbers
between 1 to N (N is a given input number).
Solution:

Algorithm:
Step-1 : Initialize i=1, even_sum = 0 and odd_sum = 0
Step-2 : READ n
Step-3 : Repeat Step-4 and Step-7 until i<=n
Step-4 : If (i mod 2 = 0) then
Goto Step-5
Else
Got Step-6
Endif
Step-5 : Compute even_sum = even_sum + i and goto Step-7
Step-6 : Compute odd_sum = odd_sum + i
Step-7 : Compute i = i + 1
Step-8 : Display even_sum and odd_sum
Step-9 : Stop

Program File : Prg53.c


#include <stdio.h>
int main()
{
int i, num, odd_sum = 0, even_sum = 0;
printf("Enter the value of num\n");
scanf("%d", &num);
for (i = 1; i <= num; i++)
{
if (i % 2 == 0) //Chek Even or Odd
even_sum = even_sum + i; //to add all Even numbers
else
odd_sum = odd_sum + i; //to add all Odd Number
}
printf("Sum of all odd numbers = %d\n", odd_sum);
printf("Sum of all even numbers = %d\n", even_sum);
return 0;
}
Output:
Enter the value of num
10
Sum of all odd numbers = 25
Sum of all even numbers = 30

FST, IFHE, Hyderabad


61
Week-5 Lab-2

Assignments:

5.4 Write a C program to display the first 100 prime numbers.


5.5 Write a C program to construct the following patterns
a) 1 b) *
12 **
123 ***
1234 ****
12345 *****
5.6 Write a C program for calculator to include the following in the menu
a. To convert decimal to binary.
b. To convert decimal to hexadecimal.

5.4 Write a C program to display the first 100 prime numbers.


Solution:

Algorithm:
Step-1 : Initilize ctr=0, p_ctr=0, num=2, i=2
Step-2 : Repeat Step-3 to Step-10 until p_ctr <= 100
Step-3 : Set i = 2
Step-4 : Set ctr = 0
Step-5 : Repeat Step-6 to Step-7 until (i <=(num/2))
Step-6 : If (num % i = 0) then
Compute ctr = ctr +1
Step-7 : Compute i = i + 1
Step-8 : If (ctr = 0) then
Display num
Step-9 : Compute p_ctr= p_ctr + 1
Step-10 : Compute num = num +1
Step-11 : Stop

FST, IFHE, Hyderabad


62
Program File : Prg54.c
#include<stdio.h>
int main()
{
int i, num, count, prime_counter=0;

printf("First 100 Prime Numbers are: ");


for(num=2 ; prime_counter<100 ; num++) //Loop to count 100 primes
{
count = 0;
for (i = 2; i <= num/2; i++) //loop to check num is prime or not
{
if(num%i == 0)
count++; //count increments if not prime
}
if(count == 0)//display if prime and then increment the count of prime numbers
{
printf("\n%d ", num);
prime_counter++;
}
}
return 0;
}

Output:
First 100 Prime Numbers are:
2
3
5
7
11
13
17
19
23
29
31
.
.
.
521
523
541

FST, IFHE, Hyderabad


63
5.5 Write a C program to construct the following patterns
a) 1 b) *
12 **
123 ***
1234 ****
12345 *****

Solution :
a) 1
12
123
1234
12345

Algorithm:
Step-1 : Initialize i=1
Step-2 : Repeat Step-3 to Step-8 until i<=5
Step-3 : Initialize j=1
Step-4 : Repeat Step-5 and Step-6 until j<=i
Step-5 : Display j
Step-6 : Compute j=j+1
Step-7 : Display a new line
Step-8 : Compute i=i+1
Step-9 : Stop

Program File : Prg541.c

#include<stdio.h>
int main()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
printf("%d",j);
printf("\n");
}
return 0;
}
Output:
1
12
123
1234
12345

FST, IFHE, Hyderabad


64
b)
*
**
***
****
*****
Algorithm:
Step-1 : Initialize i=1
Step-2 : Repeat Step-3 to Step-11 until i<=5
Step-3 : Initialize j=1
Step-4 : Repeat Step-5 and Step-6 until j <= 5 - i
Step-5 : Display “ “
Step-6 : Compute j=j+1
Step-7 : Repeat Step-8 and Step-9 until j <= i
Step-8 : Display “*“
Step-9 : Compute j=j+1
Step-10 : Display a new line
Step-11 : Compute i=i+1
Step-12 : Stop

Program File : Prg542.c


#include<stdio.h>
int main()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=5-i;j++)
printf(" ");
for(j=1;j<=i;j++)
printf("* ");
printf("\n");
}
return 0;
}

Output:
*
**
***
****
*****

FST, IFHE, Hyderabad


65
5.6 Write a C program for calculator to include the following in the menu
a. To convert decimal to binary.
b. To convert decimal to hexadecimal.
Solution:
Simple Algorithm for Conversion from Decimal to Binary

Step-1: Divide the given decimal number by 2 and note down the remainder.
Step-2: Now, divide the obtained quotient by 2, and note the remainder again.
Step-3: Repeat the above steps until you get 0 as the quotient.
Step-4: Now, write the remainders in such a way that the last remainder is written first,
followed by the rest i.e in the reverse order.
Step-5 Stop

Simple Algorithm for Conversion from Decimal to Hexadecimal

Step-1: Divide the given decimal number by 16 and note down the remainder (replace 10, 11,
12, 13, 14, 15 by A, B, C, D, E, F respectively i.e If the remainder is is less than 10, insert
(48 + remainder) in a character array otherwise if the remainder is greater than or
equal to 10, insert (55 + remainder) in the character array
Step-2: Now, divide the obtained quotient by 16, and note the remainder again as above.
Step-3: Repeat the above steps until you get 0 as the quotient.
Step-4: Now, write the remainders in such a way that the last remainder is written first,
followed by the rest i.e in the reverse order.
Step-5 Stop

Program File : Prg56.c

#include<stdio.h>
int main()
{
int n, num, bin, rem = 0, place;
long int decn,rmd,q,dn=0,m,l;
int i=1,j,tmp,opt ;
char s;

FST, IFHE, Hyderabad


66
printf("Enter a decimal number\n");
scanf("%d", &n);
do
{//start of do
printf("\nInput your option :\n");
printf("1-Decimal to Binary \n2-Decimal to HexaDecimal\n3.-Exit.\n");
scanf("%d",&opt);
switch(opt)
{
case 1:
{
printf("\nBinary equivalent of %d is ", num);
num=n;
bin=0;
place=1;
while(num)
{
rem = num % 2;
num = num / 2;
bin = bin + (rem * place);
place = place * 10;
}
printf("%d\n", bin);
break;
}
case 2:
{
dn=0;
s=' ';
for(num=n;num>0;num=num/16)
{
tmp = num % 16;
if( tmp < 10)
tmp =tmp + 48;
else
tmp = tmp + 55;
dn=dn*100+tmp;
}
printf("\nThe equivalent Hexadecimal Number : ");
for(m=dn;m>0;m=m/100)
{
s=m % 100;
printf("%c",s);
}

FST, IFHE, Hyderabad


67
printf("\n\n");
}
case 3:
break;
default:
printf("Invalid option");
}
}// end do
while(opt!=3);
}
Output:
Enter a decimal number
13
Input your option :
1-Decimal to Binary
2-Decimal to HexaDecimal
3.-Exit.
1
Binary equivalent of 0 is 1101

Input your option :


1-Decimal to Binary
2-Decimal to HexaDecimal
3.-Exit.
2
The equivalent Hexadecimal Number : D

Input your option :


1-Decimal to Binary
2-Decimal to HexaDecimal
3.-Exit.
3

FST, IFHE, Hyderabad


68
Week-6 Lab-1

Assignments:

6.1 Write a C program to count the frequency of digits in a given number. (Frequency means
number of occurrences of the digit in the given number)

6.2 Write a C program to find the sum of digits of the accepted number.

6.1 Write a C program to count the frequency of digits in a given number.


(Frequency means number of occurrence of the digit in the given number)
Solution:

Algorithm:

Step-1 : Read num

Step-2 : Read digit

Step-3 : Set ctr = 0

Step-4 : Repeat Step-5 to Step-7 until (num!=0)

Step-5 : Extract rem as the last digit of num by rem = num %10

Step-6 : Compare rem and digit and increment ctr if same i.e if rem=digit then ctr = ctr + 1

Step-7 : Remove the last digit of num by num = num / 10;

Step-8 : Display ctr

Step-9 : Stop

FST, IFHE, Hyderabad


69
Program File : Prg61.c

#include <stdio.h>
int main()
{
long num;
int digit,rem,count=0;
printf("Enter the Number: ");
scanf("%ld",&num);
printf("Enter the digit to be counted:");
scanf("%d",&digit);
while(num!=0)
{
rem=num%10;
if(rem==digit)
count++;
num=num/10;
}
printf("The digit %d present %d times ",digit,count);
}

OUTPUT
Enter the Number: 56755542311
Enter the digit to be counted:5
The digit 5 present 4 times

FST, IFHE, Hyderabad


70
6.2 Write a C program to find the sum of digits of the accepted number.
Solution:

Algorithm:
Step-1 : Read num
Step-2 : Set sum = 0
Step-3 : Repeat Step-4 to Step-6 until (num > 0)
Step-4 : Extract rem as the last digit of num by rem = num mod 10
Step-5 : Compute sum = sum + rem
Step-6 : Remove the last digit of num by num = num / 10;
Step-7 : Display sum
Step-8 : Stop

Program File : Prg62.c

#include <stdio.h>
int main()
{
int num, temp_num, sum = 0, rem;
printf("Enter an integer\n");
scanf("%d", &num); //Take any integer
temp_num=num; //Store the num in a temporary variable temp_num
while (num!=0) //Continue loop until num > 0
{
rem=num%10; //Find out remainder of division of num by 10
sum=sum+rem; //Find sum with rem
num=num/10; //Reduce the number num dividing by 10
}
num=temp_num; //Get the original number back from temp_num
printf("Sum of digits of %d = %d\n",num,sum);
return 0;
}
Output:
Enter an integer
24589
Sum of digits of 24589 = 28

FST, IFHE, Hyderabad


71
Week-6 Lab-2

Assignments:

6.3 Write a C program to check whether the given number is palindrome or not.

6.4 Write a C program to input a number and find sum of first and last digit of the number
using for loop (e.g Input 5642, Output=7)

6.5 Write a C program to print the given number in word form of digits.
(Ex input : 123, output is ONE TWO THREE )

6.3 Write a C program to check whether the given number is palindrome or


not.
Solution:

Algorithm:
Step-1 : Initialize rev = 0
Step-2 : Read num
Step-3 : Set temp_num = num
Step-4 : Repeat Step-5 to Step-7 until num != 0
Step-5 : Compute rem = num mod 10
Step-6 : Compute rev = rev *10 + rem
Step-7 : Compute num = num / 10
Step-8 : If temp_num = rev then
Display Pallindrome
Else
Display Not Pallindrome
Endif
Step-9 : Stop

FST, IFHE, Hyderabad


72
Program File : Prg63.c

#include <stdio.h>
int main()
{
int num, temp_num, rev = 0, rem;
printf("Enter an integer\n");
scanf("%d", &num); //Take any integer
temp_num=num; //Store the num in a temporary variable temp_num
while (num!=0) //Continue loop until num > 0
{
rem=num%10; //Extract the last digit
rev=rev*10+rem; //Append the last digit to rev
num=num/10; //Remove the last digit
}
num=temp_num; //Get the original number back from temp_num
if(num==rev)
printf("\n%d is Pallindrome number",num);
else
printf("\n%d is Not a Pallindrome number",num);
return 0;
}

Output-1:
Enter an integer
4562

4562 is Not a Pallindrome number

Output-1:
Enter an integer
8668

8668 is Pallindrome number

FST, IFHE, Hyderabad


73
6.4 Write a C program to input a number and find sum of first and last digit of
the number using for loop (e.g Input 5642, Output=7)
Solution:

Algorithm:
Step-1 : Initialize sum = 0
Step-2 : Read num
Step-3 : Set lastdigit = num mod 10
Step-4 : Repeat Step-5 until num >= 10
Step-5 : Compute num = num / 10
Step-6 : Set firstdigit = num
Step-7 : Compute sum = firstdigit + lastdigit
Step-8 : Display sum
Step-9 : Stop

Program File : Prg64.c

/**
* C program to find sum of first and last digit of a number using loop
*/
#include <stdio.h>
int main()
{
int num, sum=0, firstDigit, lastDigit;

/* Input a number from user */


printf("Enter any number to find sum of first and last digit: ");
scanf("%d", &num);

/* Find last digit to sum */


lastDigit = num % 10;

/* Copy num to first digit */


firstDigit = num;

/* Find the first digit by dividing num by 10 until first digit is left */
while(num >= 10)
{
num = num / 10;
}
firstDigit = num;

FST, IFHE, Hyderabad


74
/* Find sum of first and last digit*/
sum = firstDigit + lastDigit;

printf("Sum of first and last digit = %d", sum);

return 0;
}

Output:
Enter any number to find sum of first and last digit: 5642
Sum of first and last digit = 7

6.5 Write a C program to print the given number in word form of digits.
(Ex input : 123, output is ONE TWO THREE )
Solution:

Algorithm:
Step-1 : Read n
Step-2 : Take num as reverse of n

Step-3 : Repeat Step-4 to Step-7 until num != 0


Step-4 : Extract last digit of num using modulo division by 10. Store the result in a variable
say digit = rev % 10
Step-5 : Switch the value of digit found above. Since there are 10 possible values
of digit i.e. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 hence, write 10 cases
Step-6 : Display the corresponding word for each case
Step-7 : Remove last digit from num by dividing it by 10 i.e. num = num / 10
Step-8 : Stop

Program File : Prg65.c

#include<stdio.h>
int main()
{
int rev=0,digit,num,mod;
printf("Enter a positive Integer\n");
scanf("%d", &num);
/* reverse the input number */
while (num > 0)
{
rev=(rev*10)+num%10;
num/=10;
}

FST, IFHE, Hyderabad


75
num=rev;
while (num>0)
{
digit=num%10;
//printDigit(digit);
switch (digit)
{
case 0:
printf("Zero ");
break;
case 1:
printf("One ");
break;
case 2:
printf("Two ");
break;
case 3:
printf("Three ");
break;
case 4:
printf("Four ");
break;
case 5:
printf("Five ");
break;
case 6:
printf("Six ");
break;
case 7:
printf("Seven ");
break;
case 8:
printf("Eight ");
break;
case 9:
printf("Nine ");
break;
}
num=num/10;
}
return 0;
}
Output:
Output:-1 Output:-2 Output:-3 Output:-4
Enter a positive Integer Enter a positive Integer Enter a positive Integer Enter a positive Integer
54 149 2 123
Five Four One Four Nine Two One Two Three

FST, IFHE, Hyderabad


76
Week-7 Lab-1
4. Basic Viva Voce Questions and Answers

1. What is a function in C programming?


Ans:
A function is a block of code that performs a specific task. It can be called from other parts of
the program to execute the code within the function.
2. What is a function prototype?
Ans:
A function prototype is a declaration that provides the function’s name, return type, and
parameter types to the compiler before the function definition.
3. How do you access a function in C?
Ans:
A function can be accessed or called by its name followed by parentheses, and arguments
can be passed within the parentheses if the function has parameters.
4. What is recursion in C?
Ans:
Recursion is a programming technique where a function calls itself directly or indirectly to
solve a problem by breaking it into smaller sub problems.

Assignments:

7.1 Write a C program to find sum of two numbers using function without argument and
with return value
7.2 Write a program to find square of a number using function with argument and with
return value
7.3 Write a C program to find the Fibonacci numbers using a recursive function

FST, IFHE, Hyderabad


77
7.1 Write a C program to find sum of two numbers using function without
argument and with return value.
Solution:
Program File : Prg71.c

#include<stdio.h>
int add(); //Function Prototype
int main()
{
int sum;
sum=add(); //Calling Function
printf("\nSum = %d",sum);
return(0);
}

int add() //Function Definition


{
int a,b,c;
printf("Enter two numbers : ");
scanf("%d%d",&a,&b);
c=a+b;
return(c);
}

Output:
Enter two numbers : 5
7
Sum = 12

FST, IFHE, Hyderabad


78
7.2 Write a program to find square of a number using function with argument
and with return value
Solution:
Program File : Prg72.c
#include<stdio.h>
int sqr(int); //Function Prototype
int main()
{
int n,s;
printf("Enter a number :");
scanf("%d",&n);
s=sqr(n); // Function Call
printf("\nSquare of %d = %d",n,s);
return(0);
}

int sqr(int a) //Function Declaration


{
int r;
r=a*a;
return(r);
}
Output:
Enter a number :9

Square of 9 = 81

FST, IFHE, Hyderabad


79
7.3 Write a C program to find the Fibonacci numbers using a recursive function
Solution:

Program File : Prg73.c


#include<stdio.h>
void printFibonacci(int n){ //Function Definition
static int n1=0,n2=1,n3;
if(n>0){
n3 = n1 + n2;
n1 = n2;
n2 = n3;
printf("%d ",n3);
printFibonacci(n-1);
}
}

int main(){
int n;
printf("Enter the number of elements: ");
scanf("%d",&n);
printf("Fibonacci Series: ");
printf("%d %d ",0,1);
printFibonacci(n-2);//n-2 because 2 numbers are already printed
return 0;
}

Output:
Enter the number of elements: 7
Fibonacci Series: 0 1 1 2 3 5 8
Enter the number of elements: 15
Fibonacci Series: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

FST, IFHE, Hyderabad


80
Week-7 Lab-2
Assignments:
7.4 Write a C program to find sum and average of n numbers in the array.
7.5 Write a C program to find both the largest and smallest number in a list of integers.
7.6 Write a C program to perform addition of two 3 x 3 matrices

7.4 Write a C program to find sum and average of n numbers in the array.
Solution
Program File : Prg74.c

#include<stdio.h>
int main()
{
int i,n,a[100],sum=0; //Array a[100] declared with size 100
float avg;
printf("Enter Size :");
scanf("%d",&n);
printf("Enter %d Numbers into the Array\n",n);
printf("\n----------------------------------\n");

//Input n numbers to the array


for(i=0;i<n;i++)
{
printf("Enter a[%d]:",i);
scanf("%d",&a[i]);
}

//Calculate Sum and Average


for(i=0;i<n;i++)
sum=sum+a[i];
avg=(float)sum/n;
printf("\nYour Numbers are : ");

//Display
for(i=0;i<n;i++)
printf("\n%d",a[i]);
printf("\nSum = %d and Average = %.2f",sum,avg);
return(0);
}

FST, IFHE, Hyderabad


81
Output:
Enter Size :5
Enter 5 Numbers into the Array
----------------------------------
Enter a[0]:1
Enter a[1]:22
Enter a[2]:3
Enter a[3]:4
Enter a[4]:6

Your Numbers are :


1
22
3
4
6
Sum = 36 and Average = 7.20

7.5 Write a C program to find both the largest and smallest number in a list of
integers.
Solution:
Program File : Prg75.c

#include<stdio.h>
int main()
{
int i,n,a[100],large,small;
printf("\nEnter the number of elements : ");
scanf("%d",&n);
printf("\nInput the array elements : ");
for(i=0;i<n;++i)
scanf("%d",&a[i]);

large=small=a[0];

for(i=1;i<n;++i)
{
if(a[i]>large)
large=a[i];

if(a[i]<small)
small=a[i];
}

printf("\nThe smallest element is %d\n",small);


printf("\nThe largest element is %d\n",large);

FST, IFHE, Hyderabad


82
return 0;
}

Output:
Enter the number of elements : 5
Input the array elements : 10
25
68
14
23
The smallest element is 10
The largest element is 68

7.6 Write a C program to perform addition of two 3 x 3 matrices


Solution:
Program File : Prg76.c

#include<stdio.h>
int main()
{
int mat1[3][3], mat2[3][3], i, j, mat3[3][3]; //Declaration of 3X3 matrices
printf("Enter 3*3 matrix 1 elements :");
for(i=0; i<3; i++) //Input to Mat1
{
for(j=0; j<3; j++)
scanf("%d",&mat1[i][j]);
}
printf("Enter 3*3 matrix 2 elements :");
for(i=0; i<3; i++) //Input to Mat2
{
for(j=0; j<3; j++)
scanf("%d",&mat2[i][j]);
}

printf("\nAdding the two matrix.....");


for(i=0; i<3; i++) //Matrix Addition
{
for(j=0; j<3; j++)
mat3[i][j] = mat1[i][j] + mat2[i][j];
}

FST, IFHE, Hyderabad


83
printf("\nBoth matrix added successfully!");

printf("\nHere is the resultant matrix:\n");


for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
printf("%d ",mat3[i][j]);
printf("\n");
}
return 0;
}

Output:
Enter 3*3 matrix 1 elements :
121
365
421
Enter 3*3 matrix 2 elements :
961
543
276

Adding the two matrix.....


Both matrix added successfully!
Here is the resultant matrix:
10 8 2
8 10 8
697

FST, IFHE, Hyderabad


84
Week-8 Lab-1

5. Basic Viva Voce Questions and Answers

1. What is an array?
Ans:
It is a collection of elements of same data type stored at contiguous memory locations.
2. What is the beginning and end index of an array?
Ans:
The beginning index of an array is always 0 (zero) and end index is its size-1.
3. Can we store and access beyond the size of the array size?
Ans:
No, it will show undesired result.
4. Mention some advantages and disadvantages of Arrays.
Ans:
Multiple elements of Array can be sorted at the same time.
Using the index, we can access any element in O(1) time.

Assignments:

8.1 Write a C program to perform multiplication of two 3x3 matrices.


8.2 Write a C program to input elements in an array and find the sum using pointer as well as
display array using pointer.

FST, IFHE, Hyderabad


85
8.1 Write a C program to perform multiplication of two 3x3 matrices.
Solution:
Program File : Prg81.c
#include<stdio.h>
int main()
{
int mat1[3][3], mat2[3][3], mat3[3][3], sum=0, i, j, k;
printf("Enter first 3*3 matrix element: ");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
scanf("%d", &mat1[i][j]);
}
printf("Enter second 3*3 matrix element: ");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
scanf("%d", &mat2[i][j]);
}
printf("\nMultiplying two matrices...");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
sum=0;
for(k=0; k<3; k++)
sum = sum + mat1[i][k] * mat2[k][j];
mat3[i][j] = sum;
}
}
printf("\nMultiplication result of the two given Matrix is: \n");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
printf("%d\t", mat3[i][j]);
printf("\n");
}
return 0;
}

Output:
Enter first 3*3 matrix element:
618
257
147
Enter second 3*3 matrix element:
963
852
741

FST, IFHE, Hyderabad


86
Multiplying two matrices...
Multiplication result of the two given Matrix is:
118 73 28
107 65 23
90 54 18

8.2 Write a C program to input elements in an array and find the sum using
pointer as well as display array using pointer.
Solution:
Program File : Prg82.c
#include <stdio.h>
int main() {
int n, i,a[100],sum;
int *ptr;

printf("Enter the number of elements: ");


scanf("%d", &n);

ptr = a; // Assign the base address of the array to the pointer

printf("Enter the elements:\n");


for (i = 0; i < n; i++) {
scanf("%d", ptr + i); // Input elements using pointer arithmetic
}

sum=0;
for(i = 0; i < n; i++)
sum=sum+*(ptr+i);
printf("Array elements:");
for (i = 0; i < n; i++) {
printf("\n%d", *(ptr + i)); // Access and print elements using pointer dereferencing
}
printf("\nSum=%d",sum);
printf("\n");
return 0;
}
Output:
Enter the number of elements: 4
Enter the elements:
1
12
3
5
Array elements:
1

FST, IFHE, Hyderabad


87
12
3
5
Sum=21

FST, IFHE, Hyderabad


88
Week-8 Lab-2

8.3 Write a C program to swap values of two variables using pointers.

8.4 Write a C program to allocate a block of memory using Dynamic Memory Allocation
functions and perform the following.
i) accept and store the numbers
ii) find the minimum and maximum of the numbers
iii) find the average of the numbers

8.3 Write a C program to swap values of two variables using pointers.


Solution:
Program File : Prg83.c
#include <stdio.h>
void swap(int *x, int *y) {
int temp = *x;
*x = *y;
*y = temp;
}
int main() {
int a, b;

printf("Enter two numbers: ");


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

printf("Before swapping: a = %d, b = %d\n", a, b);

swap(&a, &b);

printf("After swapping: a = %d, b = %d\n", a, b);

return 0;
}
Output:
Enter two numbers: 5 10
Before swapping: a = 5, b = 10
After swapping: a = 10, b = 5

FST, IFHE, Hyderabad


89
8.4 Write a C program to allocate a block of memory using Dynamic Memory
Allocation functions and perform the following.
i) accept and store the numbers
ii) find the minimum and maximum of the numbers
iii) find the average of the numbers
Solution:
Program File : Prg84.c

#include <stdio.h>
#include <stdlib.h>

int main() {
int n, i, min, max, sum = 0;
int *ptr,*start=NULL;
float average;
printf("Enter the number of elements: ");
scanf("%d", &n);

// Allocate memory dynamically


ptr = (int *)malloc(n * sizeof(int));

if (ptr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
start=ptr;
//Accept and store elements
printf("Enter the elements:\n");
for (i = 1; i <= n; i++) {
scanf("%d", ptr++);
}
ptr=start;
// Find minimum and maximum
min = max = *ptr;
for (i = 1; i <= n; i++) {
if (*ptr < min) {
min = *ptr;
}
if (*ptr > max) {
max = *ptr;
}
sum += *ptr;
ptr++;

FST, IFHE, Hyderabad


90
}
// Calculate average
average = (float)sum / n;

printf("Minimum value: %d\n", min);


printf("Maximum value: %d\n", max);
printf("Average value: %.2f\n", average);

// Free the allocated memory


free(start);

return 0;
}

Output:
Enter the number of elements: 5
Enter the elements:
10
5
63
45
21
Minimum value: 5
Maximum value: 63
Average value: 28.80

FST, IFHE, Hyderabad


91
Week-9 Lab-1

6. Basic Viva Voce Questions and Answers

1. What is pointer in C?
Ans:
2. What is the difference between array and structure?

Ans:
A pointer can be used to store the memory address of other variables, functions, or even
other pointers. The use of pointers allows low-level memory access, dynamic memory
allocation, and many other functionality in C.
3. What are the types of function with respect to function definition?

Ans:
Function can be called either with or without arguments and might return values. They may or
might not return values to the calling functions. So the types of functions are
1. Function with no arguments and no return value
2. Function with no arguments and with return value
3. Function with argument and with no return value
4. Function with arguments and with return value

4. Differentiate call by value and call by reference function

Ans:
Call by Value involves passing the value as a copy to the function in which modifications
made within the function do not affect the original data but the Call by Reference passes the
memory address (reference) of the original data, allowing functions to directly modify the
original data.

Assignments:
9.1 Write a C program to store and print the roll no., name, age, address and marks of n
students using structure.
9.2 Write a C Program to enter the marks of 5 students in 3 courses Python, DAA, and JAVA
(each out of 100) using a structure named Marks having elements roll no., name,
Python_marks, DAA_marks and JAVA_marks and then display the percentage of each
student.

FST, IFHE, Hyderabad


92
9.1 Write a C program to store and print the roll no., name, age, address and
marks of n students using structure.
Solution:

Program File : Prg91.c

#include <stdio.h>
#include <string.h>
#define MAX_STUDENTS 100

struct Student {
int roll_no;
char name[50];
int age;
char address[100];
float marks;
};

int main() {
struct Student students[MAX_STUDENTS];
int i,n;
printf("Enter Number of Students (<100) :");
scanf("%d",&n);

// Input student information


for (i = 0; i < n; i++) {
printf("Enter details for student %d:\n", i + 1);
printf("Roll No.: ");
scanf("%d", &students[i].roll_no);
scanf("%*c"); // Consume newline character
printf("Name: ");
fgets(students[i].name, sizeof(students[i].name), stdin);
students[i].name[strcspn(students[i].name, "\n")] = '\0';//Remove newline character
printf("Age: ");
scanf("%d", &students[i].age);
scanf("%*c"); // Consume newline character
printf("Address: ");
fgets(students[i].address, sizeof(students[i].address), stdin);
students[i].address[strcspn(students[i].address, "\n")]='\0';//Remove newline character
printf("Marks: ");
scanf("%f", &students[i].marks);
}

FST, IFHE, Hyderabad


93
// Print student information
printf("\n* * * * * * * * Student Information: * * * * * * * * \n");
printf("\n------------------------------------------------------------------");
printf("\nRollNo\tName\t\tAge\tAddress\t\t\tMarks");
for (i = 0; i < n; i++) {
printf("\n%d\t",students[i].roll_no);
printf("%s\t\t", students[i].name);
printf("%d\t", students[i].age);
printf("%s\t\t", students[i].address);
printf("%.2f", students[i].marks);
}
printf("\n");
return 0;
}

Output:
* * * * * * * * Student Information: * * * * * * * *
------------------------------------------------------------------
RollNo Name Age Address Marks
101 Rajesh 21 Hyderabad 87.00
102 Ayan 20 Delhi 91.00
103 Shivam 21 Odisha 90.00
104 Mahesh 21 Chennai 85.00
105 Ganesh 19 AP 93.00

FST, IFHE, Hyderabad


94
9.2 Write a C Program to enter the marks of 5 students in 3 courses Python,
DAA, and JAVA (each out of 100) using a structure named Marks having
elements roll no., name, Python_marks, DAA_marks and JAVA_marks and
then display the percentage of each student.
Solution:
Program File : Prg92.c

#include <stdio.h>
#define SIZE 5
struct Marks {
int python;
int daa;
int java;
};

struct Students {
int roll_no;
char name[50];
struct Marks mark;
};

int main() {
struct Students students[SIZE];
int i;
float percentage;

for (i = 0; i < SIZE; i++) {


printf("Enter details for student %d:\n", i + 1);
printf("Roll No.: ");
scanf("%d", &students[i].roll_no);
scanf("%*c"); // Consume newline character
printf("Name: ");
scanf("%s", students[i].name);
printf("Python Marks: ");
scanf("%d", &students[i].mark.python);
printf("DAA Marks: ");
scanf("%d", &students[i].mark.daa);
printf("Java Marks: ");
scanf("%d", &students[i].mark.java);
}
printf("\nStudent Details and Percentage:\n");
printf("\n---------------------------------");
for (i = 0; i < SIZE; i++) {

FST, IFHE, Hyderabad


95
percentage=(((float)(students[i].mark.python + students[i].mark.daa +
students[i].mark.java) / 300) * 100);
printf("\nRoll No.: %d\n", students[i].roll_no);
printf("Name: %s\n", students[i].name);
printf("Python Marks: %d\n", students[i].mark.python);
printf("DAA Marks: %d\n", students[i].mark.daa);
printf("Java Marks: %d\n", students[i].mark.java);
printf("Percentage: %.2f%%\n", percentage);
printf("\n---------------------------------");
}
printf("\n");
return 0;
}

Output:
Enter details for student 1:
Roll No.: 111
Name: Amiya
Python Marks: 89
DAA Marks: 88
Java Marks: 96
Enter details for student 2:
Roll No.: 222
Name: Rameya
Python Marks: 78
DAA Marks: 98
Java Marks: 85
Enter details for student 3:
Roll No.: 333
Name: Rupa
Python Marks: 75
DAA Marks: 58
Java Marks: 69
Enter details for student 4:
Roll No.: 444
Name: Narendra
Python Marks: 45
DAA Marks: 59
Java Marks: 68
Enter details for student 5:
Roll No.: 555
Name: Vamshi
Python Marks: 88
DAA Marks: 77
Java Marks: 66

FST, IFHE, Hyderabad


96
Student Details and Percentage:
---------------------------------
Roll No.: 111
Name: Amiya
Python Marks: 89
DAA Marks: 88
Java Marks: 96
Percentage: 91.00%

---------------------------------
Roll No.: 222
Name: Rameya
Python Marks: 78
DAA Marks: 98
Java Marks: 85
Percentage: 87.00%

---------------------------------
Roll No.: 333
Name: Rupa
Python Marks: 75
DAA Marks: 58
Java Marks: 69
Percentage: 67.33%

---------------------------------
Roll No.: 444
Name: Narendra
Python Marks: 45
DAA Marks: 59
Java Marks: 68
Percentage: 57.33%

---------------------------------
Roll No.: 555
Name: Vamshi
Python Marks: 88
DAA Marks: 77
Java Marks: 66
Percentage: 77.00%

---------------------------------

FST, IFHE, Hyderabad


97
Week-9 Lab-2
Assignments:

9.3 Write a C program that uses functions and structures to perform the followings.
i) Reading a complex number
ii) Displaying the complex number
iii) Addition of two complex numbers
iv) Multiplication of two complex numbers

9.4 Write a program to add two distances in inch-feet using structure. The values of the
distances are to be taken from the user. Display the sum.

9.5 Implement the above program 9.1 using a union.

9.3 Write a C program that uses functions and structures to perform the
followings.
i) Reading a complex number
ii) Displaying the complex number
iii) Addition of two complex numbers
iv) Multiplication of two complex numbers
Solution:

Program File : Prg93.c

#include <stdio.h>

struct Complex {
float real;
float imag;
};

void readComplex(struct Complex *c) {


printf("Enter real part: ");
scanf("%f", &c->real);
printf("Enter imaginary part: ");
scanf("%f", &c->imag);
}

FST, IFHE, Hyderabad


98
void dispComplex(struct Complex c) {
printf("%.2f + %.2fi\n", c.real, c.imag);
}

struct Complex addComplex(struct Complex c1, struct Complex c2) {


struct Complex result;
result.real = c1.real + c2.real;
result.imag = c1.imag + c2.imag;
return result;
}

struct Complex multiplyComplex(struct Complex c1, struct Complex c2) {


struct Complex result;
result.real = (c1.real * c2.real) - (c1.imag * c2.imag);
result.imag = c1.real * c2.imag + c1.imag * c2.real;
return result;
}

int main() {
struct Complex c1, c2, sum, product;

printf("Enter first complex number:\n");


readComplex(&c1);

printf("Enter second complex number:\n");


readComplex(&c2);

sum = addComplex(c1, c2);


product = multiplyComplex(c1, c2);

printf("Sum: ");
dispComplex(sum);

printf("Product: ");
dispComplex(product);

return 0;
}
Output:
Enter first complex number:
Enter real part: 2
Enter imaginary part: 3
Enter second complex number:
Enter real part: 4
Enter imaginary part: 5
Sum: 6.00 + 8.00i
Product: -7.00 + 22.00i

FST, IFHE, Hyderabad


99
9.4 Write a program to add two distances in inch-feet using structure. The
values of the distances are to be taken from the user. Display the sum.
Solution:
Program File : Prg94.c

#include <stdio.h>
struct Distance {
int feet;
float inches;
};

struct Distance addDistances(struct Distance d1, struct Distance d2) {


struct Distance result;
result.inches = d1.inches + d2.inches;
result.feet = d1.feet + d2.feet + (int)(result.inches / 12);
result.inches = result.inches - (result.feet - d1.feet - d2.feet) * 12;
return result;
}
void displayDistance(struct Distance d) {
printf("%d feet %.2f inches\n", d.feet, d.inches);
}

int main() {
struct Distance d1, d2, sum;

printf("Enter feet and inches for the first distance: ");


scanf("%d %f", &d1.feet, &d1.inches);

printf("Enter feet and inches for the second distance: ");


scanf("%d %f", &d2.feet, &d2.inches);

sum = addDistances(d1, d2);

printf("Sum of distances: ");


displayDistance(sum);

return 0;
}

FST, IFHE, Hyderabad


100
Output-1:
Enter feet and inches for the first distance: 5
4
Enter feet and inches for the second distance: 3
6
Sum of distances: 8 feet 10.00 inches

Output-2:
Enter feet and inches for the first distance: 5
4
Enter feet and inches for the second distance: 3
11
Sum of distances: 9 feet 3.00 inches

9.5 Implement the above program 9.1 using a union.


Solution:
Program File : Prg95.c

#include <stdio.h>
#include <string.h>
#define MAX_STUDENTS 100

union Student {
int roll_no;
char name[50];
int age;
char address[100];
float marks;
};

int main() {
union Student students[MAX_STUDENTS];
int i,n;
printf("Enter Number of Students (<100) :");
scanf("%d",&n);

// Input student information


for (i = 0; i < n; i++) {
printf("Enter details for student %d:\n", i + 1);
printf("Roll No.: ");
scanf("%d", &students[i].roll_no);
scanf("%*c"); // Consume newline character

FST, IFHE, Hyderabad


101
printf("Name: ");
fgets(students[i].name, sizeof(students[i].name), stdin);
students[i].name[strcspn(students[i].name, "\n")] = '\0'; // Remove newline character
printf("Age: ");
scanf("%d", &students[i].age);
scanf("%*c"); // Consume newline character
printf("Address: ");
fgets(students[i].address, sizeof(students[i].address), stdin);
students[i].address[strcspn(students[i].address, "\n")] = '\0'; // Remove newline character
printf("Marks: ");
scanf("%f", &students[i].marks);
}
// Print student information
printf("\n* * * * * * * * Student Information: * * * * * * * * \n");
printf("\n------------------------------------------------------------------");
printf("\nRollNo\tName\t\tAge\tAddress\t\t\tMarks");
for (i = 0; i < n; i++) {
printf("\n%d\t",students[i].roll_no);
printf("%s\t\t", students[i].name);
printf("%d\t", students[i].age);
printf("%s\t\t", students[i].address);
printf("%.2f", students[i].marks);
}
printf("\n");
return 0;
}

Output:
* * * * * * * * Student Information: * * * * * * * *
------------------------------------------------------------------
RollNo Name Age Address Marks
1117782016 1117782016 80.00
1117650944 1117650944 79.00
1119617024 1119617024 94.00

FST, IFHE, Hyderabad


102
Week-10 Lab-1

7. Basic Viva Voce Questions and Answers

1. What is the difference between structure and union?

Ans:
The main difference between a structure and a union is that a structure stores multiple data
types of different sizes, while union stores multiple data types of the same size in the same
location.
When the variables are declared in a structure, the compiler allocates memory to each
variables member. The size of a structure is equal or greater to the sum of the sizes of each
data member.
When the variable is declared in the union, the compiler allocates memory to the largest size
variable member. The size of a union is equal to the size of its largest data member size.
2. What is command line argument in C?

Ans:
Instead of invoking the input statement from inside the program, it is possible to pass data
from the command line to the main() function when the program is executed. These values
are called command line arguments.
Command-line arguments are the values given after the name of the program in the
command-line shell of Operating Systems. Command-line arguments are handled by the
main() function of a C program.
3. What is difference between character array and string in C?
Ans:
Character array is the array of characters but a String is an array of character ending with a
NULL character (“\0”).
4. What is macro in C and how to define a macro?
Ans:
A macro is a piece of code in a program that is replaced by the value of the macro. Macro is
defined by #define directive. Whenever a macro name is encountered by the compiler, it
replaces the name with the definition of the macro. Macro definitions need not be
terminated by a semi-colon(;).

FST, IFHE, Hyderabad


103
Assignments:

10.1 Write a C program to perform the following operations without using string handling
functions.
i) length of a given string ii) string copy

10.2 Write a C program to perform the following operations without using string handling
functions
i) compare two strings ii) concatenate two strings

10.1 Write a C program to perform the following operations without using


string handling functions.
i) length of a given string ii) string copy
Solution:

i) Length of a given String

Algorithm:
Step 1: SET length := 0
Step 2: PRINT Enter a string :
Step 3: READ str
Step 4: Repeat step 4.1 to 4.2 while str [ i ] ! = ' \ 0 '
Step 4.1: SET length := length + 1
Step 4.2: SET i := i + 1
End of while block
Step 5: PRINT length
Step 6: Stop

FST, IFHE, Hyderabad


104
Program File : Prg101.c

// length of a given string


#include <stdio.h>

int main() {
char str[100];
int length = 0, i;

printf("Enter a string: ");


scanf("%s", str);

while (str[i] != '\0') {


length++;
i++;
}

printf("Length of the string: %d\n", length);

return 0;
}

Output:
Enter a string: IcfaiTech
Length of the string: 9

ii) Sting Copy

Algorithm:
Step 1: PRINT Enter a string :
Step 2: READ str1
Step 3: Repeat Step 3.1 to 3.2 while str1 [ i ] ! = ' \ 0 ' ;
Step 3.1: SET str2 [ i ] := str1 [ i ]
Step 3.2: SET i := i + 1
End of for block
Step 4: SET str2 [ i ] := ' \ 0 '
Step 5: PRINT str2
Step 6: Stop

Program File : Prg102.c

// string copy
#include <stdio.h>
int main() {
char str1[100], str2[100];
int i;

FST, IFHE, Hyderabad


105
printf("Enter a string: ");
scanf("%s", str1);

for (i = 0; str1[i] != '\0'; i++) {


str2[i] = str1[i];
}
str2[i] = '\0';

printf("Copied string: %s\n", str2);

return 0;
}

Output:
Enter a string: IcfaiTech
Copied string: IcfaiTech

10.2 Write a C program to perform the following operations without using


string handling functions
i) compare two strings ii) concatenate two strings
Solution:

i) Compare two strings

Algorithm:
Step-1 : Read two strings as str1 and str2
Step-2 : Compare the two strings str1 & str2 by checking whether corresponding
characters of both str1 and str2 are equal, or first string is greater than the
second or the first string is less than the second string
Step-3 : Display equal if str1 and str2 same otherwise display not equal
Step-4 : Stop

Program File : Prg1021.c


// compare two strings
#include <stdio.h>

int main() {
char str1[100], str2[100];
int i;

printf("Enter the first string: ");


scanf("%s", str1);

FST, IFHE, Hyderabad


106
printf("Enter the second string: ");
scanf("%s", str2);

for (i = 0; str1[i] == str2[i] && str1[i] != '\0' && str2[i] != '\0'; i++);

if (str1[i] == str2[i]) {
printf("The strings are equal.\n");
}
else {
printf("The strings are different.\n");
}

return 0;
}

Output-1:
Enter the first string: IcfaiTech
Enter the second string: IcfaiTech
The strings are equal.

Output:2
Enter the first string: IcfaiTech
Enter the second string: IcfaiTch
The strings are different.

ii) concatenate two strings

Algorithm:
Step 1: PRINT Enter the first string :
Step 2: READ str1
Step 3: PRINT Enter the second string :
Step 4: READ str2
Step 5: Repeat step 5.1 to 5.2 while str1[ i ] ! = ' \ 0 ' ;
Step 5.1: SET result[ i ] := str1[ i ]
Step 5.2: SET i := i + 1
End of for block
Step 6: Repeat step 6.1 to 6.2 while str2[ j ] ! = ' \ 0 ' ;
Step 6.1: SET result[ i + j ] := str2[ j ]
Step 6.2: SET j := j + 1
End of for block
Step 7: SET result[ i + j ] := ' \ 0 '
Step 8: PRINT result
Step 9: Stop

FST, IFHE, Hyderabad


107
Program File : Prg1022.c

// concatenate two strings


#include <stdio.h>

int main() {
char str1[100], str2[100], result[200];
int i, j;

printf("Enter the first string: ");


scanf("%s", str1);

printf("Enter the second string: ");


scanf("%s", str2);

// Copy str1 to result


for (i = 0; str1[i] != '\0'; i++) {
result[i] = str1[i];
}

// Copy str2 to result after str1


for (j = 0; str2[j] != '\0'; j++) {
result[i + j] = str2[j];
}

result[i + j] = '\0';
printf("Concatenated string: %s\n", result);

return 0;
}
Output:
Enter the first string: Icfai
Enter the second string: Tech
Concatenated string: IcfaiTech

FST, IFHE, Hyderabad


108
Week-10 Lab-2
Assignments:
10.3 Write a C program to perform the following operations using string handling functions.
i) length of a given string ii) string copy
iii) compare two strings iv) concatenate two strings

10.4 Write a C program to count the number of lines, characters and words in a given text of a
given string without using string handling functions.

10.5 Write a C program to convert a given string from lowercase to uppercase without using
string handling functions.

10.3 Write a C program to perform the following operations using string


handling functions.
i) length of a given string ii) string copy
iii) compare two strings iv) concatenate two strings
Solution:

Program File : Prg103.c

#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100], str3[200];
int length;

printf("Enter the first string: ");


scanf("%s", str1);

printf("Enter the second string: ");


scanf("%s", str2);

// i) Length of the first string


length = strlen(str1);
printf("Length of the first string: %d\n", length);

// ii) String copy


strcpy(str3, str1);
printf("Copied string: %s\n", str3);

// iii) Compare two strings

FST, IFHE, Hyderabad


109
int compareResult = strcmp(str1, str2);
if (compareResult == 0) {
printf("The two strings are equal.\n");
}
else {
printf("The two strings are not equal.\n");
}

// iv) Concatenate two strings


strcat(str1, str2);
printf("Concatenated string: %s\n", str1);

return 0;
}

Output:
Enter the first string: Icfai
Enter the second string: Tech
Length of the first string: 5
Copied string: Icfai
The two strings are not equal.
Concatenated string: IcfaiTech

10.4 Write a C program to count the number of lines, characters and words in
a given text of a given string without using string handling functions.
Solution:
Program File : Prg104.c
#include <stdio.h>

int main() {
int ctr_char, ctr_word, ctr_line; // Variables to count characters, words, and lines
int c; // Variable to hold input characters
int flag; // Flag to track word boundaries

ctr_char = 0; // Initialize the count of characters


flag = ctr_line = ctr_word = 0; // Initialize flag and counts for words and lines

printf("Input a string to get number of characters, words and lines:\n");

// Loop to read characters until end-of-file (EOF) is encountered


while ((c = getchar()) != EOF) {

FST, IFHE, Hyderabad


110
++ctr_char; // Increment the count of characters
if (c == ' ' || c == '\t') {
flag = 0; // Reset the flag when a space or tab is encountered
}
else if (c == '\n') {
++ctr_line; // Increment the count of lines
flag = 0; // Reset the flag on a newline
}
else {
if (flag == 0) {
++ctr_word; // Increment count of words when a new word begins
}
flag = 1; // Set the flag to indicate a word is in progress
}
}
ctr_char = ctr_char - ctr_line; // subtract no. of lines to get actual no. of words

// Print the counts of characters, words, and lines


printf("\nNumber of Characters = %d", ctr_char);
printf("\nNumber of words = %d", ctr_word);
printf("\nNumber of lines = %d", ctr_line);
}

Output:
ICFAI Foundation for Higher Education
Donthanpally, Shankarapally Road
Hyderabad, India
501203

Press ^+d to stop and count…

Number of Characters = 91
Number of words = 11
Number of lines = 4

FST, IFHE, Hyderabad


111
10.5 Write a C program to convert a given string from lowercase to uppercase
without using string handling functions.
Solution:
Algorithm:
Step-1: PRINT Enter a string :
Step-2: READ str
Step-3: Repeat step 3.1 to 3.2 while str [ i ] ! = ' \ 0 ' ;
Step 3.1: If str [ i ] > = ' a ' and str [ i ] < = ' z ' then :
Step 3.1.1: SET str [ i ] := str [ i ] - 32
End of if block
Step 3.2: SET i := i + 1
End of for block
Step 4: PRINT str
Step 4: Stop

Program File : Prg105.c


#include <stdio.h>
int main() {
char str[100];
int i;

printf("Enter a string: ");


scanf("%s", str);

for (i = 0; str[i] != '\0'; i++) {


if (str[i] >= 'a' && str[i] <= 'z') {
str[i] = str[i] - 32;
}
}

printf("Uppercase string: %s\n", str);

return 0;
}

Output:
Enter a string: icfaiTech
Uppercase string: ICFAITECH

FST, IFHE, Hyderabad


112
Week-11 Lab-1

Assignments:

11.1 Write a C program to read input characters from user and write it to file. After that read
the content of the same file and display on screen.

11.2 Write a C program to implement copy command with the use of Command line
arguments. Like “mycopy source.txt destination.txt” should copy content of source file to
destination file.

11.1 Write a C program to read input characters from user and write it to file.
After that read the content of the same file and display on screen.
Solution:
Program File : Prg111.c

#include <stdio.h>
int main() {
FILE *fptr;
char filename[50];
char ch;

printf("Enter filename: ");


scanf("%s", filename);

// Create or open file in write mode


fptr = fopen(filename, "w");
if (fptr == NULL) {
printf("Error opening file!\n");
return 1;
}

printf("Enter characters (press Ctrl+D to end):\n");


while ((ch = getchar()) != EOF) {
fputc(ch, fptr);
}

fclose(fptr);

// Open file in read mode


fptr = fopen(filename, "r");
if (fptr == NULL) {
printf("Error opening file!\n");
return 1;

FST, IFHE, Hyderabad


113
}

printf("\nContents of the file:\n");


while ((ch = fgetc(fptr)) != EOF) {
printf("%c", ch);
}
fclose(fptr);

return 0;
}

Output:

Enter filename: Address.txt


Enter characters (press Ctrl+D to end):
Department of CSE & AIDS
Faculty of Science and Technology
ICFAI Foundation for Higher Education
Hyderabad, 501203

Contents of the file:

Department of CSE & AIDS


Faculty of Science and Technology
ICFAI Foundation for Higher Education
Hyderabad, 501203

11.2 Write a C program to implement copy command with the use of Command
line arguments. Like “mycopy source.txt destination.txt” should copy content
of source file to destination file.
Solution:
Program File : Prg112.c

#include <stdio.h>
int main(int argc, char *argv[]) {
FILE *source_file, *destination_file;
char ch;

if (argc != 3) {
printf("Usage: %s source_file destination_file\n", argv[0]);
return 1;
}

source_file = fopen(argv[1], "rb");

if (source_file == NULL) {

FST, IFHE, Hyderabad


114
printf("Error opening source file!\n");
return 1;
}

destination_file = fopen(argv[2], "wb");


if (destination_file == NULL) {
printf("Error creating destination file!\n");
fclose(source_file);
return 1;
}
while ((ch = fgetc(source_file)) != EOF) {
fputc(ch, destination_file);
}

fclose(source_file);
fclose(destination_file);

printf("File copied successfully!\n");

return 0;
}

Output:
prompt#./a.out Address.txt Location.txt
File copied successfully!

Prompt#cat Location.txt
Department of CSE & AIDS
Faculty of Science and Technology
ICFAI Foundation for Higher Education
Hyderabad, 501203

FST, IFHE, Hyderabad


115
Week-11 Lab-2

Assignments:

11.3 Write a C program to write integer numbers to a file. Read them back and find the
average of all numbers.

11.4 Write a program to copy one file to another. While doing so replace all lowercase
characters with their equivalent uppercase characters.

11.5 Write a C program to merge two files into a third file.

11.3 Write a C program to write integer numbers to a file. Read them back and
find the average of all numbers.
Solution:
Program File : Prg113.c

#include <stdio.h>

int main() {
FILE *fptr;
int n, i, num, sum = 0;
float average;

printf("Enter the number of integers: ");


scanf("%d", &n);

// Create or open file in write mode


fptr = fopen("Numbers.txt", "w");

if (fptr == NULL) {
printf("Error opening file!\n");
return 1;
}

printf("Enter %d integers:\n", n);


for (i = 0; i < n; i++) {
scanf("%d", &num);
fprintf(fptr, "%d\n", num);
sum += num;
}
fclose(fptr);

// Open file in read mode


fptr = fopen("Numbers.txt", "r");

FST, IFHE, Hyderabad


116
if (fptr == NULL) {
printf("Error opening file!\n");
return 1;
}
average = (float)sum / n;

printf("Average of numbers: %.2f\n", average);


fclose(fptr);

return 0;
}

Output:
Enter the number of integers: 5
Enter 5 integers:
10
2
8
16
5
Average of numbers: 8.20

11.4 Write a program to copy one file to another. While doing so replace all
lowercase characters with their equivalent uppercase characters.
Solution:
Program File : Prg114.c

#include <stdio.h>
#include<ctype.h>

int main(int argc, char *argv[]) {


FILE *source_file, *destination_file;
char ch;

if (argc != 3) {
printf("Usage: %s source_file destination_file\n", argv[0]);
return 1;
}

source_file = fopen(argv[1], "r");


if (source_file == NULL) {
printf("Error opening source file!\n");
return 1;

FST, IFHE, Hyderabad


117
}

destination_file = fopen(argv[2], "w");

if (destination_file == NULL) {
printf("Error creating destination file!\n");
fclose(source_file);
return 1;
}

while ((ch = fgetc(source_file)) != EOF) {


ch = toupper(ch);
fputc(ch, destination_file);
}

fclose(source_file);
fclose(destination_file);

printf("File copied and converted to uppercase successfully!\n");

return 0;
}
OUTPUT:
Prompt#./a.out Address.txt UpperAddress.txt
File copied and converted to uppercase successfully!

Prompt# cat Address.txt


Department of CSE & AIDS
Faculty of Science and Technology
ICFAI Foundation for Higher Education
Hyderabad, 501203

Prompt# cat UpperAddress.txt


DEPARTMENT OF CSE & AIDS
FACULTY OF SCIENCE AND TECHNOLOGY
ICFAI FOUNDATION FOR HIGHER EDUCATION
HYDERABAD, 501203

FST, IFHE, Hyderabad


118
11.5 Write a C program to merge two files into a third file.
Solution:
Program File : Prg115.c
#include <stdio.h>

int main(int argc, char *argv[]) {


FILE *file1, *file2, *mergedFile;
char ch;

if (argc != 4) {
printf("Usage: %s file1 file2 merged_file\n", argv[0]);
return 1;
}

file1 = fopen(argv[1], "rb");

if (file1 == NULL) {
printf("Error opening file1!\n");
return 1;
}

file2 = fopen(argv[2], "rb");

if (file2 == NULL) {
printf("Error opening file2!\n");
fclose(file1);
return 1;
}

mergedFile = fopen(argv[3], "wb");

if (mergedFile == NULL) {
printf("Error creating merged file!\n");
fclose(file1);
fclose(file2);
return 1;
}

// Copy contents of file1

while ((ch = fgetc(file1)) != EOF) {


fputc(ch, mergedFile);
}

// Copy contents of file2


while ((ch = fgetc(file2)) != EOF) {
fputc(ch, mergedFile);
}

FST, IFHE, Hyderabad


119
fclose(file1);
fclose(file2);
fclose(mergedFile);

printf("Files merged successfully!\n");


return 0;
}

OUTPUT:
Prompt# cat > file1
This is my first file.
This will be merged with second file.
Press ^ + d to Save

Prompt# cat > file2


This is my second file.
This will be merged with first file.
Press ^ + d to Save

Prompt# ./a.out file1 file2 mergefile


Files merged successfully!

Prompt# cat mergefile


This is my first file.
This will be merged with second file.
This is my second file.
This will be merged with first file.

FST, IFHE, Hyderabad


120
APPENDIX – I

Sl. Date of Experiment Details Page Faculty


No. Experiment No. Signature
1 27-08-2024 2.1 Display "Welcome to IFHE" 1

2 30-08-2024 2.2 Display Your Name, Address and City 3

and So on…

FST, IFHE, Hyderabad


121
Lab Evaluation Sheet
Date of Experiment: Time of Experiment:
Week No:
Sl. Enrolment Name of Student Viva Exec- Total Sign. of the
No. No. Voce ution (1M) Student
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

FST, IFHE, Hyderabad


122
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70

Signature for Faculty 1:


2:
3:

FST, IFHE, Hyderabad


123
FST, IFHE, Hyderabad
124

You might also like