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

COMPUTER PROGRAMMING LAB Manual

The document outlines the Computer Programming Lab course (ES101) for the academic year 2024-2025, detailing its objectives, program outcomes, syllabus, and evaluation scheme. The course focuses on structured programming concepts using the C language, covering topics such as Unix OS, algorithms, data types, functions, pointers, and file management. It also includes a session plan for lab exercises and specifies attendance and makeup policies.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

COMPUTER PROGRAMMING LAB Manual

The document outlines the Computer Programming Lab course (ES101) for the academic year 2024-2025, detailing its objectives, program outcomes, syllabus, and evaluation scheme. The course focuses on structured programming concepts using the C language, covering topics such as Unix OS, algorithms, data types, functions, pointers, and file management. It also includes a session plan for lab exercises and specifies attendance and makeup policies.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 138

COURSE : COMPUTER PROGRAMMING LAB

COURSE No : ES101
Semester :I

Instructor In-charge : Dr. Santosh Kumar Sahoo

Instructors : Mr. K Brahmanaidu

Dr. Dilip Kumar Murala

Dr. Srinivasa Rao D

Academic Year : 2024-2025

1
Program Outcomes
PO1 Engineering An ability to apply knowledge of mathematics (including probability,
knowledge statistics and discrete mathematics), science, and engineering for
solving Engineering problems and modeling
PO2 Problem analysis An ability to design, simulate and conduct experiments, as well as to
analyze and interpret data including hardware and software components
PO3 Design / An ability to design a complex system or process to meet desired
development of specifications and needs
solutions
PO4 Conduct An ability to identify, formulate, comprehend, analyze, design synthesis
investigations of of the information to solve complex engineering problems and provide
complex valid conclusions.
problems
PO5 Modern tool An ability to use the techniques, skills and modern engineering tools
usage necessary for engineering practice
PO6 The engineer and An understanding of professional, health, safety, legal, cultural and
society social responsibilities
PO7 Environment and The broad education necessary to understand the impact of engineering
sustainability solutions in a global, economic, environmental and demonstrate the
knowledge need for sustainable development.
PO8 Ethics Apply ethical principles, responsibility and norms of the engineering
practice
PO9 Individual and An ability to function on multi-disciplinary teams.
team work
PO10 Communication An ability to communicate and present effectively

PO11 Project An ability to use the modern engineering tools, techniques, skills and
management and management principles to do work as a member and leader in a team, to
finance manage projects in multi-disciplinary environments
PO12 Life-long A recognition of the need for, and an ability to engage in, to resolve
learning contemporary issues and acquire lifelong learning

2
Course No : ES101 Course Title : Computer Programing
Semester : I L T P C : 2-0-4-4

Instructor In-charge : Dr. Santosh Kumar Sahoo


Instructors : Mr. K Brahmanaidu,
Dr. Dilip Kumar Murala
Dr. Srinivasa Rao D
Course Objectives:
 To train rigorously in structured programming language concepts – in particular C
language and gear them towards problem solving skills.
 To gain exposure on open system UNIX OS.
 To code a given problem in c programming language by gaining knowledge on concepts
like Conditional statements, functions, pointers, structures, unions, Low level
programming and Files.

Computer Science a Structured Programming Approach using C, Behrouz A.


Text Book(T1)
Forouzan & Richard F. Gilberg, Cengage Learning Third Edition.
Reference Book(s)
R1 Programming with ANSI C, E. Balaguruswamy TMH, 5th Edition. 2011.
R2 Computer Fundamentals & C Programming, SUMITHABHA DAS, TMH.
R3 The C Programming Language, Kernigham and Richie, PHI 2nd Ed. 2002.

R4 Let us C, Yashwanth Kanethkar, BPB Publications, 8th Edition.


Programming with C Byron Gottfried, Schaum's Outlines Series TMH 3rd
R5
Ed.

Lecture-wise plan (Syllabus):


Lecture Learning Reference to
No. objectives Topics to be covered Text book
1 Unix OS Introduction to Unix Operating system and general- Class Notes
purpose utilities commands
2 Flowcharts & Concept of problem solving and algorithms. Class Notes
Algorithms
3 Overview of C History, Introduction, Basic structures of a C T1(Ch.2)
program, Compilation and Execution, Simple /R1(Ch.1)
Programs Execution with/without Errors
4-5 Introduction to C Identifiers, Keywords, Constants, Variables, , Data T1(Ch.2)
Language Types, Declarations, Assigning Values, Input/Output /R1(Ch.2)
etc.
6-7(L) Operators and Operators (Arithmetic, Relational, Logical, T1(Ch.3)/
Expressions Increment/Decrement, Bitwise etc.), Expressions, /R1(Ch.3)
Precedence and Associatively, Expression
Evaluation, Type Conversions.
8-9(L) Decision making Statements- Selection Statements (making decisions) T1(Ch.5)
and Branching – if, if else, nested if, else if ladder and switch /R1(Ch.5)

3
statements
10- Repetition for, while, do-while statements, Loop examples, T1(Ch.6)
14(L) Statements(loops) other statements related to looping – break, continue, /R1(Ch.6)
go to, Simple C Program examples.

15- Understanding Functions- Introduction to Structured Programming, T1(Ch.4 )


18(L) functions Functions- basics, user defined functions, inter /R1(Ch.9)
& User defined function communication (call by value, call by
function reference).
19-20 Understanding Standard functions. Storage classes-auto, register, T1(Ch.4 )
functions static, extern, scope rules, arrays to functions, /R1(Ch.9)
& User defined recursive functions, example C programs
function
21- Arrays Arrays– Basic concepts, one-dimensional arrays, two T1(Ch.8 )
24(L) – dimensional arrays, multidimensional arrays, C /R1(Ch.7)
Programming examples
25 Understanding Pointers – Introduction (Basic Concepts), pointers to T1(Ch. 9,10)
pointers & pointers, compatibility, Pointer Applications /R1(Ch.11)
Dynamic memory
allocation
26-28 Programming Arrays and Pointers, Pointer Arithmetic, memory T1(Ch.10)
with pointers allocation functions, array of pointers, pointers to /R1(Ch.11)
void, pointers to functions, command–line arguments
29 Understanding Introduction to structures and unions. T1(Ch.12 )
Structures and /R1(Ch.10)
unions
30 Characters and Strings – Concepts, C Strings, String Input / Output T1(Ch.11)
strings functions, string manipulation functions, string /data /R1(Ch.8)
conversion.
31- File Management Input and Output – Concept of a file, streams, text files T1(Ch.13)
32(L) and binary files, Differences between text and binary /R1(Ch.12)
files, State of a file, Opening and Closing files, file
input / output functions (standard library input / output
functions for files), file status functions (error
handling), Positioning functions.

4
Session plan for lab exercises

S.No List of experiments Date


Week-1 1. Understand Ubuntu WSL operating system on windows
2. cat with options, ls with options, mkdir, cd, rm, cp, mv, pwd.
3. Nano editor, gcc & ./a.out
Week-2 1.Write a C program to display "Welcome to IFHE" on the screen.
2.Write a C program to display Your Name, Address and City in
different lines.
3. Write a C program to find the area of a circle. (Hints : Area= PI *
r2)
4. Write a C program to enter marks of five subjects and calculate
total, average and percentage of marks.
5. Write a C program to convert days into years, weeks and days.
Week-3 1.Write a C program to convert the temperature in degree Centigrade
into Fahrenheit and vice versa. (Formula: C= (F-32)/1.8)
2.You are given total time in seconds. Convert it into Hour: Min:
Second format.
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
4.Write a C program to find out whether the character pressed through
the Keyboard is a digit or not (Use conditional operator only).
5.Write a C program to swap variable values of two variables using
following techniques.
a) Using a third temporary variable
b) Without using temporary variable
Week-4 1.Write a C program to find the maximum of given three numbers.
2.Write a C program to determine whether input number is Odd or
Even. Display appropriate message
3.Write a program that declares Class awarded for a given percentage
of marks, where mark = 70% = Distinction. Read percentage from
standard input.
4.Write a program that prints a multiplication table for a given number
and the number of rows in the table.
For example, for a number 5 and rows=3, the output should be:
5x1=5
5 x 2 = 10
5 x 3 = 15
5.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)
Week-5 1.Write a C program for designing a calculator using menu driven
Program?
2.Write a C program to input month number and print total number of
days in month using switch...case
3.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)

5
4.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. Write a C program to find the sum of first 100 natural numbers.
Week-6 1.Write a C program to find the sum of odd numbers and even
numbers between 1 to N (N is a given input number).
2.Write a C program to display the first 100 prime numbers.
3.Write a C program to find the sum of digits of the accepted number.
4.Write a C program to check whether the given number is palindrome
or not.
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 1.Write a C program to find the factorial of a given number.
2.Write a C program to find the Fibonacci numbers using a recursive
function
3.Write a C program to construct the following patterns
a) 1 b) *
12 **
123 ***
1234 ****
12345 *****
4.Write a C program to find both the largest and smallest number in a
list of integers.
5.Write a C program to perform the following
a) Addition of two 3 x 3 matrices
b) Multiplication of two 3x3 matrices.
Week-8 1.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
2.Write a C program to perform the following operations without
using string handling functions.
i) length of a given string ii) string copy
iii) compare two strings iv) concatenate two strings
3.Write a C program to count the number of lines, characters and
words in a given text a given string.
4.Write a C program to convert a given string from lowercase to
uppercase.
Week-9 1.Write a C program to input elements in an array and print array using
pointers.
2.Write a C program to compare two strings and concatenate two
strings using pointers.
3.Write a C program to swap values of two variables using pointers.
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

6
Week- 1. Write a C program that uses functions and structures to perform the
10 followings.
i) Reading a complex number
ii) Writing a complex number
iii) Addition of two complex numbers
iv) Multiplication of two complex numbers
2.Write a program to add two distances in inch-feet using structure.
The values of the distances is to be taken from the user.
3.Write a program to store and print the roll no., name, age, address
and marks of 15 students using.
4. 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.
5.Implement the above program using a union
Week- 1.Write a C program to read input characters from user and write it to
11 file. After that read the content of the same file and display on screen.
2.Write a C program to implement copy command with the use of
Command line arguments. Like mycopy source.txt destination.txt
Copies content of source file to destination file.
3.Write a C program to write integer numbers to a file. Read them
back
and find the average of all numbers.
4.Write a program to copy one file to another. While doing so replace
all lowercase characters with their equivalent uppercase characters.
5.Write a C program to merge two files into a third file.

Evaluation Scheme:
Component Duration Weightage Date(s) Syllabus Remarks
Test-I 1 Hour 15% 16th-20th Sept. 1-14(L)
2024*
Test-II 1 Hour 15% 21th -25th Oct. 15-24(L)
2024*
Mid Lab Exam (Lab 1 Hour 10% 30th Sept. - Lab Week 1 –
Test-1) 04th Oct. Week 5
2024*
End Lab Exam (Lab 1 Hour 10% 18th – 22nd Lab Week 6 –
Test-2) Nov. 2024* Week 10
NASSCOM 10% Before 4th
Certification Nov. 2024*
Comprehensive 3 Hours 40% 9th – 20th 1-32(L)
Exam. Dec* 2024
*as per the current academic calendar and may be changed later if required

Chamber Consultation Hours:


*To be announced Later
1. A Minimum of 75% attendance is compulsory for both Theory as well as Lab and failing to which a
student will not be allowed to appear for the evaluation components.

7
2. No MAKE UP will be granted without prior permission from the Instructor in charge. Only in genuine
cases, Makeup will be allowed at the discretion of I/C.
COURSE OUTCOMES:

COURSE OUTCOME EXPLANATION


CO1 : KNOWLEDGE Understand the fundamentals of UNIX operating system and
differentiate among different programming languages for problem
solving.
CO2 : Describe the way of execution and debug programs in C language.
COMPREHENSION
CO3 : APPLICATION Define, select, and compare data types, loops, functions to solve
mathematical and scientific problem.
CO4 : ANALYSIS Understand the dynamic behavior of memory by the use of pointers
CO5 : SYNTHESIS Design and develop modular programs using control structure,
selection structure and file.
CO6 : EVALUATION Design programs using various concepts of C programming
language like pointer, functions, dynamic memory allocation etc.

CO-PO MAPPING:

CO/PO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
CO1 2 3 3 2 1
CO2 3 3 3 2
CO3 3 3 2 2 2
CO4 3 3 2 2
CO5 2 2
CO6 2 2 2 2 2

The various correlation levels are:


● “1” – Slight (Low) Correlation
● “2” – Moderate (Medium) Correlation
● “3” – Substantial (High) Correlation
● “-” indicates there is no correlation.

GAPS IN THE SYLLABUS - TO MEET INDUSTRY/PROFESSION REQUIREMENTS:

SNO DESCRIPTION PROPOSED ACTIONS

1 Competitive Coding Students are encouraged to register in competitive coding


platforms like code chef, hacker rank

TOPICS BEYOND SYLLABUS/ADVANCED TOPICS/DESIGN:


S.No. ADVANCED TOPICS
1 Algorithmic representation of the concepts
2 Foundation for switching over to other programming languages

8
WEB SOURCE REFERENCES:
S.No. Web links
1 Introduction to programming in C, IIT Kanpur- https://nptel.ac.in/courses/106104128
2 Problem Solving through Programming in C, IIT Kharagpur -
https://nptel.ac.in/courses/106105171
3 Introductory C Programming Specialization
-https://www.coursera.org/specializations/c-programming

DELIVERY/INSTRUCTIONAL METHODOLOGIES:

  
BOARD STUD. ASSIGNMENT WEB RESOURCES

STUD. SEMINARS
 
ICT ENABLED CLASSES LCD

ASSESSMENT METHODOLOGIES-DIRECT:

  MINI/MAJOR PROJECTS
TESTS/COMPRE. EXAMS ASSIGNMENT

STUD. SEMINARS  
STUD. LAB PRACTICES STUD. VIVA

ASSESSMENT METHODOLOGIES-INDIRECT:

 
ASSESSMENT OF COURSE OUTCOMES STUDENT FEEDBACK ON FACULTY
(BY FEEDBACK, ONCE) (TWICE)

ASSESSMENT OF MINI/MAJOR PROJECTS OTHERS

9
Week-1 1. Understand Ubuntu WSL operating system on
windows
2. cat with options, ls with options, mkdir, cd, rm, cp,
mv, pwd.
3. Nano editor, gcc & ./a.out

10
1.1 Understand Ubuntu WSL operating system on windows.

Ubuntu on Windows Subsystem for Linux (WSL) allows you to run a full-fledged Ubuntu terminal
on Windows.
WSL is a compatibility layer for running Linux binary executables natively on Windows 10 and
Windows 11. It enables developers to use a Linux distribution (like Ubuntu) directly on their
Windows machine without needing a virtual machine or dual-boot setup.

Why use Ubuntu WSL?

Best of both worlds : Enjoy the power of Linux tools and the convenience of Windows.
Faster performance : Runs much quicker than other ways to use Linux on Windows.
Easy to set up : You can install Ubuntu from the Microsoft Store.
Access to Linux tools: Use popular Linux programs like Git, Python, and many others.
Work with Windows files: You can easily access and edit your Windows files from Ubuntu
WSL.

11
1.2 cat with options, ls with options, mkdir, cd, rm, cp, mv, pwd.

 The ‘cat’ command in Linux is used to display the contents of a file on the screen.
 It's like opening a file and reading its content.
 The name "cat" comes from "concatenate", as it can also be used to combine multiple
files into one.

 This command displays the contents of filename to the standard output (usually the
terminal).

 If the file does not exist, then the result will be “No such file or directory”

 The cat command with the > operator is used to create a new file or overwrite an existing
file with input from the standard input (typically the keyboard).

How it works:

1. Create a new file: The > symbol tells the system to create a new file with the specified
name.
2. Start typing: After you execute the command, your terminal will enter a new line. You
can start typing the content you want to add to the file.
3. Save the file: To save the file, press Ctrl+D. This signals the end of input and closes the
file.

12
cat command Common Options:
-n: Numbers the output lines.

-s: Squeezes multiple blank lines into a single blank line.

-b: Numbers non-empty output lines.

13
-E: Displays end-of-line characters as '$'.

Concatenating files: Combine multiple files into one:

‘cat’ command Summary


cat filename
cat > filename
cat –n filename
cat –s filename
cat –b filename
cat –e filename
cat file1 file2 >file3

14
ls command with options, mkdir, cd, rm, cp, mv, pwd

pwd command:
 The pwd command in Unix-like operating systems stands for "print working directory."
 It is used to display the current directory you are working in.

mkdir command:
 mkdir is a command used to create new directories (folders) in Linux and Unix-like
systems.
 It stands for "make directory."

cd command:
 cd stands for "change directory".
 It's used to navigate through your file system.

15
cd ..
Change to the Parent Directory

Change to Root Directory


cd /

cd ~
Navigates to the home directory, e.g., /home/username.

cd –
If you were previously in /var/log and are now in /home/username, this command will take you back to
/var/log.

16
cd command summary
cd directory_name
cd ..
cd /
cd ~
cd -

cp command:
cp stands for "copy".
It's used to create duplicates of files or directories.

This command copies source_file to destination_file.


Copies source_file to destination_file If destination_file does not exist, it is created; if it does exist, it is
overwritten.

17
Copy Multiple Files to a Directory
cp file1.txt file2.txt /path/to/directory/
Copies file1.txt and file2.txt to the specified directory.

Copy Directories: -r or --recursive

 Recursively copies the contents of a directory, including all its files and subdirectories.

cp -r source_directory/ destination_directory/

18
Interactive Mode: -i

 Prompts you before overwriting existing files.

cp -i file1.txt /path/to/directory/

Copy a file
cp source_file destination_file
Copy Multiple Files to a Directory

Copy Directories: -r or --recursive

Interactive Mode: -i

19
mv command:

mv stands for "move".


It's versatile command used to both move files or directories from one location to another and to rename
them.
mv source destination
 source: The file or directory you want to move or rename.
 destination: The new location or the new name for the file or directory.
Moving a file:

Renaming a file:
mv old_name.txt new_name.txt

Moving a directory:

Here it moves demo1 directory to demo2 directory

20
ls command with options
ls
This command lists the contents of the current directory.

-l: Lists files in a long format, providing details like permissions, owner, group, size, date, and time.

-a: Lists all files, including hidden ones (starting with a dot).

-R: Recursively lists subdirectories.

21
-t: Sorts files by modification time (newest first).

-r: Reverses the order of the listing.

rm Command: Removing Files and Directories

rm stands for "remove".

It's a command used to delete files and directories from your file system.

rm filename
This command removes the specified file named filename.

Interactive Mode: -i

 Prompts before every removal.

rm -i filename

22
Force Removal: -f

 Forces the removal without prompting for confirmation, even if the file is write-
protected.

rm -f filename

Recursive Removal: -r or -R

 Recursively removes directories and their contents.

rm -r directoryname

23
1.3 Nano editor, gcc & ./a.out
Nano Editor:
A simple text editor used to create and edit plain text files.

gcc Compiler
A C compiler used to translate C code into machine-readable executable files.

./a.out
Executes the default executable file created by the gcc compiler.

24
Week- 1.Write a C program to display "Welcome to IFHE" on the
2 screen.
2.Write a C program to display Your Name, Address and City
in different lines.
3. Write a C program to find the area of a circle. (Hints :
Area= PI * r2)
4. Write a C program to enter marks of five subjects and
calculate total, average and percentage of marks.
5. Write a C program to convert days into years, weeks and
days.

25
Instructions to write C Programs:

1) Create a directory to store the programs.


2) Change the pwd to new directory created in step1.
3) In command prompt, type nano filename.c (to open the file with the given filename)
4) Text editor will be open, there we need to write C code.
5) After step4, to exit press Ctrl+x
6) In command prompt, to compile the code use gcc filename.c
7) If there are no errors, to check the output use the command ./a.out

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

Algorithm

1. Start
2. Display "Welcome to IFHE"
3. Stop

Flowchart

Program:

To exit from Nano editor, Apply ctrl+x

27
To check the output use

./a.out

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

Algorithm

1. Start
2. Display "Name: ICFAI"
3. Display “Address: Donthanapally”
4. Display “City: Hyderabad”
5. Stop

Flowchart:

29
Program: info.c
#include <stdio.h>

int main() {
// Print name, address, and city on different lines
printf("Name: ICFAI\n");
printf("Address: Donthanapally\n");
printf("City: Hyderabad\n");

return 0;
}

OUTPUT:

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

Algorithm

1. Start
2. Declare variables: radius, area
3. Initialize: Define PI as 3.14159
4. Input: Prompt the user to enter the radius of the circle
5. Calculate: Compute the area using the formula area = PI * radius * radius
6. Output: Display the calculated area
7. Stop

Flowchart

31
Program: area_of_circle.c
#include <stdio.h>

int main() {
// Declare variables
float radius, area;
const float PI = 3.14159;

// Input: Prompt the user to enter the radius


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

// Calculate the area


area = PI * radius * radius;

// Output: Display the area


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

return 0;
}

OUTPUT:

32
2.4 Write a C program to enter marks of five subjects and calculate total, average and
percentage of marks.

Algorithm:

1. Start
2. READ eng, phy, chem, math,comp
3. Calculate
total = eng + phy + chem + math + comp;
average = total / 5.0;
percentage = (total / 500.0) * 100;
4. Display total,average,percentage
5. Stop

Flowchart:

33
Program: marks.c

/**
* C program to calculate total, average and percentage of five subjects
*/

#include <stdio.h>

int main()
{
float eng, phy, chem, math, comp;
float total, average, percentage;

/* Input marks of all five subjects */


printf("Enter marks of five subjects: \n");
scanf("%f%f%f%f%f", &eng, &phy, &chem, &math, &comp);

/* Calculate total, average and percentage */


total = eng + phy + chem + math + comp;
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:

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

Algorithm
1. Start
2. READ days
3. CALCULATE
years = days/365; // Calculate years
weeks = (days % 365)/7; // Calculate weeks
days = days - ((years*365) + (weeks*7)); //remaining days
4. DISPLAY years, weeks, days
5. STOP

FLOWCHART:

35
Program: days.c

#include <stdio.h>

int main()
{
int days, years, weeks;
printf("Enter total no.of days : ");
scanf("%d",&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:

36
Week- 1.Write a C program to convert the temperature in degree
3 Centigrade into Fahrenheit and vice versa. (Formula: C= (F-
32)/1.8)

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

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

4.Write a C program to find out whether the character pressed


through the Keyboard is a digit or not (Use conditional operator
only).

5.Write a C program to swap variable values of two variables


using following techniques.
a) Using a third temporary variable
b) Without using temporary variable

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

Algorithm: To convert temperature from degree celsius to fahrenheit


1. START
2. READ temperature in celsius
3. COMPUTE
fahrenheit = (celsius * 9 / 5) + 32
4. DISPLAY fahrenheit
5. STOP

FLOWCHART: To convert temperature from degree celsius to Fahrenheit

38
Program: temperature.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:

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

Algorithm:

1. START
2. READ sec
3. SET h := ( sec / 3600 )
4. SET m := ( sec - ( 3600 * h ) ) / 60
5. SET s := ( sec - ( 3600 * h ) - ( m * 60 ) )
6. PRINT h , m , s
7. RETURN 0
8. STOP

40
Program: time.c

#include <stdio.h>
int main() {
int sec, h, m, s; // 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


h = (sec/3600);
m = (sec -(3600*h))/60;
s = (sec -(3600*h)-(m*60));

// Print the time in format H:M:S


printf("H:M:S - %d:%d:%d\n",h,m,s);

return 0;
}

OUTPUT:

41
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

Algorithm:
1. STARTSTEP
2. Get the two values required numbers.
3. Check arithmetic operators result.
4. apply relational, logical, increment, decrement, Bitwise operators and find the result.
5. STOP

42
Program: operators.c
#include<stdio.h>
void main( ){
int a,b;
printf("enter the values of a and b\n");
scanf("%d%d",&a,&b);
printf("the arithmetic operators result is %d %d %d %d\n", a+b,a-b,a*b,a/b);
printf("the relational operators result is %d %d %d %d\n", a>b,a<b,a>=b,a<=b);
printf("the logical operators result is %d %d %d %d\n", a&&b,a||b,!a, !b);
printf("the increment operator result is %d %d %d %d\n",a++,++a,b++,++b);
printf("the decrement operator result is %d %d %d %d\n",a--,--a,b--,--b);
printf("the bitwise AND operator result is %d\n",a&b);
printf("the bitwise OR operator result is %d\n",a|b);
printf("the bitwise NOT operator result is %d\n",a^b);
}

OUTPUT:

43
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).

ASCII value ranges-

For capital alphabets 65 – 90


For small alphabets 97 – 122
For digits 48 – 57

Algorithm:

Begin
Step 1: PRINT Enter a Character \ n
Step 2: READ c
Step 3: SET isDigit := ( ( c > = ' 0 ' ) & & ( c < = ' 9 ' ) ) ? 1 : 0
Step 4: if isDigit = 1 then :
Step 1: PRINT c
End of if block
Step 5: else :
Step 1: PRINT c
End of else block
Step 6: RETURN 0
End

44
Program: digit.c

#include<stdio.h>
int main() {
char c;
int isDigit;

printf("Enter a Character\n");
scanf("%c", &c);

/* Check, If input character is digit */


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

if(isDigit == 1)
printf("%c is Digit\n", c);
else
printf("%c is Not a Digit\n", c);

return 0;
}

OUTPUT:

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

Algorithm:
Begin
Step 1: PRINT Enter first number :
Step 2: READ first
Step 3: PRINT Enter second number :
Step 4: READ second
Step 5: SET temp := first
Step 6: SET first := second
Step 7: SET second := temp
Step 8: PRINT first number = % d \ n " , first
Step 9: PRINT second number = % d \ n " , second
Step 10: RETURN 0
End

46
Program: swap.c

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

// value of first is assigned to temp


temp = first;

// value of second is assigned to first


first = second;

// value of temp (initial value of first) is assigned to second


second = temp;

printf("\nAfter swapping, first number = %d\n", first);


printf("After swapping, second number = %d\n", second);
return 0;
}

OUTPUT:

47
Program: swapWithoutTemp.c

Algorithm:
Begin
Step 1: PRINT Enter first number :
Step 2: READ first
Step 3: PRINT Enter second number :
Step 4: READ second
Step 5: SET first := first + second
Step 6: SET second := first - second
Step 7: SET first := first - second
Step 8: PRINT first number = % d \ n " , first
Step 9: PRINT second number = % d \ n " , second
Step 10: RETURN 0
End

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

first = first + second;


second = first - second;
first = first - second;

printf("\nAfter swapping, first number = %d\n", first);


printf("After swapping, second number = %d\n", second);
return 0;
}

OUTPUT:

48
Week- 1.Write a C program to find the maximum of given three
4 numbers.

2.Write a C program to determine whether input number is Odd


or Even. Display appropriate message

3.Write a program that declares Class awarded for a given


percentage of marks, where mark = 70% = Distinction. Read
percentage from standard input.

4.Write a program that prints a multiplication table for a given


number and the number of rows in the table.
For example, for a number 5 and rows=3, the output should be:
5x1=5
5 x 2 = 10
5 x 3 = 15

5.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)

49
4.1 Write a C program to find the maximum of given three numbers.

Algorithm:

Begin
Step 1: PRINT Enter three numbers :
Step 2: READ a , b , c
Step 3: if a > = b and a > = c then :
Step 1: SET max := a
End of if block
Step 4: else :
Step 1: if b > = a and b > = c then :
Step 1: SET max := b
End of if block
End of else block
Step 5: else :
Step 1: SET max := c
End of else block
Step 6: PRINT max
Step 7: RETURN 0

End

50
PROGRAM: max.c

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

printf("Enter three numbers: ");


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

if (a >= b && a >= c) {


max = a;
} else if (b >= a && b >= c) {
max = b;
} else {
max = c;
}
printf("The maximum number is: %d\n", max);
return 0;
}

OUTPUT:

51
4.2 Write a C program to determine whether input number is Odd or Even. Display
appropriate message

Algorithm:

Begin

Step 1: PRINT Enter an integer :


Step 2: READ number
Step 3: if number % 2 = 0 then :
Step 1: PRINT number
End of if block
Step 4: else :
Step 1: PRINT number
End of else block
Step 5: RETURN 0

End

Program: evenOdd.c

#include <stdio.h>

int main() {
int number;

printf("Enter an integer: ");


scanf("%d", &number);

if (number % 2 == 0) {
printf("%d is even.\n", number);
} else {
printf("%d is odd.\n", number);
}

return 0;
}

OUTPUT:

52
4.3 Write a program that declares Class awarded for a given percentage of marks, where
mark = 70% = Distinction. Read percentage from standard input.

Algorithm:

Begin

Step 1: PRINT Enter percentage :


Step 2: READ percentage
Step 3: if percentage > = 70 then :
Step 1: PRINT Distinction \ n
End of if block
Step 4: else :
Step 1: if percentage > = 60 then :
Step 1: PRINT First Class \ n
End of if block
End of else block
Step 5: else :
Step 1: if percentage > = 50 then :
Step 1: PRINT Second Class \ n
End of if block
End of else block
Step 6: else :
Step 1: if percentage > = 40 then :
Step 1: PRINT Pass Class \ n
End of if block
End of else block
Step 7: else :
Step 1: PRINT Fail \ n
End of else block
Step 8: RETURN 0

End

53
Program: grade.c
#include <stdio.h>
int main() {
float percentage;

printf("Enter percentage: ");


scanf("%f", &percentage);

if (percentage >= 70) {


printf("Distinction\n");
} else if (percentage >= 60) {
printf("First Class\n");
} else if (percentage >= 50) {
printf("Second Class\n");
} else if (percentage >= 40) {
printf("Pass Class\n");
} else {
printf("Fail\n");
}

return 0;
}

OUTPUT:

54
4.4 Write a program that prints a multiplication table for a given number and the number
of rows in the table.
For example, for a number 5 and rows=3, the output should be:
5x1=5
5 x 2 = 10
5 x 3 = 15

Algorithm:

Begin
Step 1: PRINT Enter a number :
Step 2: READ number
Step 3: PRINT Enter the number of rows :
Step 4: READ rows
Step 5: Repeat step 1 to 2 while i < = rows ;
Step 1: PRINT number , i , number * i
Step 2: SET i := i + 1
End of for block
Step 5: RETURN 0
End

Program: multi_table.c
#include <stdio.h>

int main() {
int number, rows, i;

printf("Enter a number: ");


scanf("%d", &number);

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


scanf("%d", &rows);

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


printf("%d x %d = %d\n", number, i, number * i);
}

return 0;
}

55
OUTPUT:

56
4.5 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)

Algorithm:

Begin
Step 1: PRINT Enter a number :
Step 2: READ num
Step 3: SET lastDigit := num % 10
Step 4: SET temp := num
Step 5: Repeat step 1 to 1 while temp > = 10
Step 1: SET temp := temp / 10
End of while block
Step 5: SET firstDigit := temp
Step 6: SET sum := firstDigit + lastDigit
Step 7: PRINT sum
Step 8: RETURN 0
End

Program: sum_of_first_last_digits.c
#include <stdio.h>

int main() {
int num, temp, firstDigit, lastDigit, sum;

printf("Enter a number: ");


scanf("%d", &num);

// Find the last digit


lastDigit = num % 10;

// Find the first digit


temp = num;
while (temp >= 10) {
temp /= 10;
}
firstDigit = temp;

// Calculate the sum


sum = firstDigit + lastDigit;

printf("Sum of first and last digit: %d\n", sum);

return 0;
}

57
OUTPUT:

58
Week- 1.Write a C program for designing a calculator using menu
5 driven Program?
2.Write a C program to input month number and print total
number of days in month using switch...case
3.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)
4.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. Write a C program to find the sum of first 100 natural
numbers.

59
5.1 Write a C program for designing a calculator using menu driven Program?

Program: calc.c
#include <stdio.h>

int main() {
int num1, num2, choice;
float result;

do {
printf("\nCalculator Menu:\n");
printf("1. Addition\n");
printf("2. Subtraction\n");
printf("3. Multiplication\n");
printf("4. Division\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
result = num1 + num2;
printf("Sum = %.2f\n", result);
break;
case 2:
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
result = num1 - num2;
printf("Difference = %.2f\n", result);
break;
case 3:
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
result = num1 * num2;
printf("Product = %.2f\n", result);
break;
case 4:
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
if (num2 == 0) {
printf("Error: Division by zero\n");
} else {
result = (float)num1 / num2;
printf("Quotient = %.2f\n", result);
}
break;
case 5:
printf("Exiting calculator.\n");
break;
default:

60
printf("Invalid choice.\n");
}
} while (choice != 5);

return 0;
}

OUTPUT:

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

Program: month_days.c
#include <stdio.h>

int main() {
int month, year, days;

// Input month number


printf("Enter month number (1-12): ");
scanf("%d", &month);

// Input year to check for leap year in case of February


printf("Enter year: ");
scanf("%d", &year);

// Determine the number of days using switch...case


switch(month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
days = 31;
break;
case 4:
case 6:
case 9:
case 11:
days = 30;
break;
case 2:
// Check for leap year
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
days = 29;
} else {
days = 28;
}
break;
default:
printf("Invalid month number!\n");
return 1;
}

// Output the number of days in the month


printf("Total number of days: %d\n", days);

return 0;
}

63
OUTPUT:

64
5.3 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)

Algorithm:

Begin
Step 1: PRINT Enter a number :
Step 2: READ num
Step 3: Repeat step 1 to 3 while num ! = 0
Step 1: SET digit := num % 10
Step 2: SET freq [ digit ] + + ;
Step 3: SET num := num / 10
End of while block
Step 3: PRINT Digit Frequency \ n
Step 4: Repeat step 1 to 2 while i < 10 ;
Step 1: if freq [ i ] ! = 0 then :
Step 1: PRINT i , freq [ i ]
End of if block
Step 2: SET i := i + 1
End of for block
Step 4: RETURN 0
End

Program: digit_frequency.c
#include <stdio.h>

int main() {
int num, digit, freq[10] = {0};

printf("Enter a number: ");


scanf("%d", &num);

while (num != 0) {
digit = num % 10;
freq[digit]++;
num /= 10;
}

printf("Digit Frequency\n");
for (int i = 0; i < 10; i++) {
if (freq[i] != 0) {
printf("%d occurs %d times\n", i, freq[i]);
}
}

return 0;
}

65
OUTPUT:

66
5.4 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.

Program: decimal_binary_hexa.c
#include <stdio.h>

void decimalToBinary(int decimal) {


int binary[32];
int index = 0;

while (decimal > 0) {


binary[index] = decimal % 2;
decimal /= 2;
index++;
}

printf("Binary equivalent: ");


for (int i = index - 1; i >= 0; i--) {
printf("%d", binary[i]);
}
printf("\n");
}

void decimalToHexadecimal(int decimal) {


char hexadecimal[32];
int index = 0;

while (decimal > 0) {


int remainder = decimal % 16;
if (remainder < 10) {
hexadecimal[index] = 48 + remainder; // 48 is ASCII for '0'
} else {
hexadecimal[index] = 55 + remainder; // 55 is ASCII for 'A'
}
decimal /= 16;
index++;
}

printf("Hexadecimal equivalent: ");


for (int i = index - 1; i >= 0; i--) {
printf("%c", hexadecimal[i]);
}
printf("\n");
}

int main() {
int choice;
int number;

do {
// Display the menu
printf("\nMenu:\n");

67
printf("1. Convert decimal to binary\n");
printf("2. Convert decimal to hexadecimal\n");
printf("3. Exit\n");
printf("Enter your choice (1-3): ");
scanf("%d", &choice);

switch (choice) {
case 1:
// Convert decimal to binary
printf("Enter a decimal number: ");
scanf("%d", &number);
decimalToBinary(number);
break;
case 2:
// Convert decimal to hexadecimal
printf("Enter a decimal number: ");
scanf("%d", &number);
decimalToHexadecimal(number);
break;
case 3:
printf("Exiting the program...\n");
break;
default:
printf("Invalid choice! Please enter a valid option (1-3).\n");
}
} while (choice != 3);

return 0;
}

68
OUTPUT:

69
5.5 Write a C program to find the sum of first 100 natural numbers.

Algorithm:
Begin
Step 1: SET sum := 0
Step 2: PRINT Enter a positive integer :
Step 3: READ n
Step 4: if n < = 0 then :
Step 1: PRINT Invalid input. Please enter a positive integer. \ n
End of if block
Step 5: else :
Step 1: Repeat step 1 to 2 while i < = n ;
Step 1: SET sum := sum + i
Step 2: SET i := i + 1
End of for block
Step 1: PRINT n , sum
End of else block
Step 6: RETURN 0
End

#include <stdio.h>

int main() {
int n, sum = 0, i;

printf("Enter a positive integer: ");


scanf("%d", &n);

if (n <= 0) {
printf("Invalid input. Please enter a positive integer.\n");
} else {
for (i = 1; i <= n; i++) {
sum += i;
}
printf("Sum of first %d natural numbers: %d\n", n, sum);
}

return 0;
}

70
OUTPUT:

71
Week- 1.Write a C program to find the sum of odd numbers and even
6
numbers between 1 to N (N is a given input number).
2.Write a C program to display the first 100 prime numbers.
3.Write a C program to find the sum of digits of the accepted
number.
4.Write a C program to check whether the given number is
palindrome or not.
5.Write a C program to print the given number in word form of
digits.
(Ex input : 123, output is ONE TWO THREE )

72
6.1 Write a C program to find the sum of odd numbers and even numbers between 1 to N
(N is a given input number).

Algorithm:

Begin
Step 1: SET evenSum := 0, oddSum := 0
Step 2: PRINT Enter a positive integer :
Step 3: READ n
Step 4: if n < = 0 then :
Step 1: PRINT Invalid input. Please enter a positive integer. \ n
End of if block
Step 5: else :
Step 1: Repeat step 1 to 3 while i < = n ;
Step 1: if i % 2 = 0 then :
Step 1: SET evenSum := evenSum + i
End of if block
Step 2: else :
Step 1: SET oddSum := oddSum + i
End of else block
Step 3: SET i := i + 1
End of for block
Step 1: PRINT evenSum
Step 2: PRINT oddSum
End of else block
Step 6: RETURN 0
End
Program: sum_even_odd.c
#include <stdio.h>

int main() {
int n, i, evenSum = 0, oddSum = 0;

printf("Enter a positive integer: ");


scanf("%d", &n);

if (n <= 0) {
printf("Invalid input. Please enter a positive integer.\n");
} else {
for (i = 1; i <= n; i++) {
if (i % 2 == 0) {
evenSum += i;
} else {
oddSum += i;
}
}

printf("Sum of even numbers: %d\n", evenSum);


printf("Sum of odd numbers: %d\n", oddSum);
}

return 0;
}

73
OUTPUT:

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

Program: prime_numbers.c
#include <stdio.h>

int is_prime(int num) {


if (num <= 1) {
return 0;
}
if (num <= 3) {
return 1;
}
if (num % 2 == 0 || num % 3 == 0) {
return 0;
}
int i;
for (i = 5; i * i <= num; i += 6) {
if (num % i == 0 || num % (i + 2) == 0) {
return 0;
}
}
return 1;
}

int main() {
int n, count = 0, num = 2;

printf("Enter the value of n: ");


scanf("%d", &n);

printf("First %d prime numbers:\n", n);

while (count < n) {


if (is_prime(num)) {
printf("%d ", num);
count++;
}
num++;
}

printf("\n");

return 0;
}

75
OUTPUT:

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

Algorithm:

Begin
Step 1: SET sum := 0
Step 2: PRINT Enter a number :
Step 3: READ num
Step 4: Repeat step 1 to 3 while num ! = 0
Step 1: SET digit := num % 10
Step 2: SET sum := sum + digit
Step 3: SET num := num / 10
End of while block
Step 4: PRINT sum
Step 5: RETURN 0
End

Program: sum_digits.c
#include <stdio.h>

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

printf("Enter a number: ");


scanf("%d", &num);

while (num != 0) {
digit = num % 10;
sum += digit;
num /= 10;
}

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

return 0;
}

OUTPUT:

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

Algorithm:

Begin
Step 1: SET reversed := 0
Step 2: PRINT Enter an integer :
Step 3: READ num
Step 4: SET originalNum := num
Step 5: Repeat step 1 to 3 while num ! = 0
Step 1: SET remainder := num % 10
Step 2: SET reversed := reversed * 10 + remainder
Step 3: SET num := num / 10
End of while block
Step 5: if originalNum = reversed then :
Step 1: PRINT originalNum
End of if block
Step 6: else :
Step 1: PRINT originalNum
End of else block
Step 7: RETURN 0
End

Program: palindrome.c
#include <stdio.h>

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

printf("Enter an integer: ");


scanf("%d", &num);

originalNum = num;

while (num != 0) {
remainder = num % 10;
reversed = reversed * 10 + remainder;
num /= 10;
}

if (originalNum == reversed) {
printf("%d is a palindrome.\n", originalNum);
} else {
printf("%d is not a palindrome.\n", originalNum);
}

return 0;
}

78
OUTPUT:

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

Program: number_to_word.c
#include <stdio.h>

// Function to print the word corresponding to a digit


void printDigitInWords(int 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;
default: printf("INVALID "); break; // Just in case of unexpected input
}
}

int main() {
int number;

// Input the number


printf("Enter a number: ");
scanf("%d", &number);

// Handle negative numbers


if (number < 0) {
printf("NEGATIVE ");
number = -number; // Convert number to positive for processing
}

// Process each digit of the number


if (number == 0) {
printDigitInWords(0); // Special case for 0
} else {
int digit;
int temp = number;

// Calculate the number of digits in the number


int divisor = 1;
while (temp > 0) {
temp /= 10;
divisor *= 10;
}
divisor /= 10;

// Extract and print each digit in word form


while (divisor > 0) {

80
digit = number / divisor; // Get the most significant digit
printDigitInWords(digit);
number %= divisor; // Remove the most significant digit
divisor /= 10; // Move to the next digit
}
}

printf("\n");
return 0;
}

OUTPUT:

81
Week- 1.Write a C program to find the factorial of a given number.
7 2.Write a C program to find the Fibonacci numbers using a
recursive function
3.Write a C program to construct the following patterns
a) 1 b) *
12 **
123 ***
1234 ****
12345 *****
4.Write a C program to find both the largest and smallest
number in a list of integers.
5.Write a C program to perform the following
a) Addition of two 3 x 3 matrices
b) Multiplication of two 3x3 matrices.

82
7.1 Write a C program to find the factorial of a given number.

Algorithm:

Begin
Step 1: PRINT Enter a positive integer :
Step 2: READ number
Step 3: if number < 0 then :
Step 1: PRINT Factorial of a negative number doesn ' t exist. \ n
End of if block
Step 4: else :
Step 1: Repeat step 1 to 2 while i < = number ;
Step 1: SET factorial := factorial * i
Step 2: SET i := i + 1
End of for block
Step 1: PRINT number , factorial
End of else block
Step 5: RETURN 0
End

Program: factorial.c
#include <stdio.h>

int main() {
int number;
unsigned long long factorial = 1; // Using unsigned long long to handle large factorials

// Input the number


printf("Enter a positive integer: ");
scanf("%d", &number);

// Check if the input is negative


if (number < 0) {
printf("Factorial of a negative number doesn't exist.\n");
} else {
// Calculate the factorial
for (int i = 1; i <= number; i++) {
factorial *= i;
}

// Output the result


printf("Factorial of %d = %llu\n", number, factorial);
}

return 0;
}

83
OUTPUT:

84
7.2 Write a C program to find the Fibonacci numbers using a recursive function

Algorithm:

Begin
Step 1: if n < = 1 then :
Step 1: RETURN n
End of if block
Step 2: else :
Step 1: RETURN fibonacci ( n - 1 ) + fibonacci ( n - 2 )
End of else block
End procedure

Begin procedure main():-


Step 1: PRINT Enter the number of terms :
Step 2: READ n
Step 3: PRINT Fibonacci Series : \ n
Step 4: Repeat step 1 to 2 while i < n ;
Step 1: PRINT fibonacci ( i )
Step 2: SET i := i + 1
End of for block
Step 4: PRINT \ n
Step 5: RETURN 0
End

Program: fib_recursion.c
#include <stdio.h>

int fibonacci(int n) {
if (n <= 1) {
return n;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}

int main() {
int n, i;

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


scanf("%d", &n);

printf("Fibonacci Series:\n");
for (i = 0; i < n; i++) {
printf("%d ", fibonacci(i));
}
printf("\n");

return 0;
}

85
OUTPUT:

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

Algorithm:

Begin
Step 1: PRINT Enter the number of rows :
Step 2: READ rows
Step 3: Repeat step 1 to 2 while i < = rows ;
Step 1: Repeat step 1 to 2 while j < = i ;
Step 1: PRINT j
Step 2: SET := + 1
End of for block
Step 1: PRINT \ n
Step 2: SET := + 1
End of for block
Step 3: RETURN 0
End

Program: half_pyramid.c
#include <stdio.h>
int main() {
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; ++i) {
for (j = 1; j <= i; ++j) {
printf("%d ", j);
}
printf("\n");
}
return 0;
}

OUTPUT:

87
Program: full_pyramid.c
#include <stdio.h>
int main() {
int i, space, rows, k = 0;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; ++i, k = 0) {
for (space = 1; space <= rows - i; ++space) {
printf(" ");
}
while (k != 2 * i - 1) {
printf("* ");
++k;
}
printf("\n");
}
return 0;
}

OUTPUT:

88
7.4 Write a C program to find both the largest and smallest number in a list of integers.

Algorithm:
Begin
Step 1: PRINT Enter the number of elements :
Step 2: READ n
Step 3: PRINT n
Step 4: READ largest
Step 5: SET smallest := largest
Step 6: Repeat step 1 to 4 while i < n ;
Step 1: READ num
Step 2: if num > largest then :
Step 1: SET largest := num
End of if block
Step 3: else :
Step 1: if num < smallest then :
Step 1: SET smallest := num
End of if block
End of else block
Step 4: SET i := i + 1
End of for block
Step 6: PRINT largest
Step 7: PRINT smallest
Step 8: RETURN 0
End
Program: list_small_large.c
#include <stdio.h>

int main() {
int n, i, num, largest, smallest;

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


scanf("%d", &n);

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


scanf("%d", &largest); // Assume the first number as both largest and smallest
smallest = largest;

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


scanf("%d", &num);
if (num > largest) {
largest = num;
} else if (num < smallest) {
smallest = num;
}
}

printf("Largest number: %d\n", largest);


printf("Smallest number: %d\n", smallest);

return 0;
}

89
OUTPUT:

90
7.5 Write a C program to perform the following
a) Addition of two 3 x 3 matrices
b) Multiplication of two 3x3 matrices.

Algorithm:

Begin procedure main():-


Step 1: PRINT Enter elements of matrix A : \ n
Step 2: Repeat step 1 to 1 while i < 3 ;
Step 1: Repeat step 1 to 2 while j < 3 ;
Step 1: READ a [ i ] [ j ]
Step 2: SET j := j + 1
End of for block
Step 1: SET i := i + 1
End of for block
Step 2: PRINT Enter elements of matrix B : \ n
Step 3: Repeat step 1 to 1 while i < 3 ;
Step 1: Repeat step 1 to 2 while j < 3 ;
Step 1: READ b [ i ] [ j ]
Step 2: SET j := j + 1
End of for block
Step 1: SET i := i + 1
End of for block
Step 3: Repeat step 1 to 1 while i < 3 ;
Step 1: Repeat step 1 to 2 while j < 3 ;
Step 1: SET result [ i ] [ j ] := a [ i ] [ j ] + b [ i ] [ j ]
Step 2: SET j := j + 1
End of for block
Step 1: SET i := i + 1
End of for block
Step 3: PRINT Sum of matrices : \ n
Step 4: Repeat step 1 to 2 while i < 3 ;
Step 1: Repeat step 1 to 2 while j < 3 ;
Step 1: PRINT result [ i ] [ j ]
Step 2: SET j := j + 1
End of for block
Step 1: PRINT \ n
Step 2: SET i := i + 1
End of for block
Step 4: RETURN 0
End procedure

91
Program: add_matrices.c
#include <stdio.h>

int main() {
int a[3][3], b[3][3], result[3][3], i, j;

printf("Enter elements of matrix A:\n");


for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
scanf("%d", &a[i][j]);
}
}

printf("Enter elements of matrix B:\n");


for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
scanf("%d", &b[i][j]);
}
}

// Adding the matrices


for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
result[i][j] = a[i][j] + b[i][j];
}
}

printf("Sum of matrices:\n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}

return 0;
}

92
OUTPUT:

93
Algorithm: (Matrix_Multiplication)

Begin
Step 1: PRINT Enter elements of matrix A : \ n
Step 2: Repeat step 1 to 1 while i < 3 ;
Step 1: Repeat step 1 to 2 while j < 3 ;
Step 1: READ a [ i ] [ j ]
Step 2: SET j := j + 1
End of for block
Step 1: SET i := i + 1
End of for block
Step 2: PRINT Enter elements of matrix B : \ n
Step 3: Repeat step 1 to 1 while i < 3 ;
Step 1: Repeat step 1 to 2 while j < 3 ;
Step 1: READ b [ i ] [ j ]
Step 2: SET j := j + 1
End of for block
Step 1: SET i := i + 1
End of for block
Step 3: Repeat step 1 to 1 while i < 3 ;
Step 1: Repeat step 1 to 2 while j < 3 ;
Step 1: SET result [ i ] [ j ] := 0
Step 2: Repeat step 1 to 2 while k < 3 ;
Step 1: SET result [ i ] [ j ] + := a [ i ] [ k ] * b [ k ] [ j ]
Step 2: SET k := k + 1
End of for block
Step 2: SET j := j + 1
End of for block
Step 1: SET i := i + 1
End of for block
Step 3: PRINT Product of matrices : \ n
Step 4: Repeat step 1 to 2 while i < 3 ;
Step 1: Repeat step 1 to 2 while j < 3 ;
Step 1: PRINT result [ i ] [ j ]
Step 2: SET j := j + 1
End of for block
Step 1: PRINT \ n
Step 2: SET i := i + 1
End of for block
Step 4: RETURN 0
End

94
Program: mul_matrices.c
#include <stdio.h>

int main() {
int a[3][3], b[3][3], result[3][3], i, j, k;

printf("Enter elements of matrix A:\n");


for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
scanf("%d", &a[i][j]);
}
}

printf("Enter elements of matrix B:\n");


for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
scanf("%d", &b[i][j]);
}
}

// Multiplying matrices
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
result[i][j] = 0;
for (k = 0; k < 3; k++) {
result[i][j] += a[i][k] * b[k][j];
}
}
}

printf("Product of matrices:\n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}

return 0;
}

95
OUTPUT:

96
Week- 1.Write a C program to perform the following operations using
8 string handling functions.
i) length of a given string ii) string copy
iii) compare two strings iv) concatenate two strings
2.Write a C program to perform the following operations without
using string handling functions.
i) length of a given string ii) string copy
iii) compare two strings iv) concatenate two strings
3.Write a C program to count the number of lines, characters and
words in a given text a given string.
4.Write a C program to convert a given string from lowercase
to uppercase.

97
8.1 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

Program: stringHandlingFunctions.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


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:

98
8.2 Write a C program to perform the following operations without using string handling
functions.
i) length of a given string ii) string copy
iii) compare two strings iv) concatenate two strings

Algorithm:

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

Program: str_length.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:

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

Program: str_copy.c
// string copy

#include <stdio.h>

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

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:

100
Algorithm:
Begin
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 1 to 2 while str1 [ i ] ! = ' \ 0 ' ;
Step 1: SET result [ i ] := str1 [ i ]
Step 2: SET i := i + 1
End of for block
Step 5: Repeat step 1 to 2 while str2 [ j ] ! = ' \ 0 ' ;
Step 1: SET result [ i + j ] := str2 [ j ]
Step 2: SET j := j + 1
End of for block
Step 5: SET result [ i + j ] := ' \ 0 '
Step 6: PRINT result
Step 7: RETURN 0
End

Program: str_concatenate.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;
}

101
OUTPUT:

Program: str_compare.c
// compare two strings
#include <stdio.h>

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

printf("Enter the first string: ");


scanf("%s", str1);

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:

102
8.3 Write a C program to count the number of lines, characters and words in a given text a
given string.

Program: str_number_lwc.c
#include <stdio.h>

int main() {
long 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 and get number of characters, words and lines:\n");

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


while ((c = getchar()) != EOF) {
++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 the count of words when a new word begins
}
flag = 1; // Set the flag to indicate a word is in progress
}
}

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


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

OUTPUT:

103
8.4 Write a C program to convert a given string from lowercase to uppercase.

Algorithm:

Begin
Step 1: PRINT Enter a string :
Step 2: READ str
Step 3: Repeat step 1 to 2 while str [ i ] ! = ' \ 0 ' ;
Step 1: if str [ i ] > = ' a ' and str [ i ] < = ' z ' then :
Step 1: SET str [ i ] := str [ i ] - 32
End of if block
Step 2: SET i := i + 1
End of for block
Step 3: PRINT str
Step 4: RETURN 0
End

Program: lower_to_upper.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:

104
Week- 1.Write a C program to input elements in an array and print array
9 using pointers.
2.Write a C program to compare two strings and concatenate two
strings using pointers.
3.Write a C program to swap values of two variables using
pointers.
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

105
9.1 Write a C program to input elements in an array and print array using pointers.

Algorithm:

Begin
Step 1: PRINT Enter the number of elements :
Step 2: READ n
Step 3: SET ptr := arr
Step 4: PRINT Enter the elements : \ n
Step 5: Repeat step 1 to 2 while i < n ;
Step 1: READ ptr + i
Step 2: SET i := i + 1
End of for block
Step 5: PRINT Array elements : \ n
Step 6: Repeat step 1 to 2 while i < n ;
Step 1: PRINT * ( ptr + i )
Step 2: SET i := i + 1
End of for block
Step 6: PRINT \ n
Step 7: RETURN 0
End

Program: array_pointers.c
#include <stdio.h>

int main() {
int n, i;
int *ptr;

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


scanf("%d", &n);

int arr[n]; // Declare an array of size n

ptr = arr; // 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
}

printf("Array elements:\n");
for (i = 0; i < n; i++) {
printf("%d ", *(ptr + i)); // Access and print elements using pointer dereferencing
}
printf("\n");

return 0;
}

106
OUTPUT:

107
9.2 Write a C program to compare two strings and concatenate two strings using pointers.

Program: str_compare_ptr.c
#include <stdio.h>

int main()
{
char string1[50],string2[50],*str1,*str2;
int i,equal = 0;

printf("Enter The First String: ");


scanf("%s",string1);

printf("Enter The Second String: ");


scanf("%s",string2);

str1 = string1;
str2 = string2;

while(*str1 == *str2)
{
if ( *str1 == '\0' || *str2 == '\0' )
break;

str1++;
str2++;
}

if( *str1 == '\0' && *str2 == '\0' )


printf("\n\nBoth Strings Are Equal.\n");
else
printf("\n\nBoth Strings Are Not Equal.\n");
}
OUTPUT:

108
Program: str_concatenate_ptr.c
#include <stdio.h>
int main()
{
char string1[20]; // char array declaration
char string2[20]; // char array declaration
int i=0,j=0; // declaration of integer variables
char *str1; // declaration of char pointer
char *str2; // declaration of char pointer
str1=string1;
str2=string2;
printf("Enter the first string: ");
scanf("%s",string1);
printf("\nEnter the second string: ");
scanf("%s", string2);
while(string1[i]!='\0')
{

++str1;
i++;
}
while(string2[j]!='\0')
{
*str1=*str2;
str1++;
str2++;
j++;
}
printf("The concatenated string is %s\n",string1);

return 0;
}

OUTPUT:

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

Algorithm:

Begin procedure swap(int x , int y):-


Step 1: SET temp := * x
Step 2: SET x := * y
Step 3: SET y := temp
End procedure

Begin procedure main():-


Step 1: PRINT Enter two numbers :
Step 2: READ a , b
Step 3: PRINT b = % d \ n " , a , b
Step 4: PRINT b = % d \ n " , a , b
Step 5: RETURN 0
End procedure

Program: swap_ptr.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;
}

110
OUTPUT:

111
9.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

Program: dma.c
#include <stdio.h>
#include <stdlib.h>

int main() {
int n, i, min, max, sum = 0;
int *ptr;
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;
}

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


for (i = 0; i < n; i++) {
scanf("%d", ptr + i);
}

// Find minimum and maximum


min = max = *ptr;
for (i = 1; i < n; i++) {
if (*(ptr + i) < min) {
min = *(ptr + i);
}
if (*(ptr + i) > max) {
max = *(ptr + i);
}
sum += *(ptr + i);
}

// 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(ptr);

112
return 0;
}

OUTPUT:

113
Week- 1. Write a C program that uses functions and structures to perform
10 the followings.
i) Reading a complex number
ii) Writing a complex number
iii) Addition of two complex numbers
iv) Multiplication of two complex numbers
2.Write a program to add two distances in inch-feet using
structure. The values of the distances is to be taken from the user.
3.Write a program to store and print the roll no., name, age,
address and marks of 15 students using.
4. 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.
5.Implement the above program using a union

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

Algorithm:

An ADT with the name of Complex has been declared with the following fields: 'real' of type float,
'imag' of type float

Begin procedure readComplex(struct Complex c):-


Step 1: PRINT Enter real part :
Step 2: READ c -> real
Step 3: PRINT Enter imaginary part :
Step 4: READ c -> imag
End procedure

Begin procedure writeComplex(struct Complex c):-


Step 1: PRINT c.real , c.imag
End procedure
Step 2: SET result.real := c1.real + c2.real
Step 3: SET result.imag := c1.imag + c2.imag
Step 4: RETURN result
Step 5: SET result.real := c1.real * c2.real - c1.imag * c2.imag
Step 6: SET result.imag := c1.real * c2.imag + c1.imag * c2.real
Step 7: RETURN result

Begin procedure main():-


Step 1: PRINT Enter first complex number : \ n
Step 2: PRINT Enter second complex number : \ n
Step 3: SET sum := addComplex ( c1 , c2 )
Step 4: SET product := multiplyComplex ( c1 , c2 )
Step 5: PRINT Sum :
Step 6: PRINT Product :
Step 7: RETURN 0
End procedure

115
Program: complex_numbers.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);
}

void writeComplex(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: ");
writeComplex(sum);

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

return 0;
}

116
OUTPUT:

117
10.2 Write a program to add two distances in inch-feet using structure. The values of the
distances is to be taken from the user.

Algorithm:
An ADT with the name of Distance has been declared with the following fields: 'feet' of type int,
'inches' of type float
Step 1: SET result.inches := d1.inches + d2.inches
Step 2: SET result.feet := d1.feet + d2.feet + ( int ) ( result.inches / 12 )
Step 3: SET result.inches := result.inches - ( result.feet - d1.feet - d2.feet ) * 12
Step 4: RETURN result

Begin procedure displayDistance(struct Distance d):-


Step 1: PRINT d.feet , d.inches
End procedure

Begin procedure main():-


Step 1: PRINT Enter feet and inches for the first distance : "
End procedure
Step 2: READ d1.feet , d1.inches
Step 3: PRINT Enter feet and inches for the second distance : "
Step 4: READ d2.feet , d2.inches
Step 5: SET sum := addDistances ( d1 , d2 )
Step 6: PRINT Sum of distances :
Step 7: RETURN 0

Program: distance_structure.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);

118
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;
}

OUTPUT:

119
10.3 Write a program to store and print the roll no., name, age, address and marks of 15
students using structure.

Program: student_structures.c
#include <stdio.h>
#include <string.h>
#define MAX_STUDENTS 5

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

int main() {
struct Student students[MAX_STUDENTS];
int i;

// Input student information


for (i = 0; i < MAX_STUDENTS; 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);
}

// Print student information


printf("\nStudent Information:\n");
for (i = 0; i < MAX_STUDENTS; i++) {
printf("Roll No.: %d\n", students[i].roll_no);
printf("Name: %s", students[i].name);
printf("Age: %d\n", students[i].age);
printf("Address: %s\n", students[i].address);
printf("Marks: %.2f\n\n", students[i].marks);
}

return 0;
}

120
OUTPUT:

121
10.4 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.

Program: marks_percentage.c
#include <stdio.h>

struct Marks {
int roll_no;
char name[50];
int python_marks;
int daa_marks;
int java_marks;
};

int main() {
struct Marks students[5];
int i;

for (i = 0; i < 5; 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].python_marks);
printf("DAA Marks: ");
scanf("%d", &students[i].daa_marks);
printf("Java Marks: ");
scanf("%d", &students[i].java_marks);
}

printf("\nStudent Details and Percentage:\n");


for (i = 0; i < 5; i++) {
float percentage = (students[i].python_marks + students[i].daa_marks +
students[i].java_marks) / 3.0;
printf("Roll No.: %d\n", students[i].roll_no);
printf("Name: %s\n", students[i].name);
printf("Python Marks: %d\n", students[i].python_marks);
printf("DAA Marks: %d\n", students[i].daa_marks);
printf("Java Marks: %d\n", students[i].java_marks);
printf("Percentage: %.2f%%\n\n", percentage);
}

return 0;
}

122
OUTPUT:

icfai@DSR:~/week10$ gcc marks_percentage.c


icfai@DSR:~/week10$ ./a.out
Enter details for student 1:
Roll No.: 11
Name: DS
Python Marks: 80
DAA Marks: 70
Java Marks: 90
Enter details for student 2:
Roll No.: 22
Name: ABCD
Python Marks: 58
DAA Marks: 83
Java Marks: 48
Enter details for student 3:
Roll No.: 33
Name: POIU
Python Marks: 58
DAA Marks: 86
Java Marks: 66
Enter details for student 4:
Roll No.: 44
Name: TYU
Python Marks: 66
DAA Marks: 77
Java Marks: 88
Enter details for student 5:
Roll No.: 55
Name: YUIO
Python Marks: 66
DAA Marks: 55
Java Marks: 77

Student Details and Percentage:


Roll No.: 11
Name: DS
Python Marks: 80
DAA Marks: 70
Java Marks: 90
Percentage: 80.00%

Roll No.: 22
Name: ABCD
Python Marks: 58
DAA Marks: 83
Java Marks: 48
Percentage: 63.00%

Roll No.: 33
Name: POIU
Python Marks: 58
DAA Marks: 86

123
Java Marks: 66
Percentage: 70.00%

Roll No.: 44
Name: TYU
Python Marks: 66
DAA Marks: 77
Java Marks: 88
Percentage: 77.00%

Roll No.: 55
Name: YUIO
Python Marks: 66
DAA Marks: 55
Java Marks: 77
Percentage: 66.00%

124
10.5 Enter the marks of 5 students in 3 courses Python, DAA, and JAVA (each out of 100)
using a structure UNION named Marks having elements roll no., name, Python_marks,
DAA_marks and JAVA_marks and then display the percentage of each student.

Program: marks_percentage_union.c

#include <stdio.h>

union Marks {
int roll_no;
char name[50];
int python_marks;
int daa_marks;
int java_marks;
};

int main() {
union Marks students[5];
int i;

for (i = 0; i < 5; 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].python_marks);
printf("DAA Marks: ");
scanf("%d", &students[i].daa_marks);
printf("Java Marks: ");
scanf("%d", &students[i].java_marks);
}

printf("\nStudent Details and Percentage:\n");


for (i = 0; i < 5; i++) {
float percentage = (students[i].python_marks + students[i].daa_marks +
students[i].java_marks) / 3.0;
printf("Roll No.: %d\n", students[i].roll_no);
printf("Name: %s\n", students[i].name);
printf("Python Marks: %d\n", students[i].python_marks);
printf("DAA Marks: %d\n", students[i].daa_marks);
printf("Java Marks: %d\n", students[i].java_marks);
printf("Percentage: %.2f%%\n\n", percentage);
}

return 0;
}

125
OUTPUT:

icfai@DSR:~/week10$ gcc marks_percentage_union.c


icfai@DSR:~/week10$ ./a.out
Enter details for student 1:
Roll No.: 11
Name: AAA
Python Marks: 54
DAA Marks: 65
Java Marks: 76
Enter details for student 2:
Roll No.: 22
Name: BBB
Python Marks: 77
DAA Marks: 88
Java Marks: 66
Enter details for student 3:
Roll No.: 33
Name: CCC
Python Marks: 65
DAA Marks: 87
Java Marks: 49
Enter details for student 4:
Roll No.: 44
Name: GGG
Python Marks: 79
DAA Marks: 58
Java Marks: 94
Enter details for student 5:
Roll No.: 55
Name: HHHH
Python Marks: 75
DAA Marks: 75
Java Marks: 75

Student Details and Percentage:


Roll No.: 76
Name: L
Python Marks: 76
DAA Marks: 76
Java Marks: 76
Percentage: 76.00%

Roll No.: 66
Name: B
Python Marks: 66
DAA Marks: 66
Java Marks: 66
Percentage: 66.00%

Roll No.: 49
Name: 1
Python Marks: 49
DAA Marks: 49

126
Java Marks: 49
Percentage: 49.00%

Roll No.: 94
Name: ^
Python Marks: 94
DAA Marks: 94
Java Marks: 94
Percentage: 94.00%

Roll No.: 75
Name: K
Python Marks: 75
DAA Marks: 75
Java Marks: 75
Percentage: 75.00%

127
Week- 1.Write a C program to read input characters from user and write
11 it to file. After that read the content of the same file and display on
screen.
2.Write a C program to implement copy command with the use of
Command line arguments. Like mycopy source.txt destination.txt
Copies content of source file to destination file.
3.Write a C program to write integer numbers to a file. Read them
back
and find the average of all numbers.
4.Write a program to copy one file to another. While doing so
replace all lowercase characters with their equivalent uppercase
characters.
5.Write a C program to merge two files into a third file.

128
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.

Program: files1.c
#include <stdio.h>
#include <stdlib.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;
}

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


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

fclose(fptr);

return 0;
}

129
OUTPUT:

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

Program: copyFile.c

#include <stdio.h>
#include <stdlib.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) {
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;
}

131
OUTPUT:

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

Program: numbers_files.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");
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;
}

133
OUTPUT:

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

Program:lower_to_upper_files.c

#include <stdio.h>
#include <stdlib.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], "rb");


if (source_file == NULL) {
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) {


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

fclose(source_file);
fclose(destination_file);

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

return 0;
}

135
OUTPUT:

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

Program:merge_files.c

#include <stdio.h>
#include <stdlib.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);
}

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

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

return 0;
}

OUTPUT:

138

You might also like