TSP Lab Record With Solutions
TSP Lab Record With Solutions
DEPARTMENT OF
ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING
I YEAR – II SEMESTER
LAB RECORD
Name: Roll No :
Reg. No.: Section:
1
PANIMALAR ENGINEERING COLLEGE
(AN AUTONOMOUS INSTITUTION)
JAISAKTHI EDUCATIONAL TRUST
DEPARTMENT OF
BONAFIDE CERTIFICATE
This is a Certified Bonafide Record Book of Mr. /Ms. …..…………………………............
Register Number ................................................... Batch: 2023-2027, submitted for Anna
University Practical Examination held on ……………… in 23ES1212 - Technical Skill
Practices I during Feb- May 2024.
STAFF-IN-CHARGE
2
SYLLABUS
Module 1
INTRODUCTION TO PROGRAMMING
Module 2
CONTROL STRUCTURES AND LOOPING
Decision Making and Branching: introduction, simple if statement, if-else statement, nesting
of if…else statements, if-else ladder statement, switch-case statement, break, continue, goto-
label, return, exit(), Decision making and looping : while, for, do-while, nested-for.
Module 3
ARRAYS AND STRINGS
Arrays: introduction, declaration, initialization, One-dimension arrays, Two-dimensional
Arrays, Applications: Bubble sort, Linear search, Binary search, 2D matrix addition,
subtraction, multiplication, transpose. Strings: declaration and initialization of string
variables, reading strings from terminal, writing strings to screen, array of strings, string
operations, string library functions: strcpy, strcmp, strcat, strlen, strupr, strlwr, strrev.
Module 4
FUNCTIONS AND POINTERS
User-defined Functions: Need for functions, Elements of User-defined Functions, Definition
of Functions, Return Values and their Types, Function Calls, Function Declaration and
definition, types of functions, Passing Arrays to Functions, Recursion, Scope, Visibility and
Lifetime of variables. Pointers: Pointers - Pointer increment, Pointer arithmetic - Parameter
passing: Pass by value, Pass by reference, pointer and arrays, dynamic memory allocation with
malloc/calloc.
Module 5
STRUCTURES AND FILE MANAGEMENT
Structures and unions: Introduction, defining a structure, Declaration and initialization of
structures and unions, accessing members, array of structures, pointer to structure , structure
and functions, typedef , bit fields. File Management in C: Introduction, Defining and opening
a file, closing a file, Input/output and Error Handling on Files.
3
VISION AND MISSION OF THE INSTITUTION
Vision
Mission
4
INDEX
4 INTERMEDIATE LEVEL 18
PROGRAMS IN C – WEEK 4
5 INTERMEDIATE LEVEL 22
PROGRAMS IN C– WEEK 5
6 INTERMEDIATE LEVEL 28
PROGRAMS IN C– WEEK 6
SOLUTIONS 54
--
5
EX.NO.1 BASIC LEVEL PROGRAMS IN C - WEEK-1
DATE:
AIM:
To implement the following exercises in C language (use Iterations – loops, basic Arithmetic
operators, functions, typecasting).
Check the occurrence of a digit in a given number using a while loop.
Compute the perimeter and area of a rectangle, taking the length and breadth as input.
Convert a specified number of days into years, weeks, and remaining days. Note:
Leap years are ignored.
Write a program that accepts an employee's ID, total worked hours in a month, and the
amount received per hour. Print the employee's ID and salary (rounded to two decimal
places) for a particular month.
Determine whether a given number is even or odd, using a function.
Read an amount (integer value) and display the amount using the smallest possible
number of banknotes using typecasting.
EXERCISE-1
Write a C program to check the occurrence of a digit in a given number using a while loop.
Test case-1
Enter any number :: 443454
Enter the digit :: 4
Expected output-1
The occurrence of 4 is 4 times
Test case-2
Enter any number :: 667865
Enter the digit :: 6
Expected output-2
The occurrence of 6 is 3 times
Test case-3
Enter any number :: 1234519
Enter the digit :: 0
Expected output-3
The occurrence of 0 is 0 times
EXERCISE-2
Write a C program to compute the perimeter and area of a rectangle, taking the length
and breadth as input.
Test case-1
Enter length of the rectangle = 12.4
Enter breadth of the rectangle = 23.5
6
Expected output-1
Area of rectangle = 291.399994
Perimeter of rectangle = 582.799988
Test case-2
Enter length of the rectangle = 12
Enter breadth of the rectangle = 67
Expected output-2
Area of rectangle = 804.000000
Perimeter of rectangle = 1608.000000
Test case-3
Enter length of the rectangle = 34
Enter breadth of the rectangle = 78.9
Expected output-3
Area of rectangle = 2682.600098
Perimeter of rectangle = 5365.200195
EXERCISE-3
Write a C program to convert a specified number of days into years, weeks, and remaining
days. Note: Leap years are ignored.
Test case-1
Number of days : 5
Expected output-1
Years: 0
Weeks: 0
Days: 5
Test case-2
Number of days : 13291
Expected output-2
Years: 36
Weeks: 21
Days: 4
Test case-3
enter the number of days
600.23
Expected output-3
Years: 1
Weeks: 33
Days: 4
EXERCISE-4
Write a C program that accepts an employee's ID, total worked hours in a month, and the
amount received per hour. Print the employee's ID and salary (rounded to two decimal
places) for a particular month.
7
Test case-1
Input the Employees ID(Max. 10 chars): 121
Input the working hrs: 8
Salary amount/hr: 1400
Expected output-1
Employees ID = 121
Salary = Rs.11200.00
Test case-2
Input the Employees ID(Max. 10 chars): 125
Input the working hrs: 9
Salary amount/hr: 1700
Expected output-2
Employees ID = 125
Salary = Rs.15300.00
Test case-3
Input the Employees ID(Max. 10 chars): 137
Input the working hrs: 4
Salary amount/hr: 2000
Expected output-3
Employees ID = 137
Salary = Rs.8000.00
EXERCISE-5
Write a C program using a function to determine whether a given number is even or odd.
Test case-1
Input any number : 67.9
Expected output-1
The entered number is odd.
Test case-2
Input any number : 89.123
Expected output-2
The entered number is odd.
Test case-3
Input any number : 1298
Expected output-3
The entered number is even.
EXERCISE-6
Write a C program to read an amount (integer value) and display the amount using the
smallest possible number of banknotes (use typecasting).
Test case-1
Input the amount: 675.57
8
Expected output-1
There are:
6 Note(s) of 100
1 Note(s) of 50
1 Note(s) of 20
0 Note(s) of 10
1 Note(s) of 5
0 Note(s) of 2
0 Note(s) of 1
Test case-2
Input the amount: 454.667
Expected output-2
There are:
4 Note(s) of 100
1 Note(s) of 50
0 Note(s) of 20
0 Note(s) of 10
0 Note(s) of 5
2 Note(s) of 2
0 Note(s) of 1
Test case-3
Input the amount: 392.998
Expected output-3
There are:
3 Note(s) of 100
1 Note(s) of 50
2 Note(s) of 20
0 Note(s) of 10
0 Note(s) of 5
1 Note(s) of 2
0 Note(s) of 1
RESULT
Thus, C programs were written for the following exercises, executed, and results were verified
with the given test cases.
Check the occurrence of a digit in a given number using a while loop
Compute the perimeter and area of a rectangle, taking the length and breadth as input
Convert a specified number of days into years, weeks, and remaining days. Note: Leap
years are ignored.
Write a program that accepts an employee's ID, total worked hours in a month, and the
amount received per hour. Print the employee's ID and salary (rounded to two decimal
places) for a particular month.
Determine whether a given number is even or odd using a function
Read an amount (integer value) and display the amount using the smallest possible
number of banknotes (using typecasting).
9
EX.NO.2 BASIC LEVEL PROGRAMS IN C- WEEK-2
DATE:
AIM:
To implement the following exercises in C language – use (relation, relational, logical operators,
strings, arrays, unconditional statements)
Check whether a given character is a vowel or a consonant.
Find the maximum of 3 numbers.
Copy the content of one string, S1, into another string, S2, while removing characters
other than alphabets and spaces.
Read a string from the first line and print the middle three characters if the length of the
string is odd. Otherwise, print the middle two characters on the next line as output.
Read 'n' numbers into an array and calculate the sum of its elements.
Determine whether a given number is a power of two or not. If the number is a power of
two, print 'Yes'; otherwise, print 'No', using a break statement.
EXERCISE-1
Write a C program to check whether a given character is a vowel or a consonant.
Test case- 1
Input any alphabet : 5
Expected output-1
The character is not an alphabet.
Test case- 2
Input any alphabet : e
Expected output-2
The alphabet is a vowel.
Test case- 3
Input any alphabet : w
Expected output-3
The alphabet is a consonant.
EXERCISE-2
Write a C program to find the maximum of 3 numbers.
Test case-1
Enter three different numbers: 34
56
78
Expected output-1
78.0 is the largest number.
10
Test case-2
Enter three different numbers: 45.6
78.9
11.2
Expected output-2
78.9 is the largest number.
Test case-3
Enter three different numbers: 123 45.7 89.99
Expected output-3
123.0 is the largest number.
EXERCISE-3
Write a C program to copy the content of one string, S1, into another string, S2, while
removing characters other than alphabets and spaces.
Note
Maximum size of each string can be 1000
Read input string in the first line
Print output string in the second in the second
Constraints
Input string can contain alphabets, space, digits, and any other special characters
Output string must contain alphabets and space alone
Test case- 1
abcd 123 ***
Expected output-1
abcd
Test case- 2
123 io 56 nm
Expected output-2
io nm
Test case- 3
welcome to $$$$ india
Expected output-3
welcome to india
EXERCISE-4
Write a C program to read a string from the first line and print the middle three
characters if the length of the string is odd. Otherwise, print the middle two characters on
the next line as output.
Note
Read string in the first line
Print the middle characters in the second line
Constraint on inputs:
The input string can contain space also
11
Test case-1
malayalam
Expected output-1
aya
Test case-2
abcd
Expected output-2
bc
Test case-3
abcd efgh
Expected output-3
de
EXERCISE-5
Write a C program to read 'n' numbers into an array and calculate the sum of its elements.
Test case-1
Input the number of elements in the array :4
Input 4 elements in the array :
element - 0 : 76
element - 1 : 54
element - 2 : 32
element - 3 : 10
Expected output-1
Sum of all elements stored in the array is : 172
Test case-2
Input the number of elements in the array :4
Input 4 elements in the array :
element - 0 : 12.3
element - 1 : 56.7
element - 2 : 89.5
element - 3 : 34.2
Expected output-2
Sum of all elements stored in the array is : 191
Test case-3
Input the number of elements in the array :3
Input 3 elements in the array :
element - 0 : 11.1
element - 1 : 12
element - 2 : 22.22
Expected output-3
Sum of all elements stored in the array is : 45
12
EXERCISE-6
Write a C program to determine whether a given number is a power of two or not. If the
number is a power of two, print 'Yes'; otherwise, print 'No', using a break statement.
Note
Read N in the first line
Print output in the second
Test case- 1
16
Expected output-1
Yes
Test case- 2
12
Expected output-2
No
Test case- 3
128
Expected output-3
Yes
RESULT
Thus, C programs were written for the following exercises, executed, and results were verified
with the given test cases.
Check whether a given character is a vowel or a consonant.
Find the maximum of 3 numbers.
Copy the content of one string, S1, into another string, S2, while removing characters
other than alphabets and spaces.
Read a string from the first line and print the middle three characters if the length of the
string is odd. Otherwise, print the middle two characters on the next line as output.
Read 'n' numbers into an array and calculate the sum of its elements.
Determine whether a given number is a power of two or not. If the number is a power of
two, print 'Yes'; otherwise, print 'No', using a break statement.
13
EX.NO.3 BASIC LEVEL PROGRAMS IN C - WEEK-3
DATE:
AIM:
Get details about two students and display their details using structure members. This
program is used to store and access information such as name, roll number, and marks
Find the square of a number using a function.
Add two numbers using pointers
Print the first n natural numbers in reverse order using recursion
Print individual characters of a string in reverse order
Print numbers in a pyramid using a for loop
EXERCISE-1
Write a C program to get details about two students and display their details using
structure members. This program is used to store and access information such as name,
roll number, and marks.
Test case-1
Enter name, rollno and marks for stu1 : GANESH 101 99
Enter name, rollno and marks for stu2 : SIVA 203 87
Expected output-1
stu1 : GANESH 101 99
stu2 : SIVA 203 87
Test case-2
Enter name, rollno and marks for stu1 : anjali 244 86
Enter name, rollno and marks for stu2 : kumar 203 65
Expected output-2
stu1 : anjali 244 86
stu2 : kumar 203 65
Test case-3
Enter name, rollno and marks for stu1 : 1234 mahadev 98
Enter name, rollno and marks for stu2 : sankar $09 55
Expected output-3
stu1 : 1234 0 0
stu2 : mahadev 98 0
14
EXERCISE-2
Write a C program to find the square of a number using a function.
Test case-1
Input any number for square : 4
Expected output-1
The square of 4 is : 16.00
Test case -2
Input any number for square : 6.7
Expected output-2
The square of 6 is : 36.00
Test case -3
Input any number for square : $
Expected output-3
The square of 0 is : 0.00
EXERCISE-3
Write a C program to add two numbers using pointers.
Test case -1 :
Input the first number : 67
Input the second number : 89
Expected output-1
The sum of the entered numbers is : 156
Test case -2
Input the first number : 12345
Input the second number : 765
Expected output-2
The sum of the entered numbers is : 13110
Test case -3
Input the first number : 45 78
Input the second number :
Expected output-3
The sum of the entered numbers is : 123
EXERCISE-4
Write a C program to print the first n natural numbers in reverse order using recursion.
Test case -1
print n value :5
Expected output-1
5 4 3 2 1
15
Test case -2
print n value :10
Expected output-2
10 9 8 7 6 5 4 3 2 1
Test case -3
print n value :4.5
Expected output-3
4 3 2 1
EXERCISE-5
Write a C program to print individual characters of a string in reverse order.
Test case -1
Input the string : 56778
Expected output
The characters of the string in reverse are :
8 7 7 6 5
Test case -2
Input the string : welcome
Expected output
The characters of the string in reverse are :
e m o c l e w
Test case -3
Input the string : #$%%^^^
Expected output
The characters of the string in reverse are :
^ ^ ^ % % $ #
.
EXERCISE-6
Write a C Program to print numbers in a Pyramid using a for Loop.
Test case-1
enter the value of n
4
Expected output-1
1
2 3
4 5 6
7 8 9 10
Test case-2
enter the value of n
7
16
Expected output-2
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
Test case-3
enter the value of n
6
Expected output-3
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
RESULT
Thus, C programs were written for the following exercises, executed, and results were verified
with the given test cases
Get details about two students and display their details using structure members. This
program is used to store and access information such as name, roll number, and marks
Find the square of a number using a function.
Add two numbers using pointers.
Print the first n natural numbers in reverse order using recursion .
Print individual characters of a string in reverse order.
Print numbers in a pyramid using a for loop.
17
EX.NO.4 INTERMEDIATE LEVEL PROGRAMS IN C- WEEK-4
DATE:
AIM:
Write C programs to implement the following exercises (use -series, one dimensional array,
command line arguments, strings, files, user defined functions)
Find the sum of the series 1+11+111+1111+... up to n terms using a for loop, where 1
<= n <= 10
Count even and odd elements in an array.
Find the sum of N integer numbers using command line arguments.(Note: store the name
of the program as example.c)
Count the number of characters in a file.
Swap two strings using the strcpy() function.
Print all leap years from the start year 's' to the ending year 'd’.
EXERCISE-1
Write a C program to find the sum of the series 1+11+111+1111+... up to n terms using a for
loop, where 1 <= n <= 10.
Input and Output:
● Read value of number of terms n the first line.
● print the series .
● Print the sum of the series in the second line.
testcase-1
Enter the number of terms
3
Expected output-1
1 11 111
123
testcase-2
4
Expected output-2
1 11 111 1111
1234
testcase-3
Enter the number of terms
7
Expected output-3
1 11 111 1111 11111 111111 1111111
1234567
18
EXERCISE-2
Write a C program to count even and odd elements in an array.
Test Case -1
Enter size of the array: 5
Enter 5 elements in array :: 12 34 89 77 66
Expected output-1
Total even elements: 3
Total odd elements: 2
Test Case -2
Enter size of the array: 4
Enter 4 elements in array :: -1 -44 -77 -99
Expected output-2
Total even elements: 1
Total odd elements: 3
Test Case -3
Enter size of the array: -4
Enter -4 elements in array ::
Expected output-3
Total even elements: 0
Total odd elements: 0
.
EXERCISE-3
Write a C program to find the sum of N integer numbers using command line
arguments.(Note: store the name of the program as example.c)
testcase-1
example 12 20
expected output-1
arg[1] : 12
arg[2] : 22
Sum of all values: 34
testcase-2
example 12.5 22.5
expected output-2
arg[1] : 12
arg[2] :22
Sum of all values: 34
testcase-3
example a c
19
expected output-3
arg[1] : 0
arg[2] : 0
Sum of all values: 0
.
EXERCISE-4
Write a C program to count the number of characters in a file.
//create a file called read.txt and the contents of read.txt is india is my country
testcase-1
Type a file name : read.txt
expected output-1
File has 19 characters.
//create a file called file1.txt and the contents of the file is #include<stdio.h>
testcase-2
Type a file name : file1.txt
expected output-2
File has 18 characters.
testcase-2
Enter the First String: I AM IN CHENNAI
Enter the Second String: YOU ARE MY FRIEND
expected output-2
String before Swap:
First String = I AM IN CHENNAI Second String = YOU ARE MY FRIEND
String after Swap:
First String = YOU ARE MY FRIEND Second String = I AM IN CHENNAI
20
testcase-3
Enter the First String: 1234
Enter the Second String: 67890
expected output-3
String before Swap:
First String = 1234 Second String = 67890
String after Swap:
First String = 67890 Second String = 1234
.
EXERCISE-6
Write a C program to print all leap years from the start year 's' to the ending year 'd’.
testcase-1
Enter the value of starting year and ending year: 200 300
expected output-1
Leap years from 200 to 300:
204 208 212 216 220 224 228 232 236 240 244 248 252
256 260 264 268 272 276 280 284 288 292 296
testcase-2
Enter the value of starting year and ending year: 2000 2050
expected output-2
Leap years from 2000 to 2050:
2000 2004 2008 2012 2016 2020 2024 2028 2032 2036 2040 2044 2048
testcase-3
Enter the value of starting year and ending year: 1500 1600
expected output-3
Leap years from 1500 to 1600:
1504 1508 1512 1516 1520 1524 1528 1532 1536 1540 1544 1548 1552
1556 1560 1564 1568 1572 1576 1580 1584 1588 1592 1596 1600
RESULT
Thus, C programs were written for the following exercises, executed, and results were verified
with the given test cases.
Find the sum of the series 1+11+111+1111+….. upto n terms using for loop where Find
the sum of the series 1+11+111+1111+... up to n terms using a for loop, where 1 <= n
<= 10
Count even and odd elements in an array.
Find the sum of N integer numbers using command line arguments.(Note: store the name
of the program as example.c)
Count the number of characters in a file.
Swap two strings using the strcpy() function
Print all leap years from the start year 's' to the ending year 'd’.
21
EX.NO.5 INTERMEDIATE LEVEL PROGRAMS IN C - WEEK-5
DATE:
AIM:
Write C programs to implement the following exercises (use -patterns, loops, malloc(), typedef,
2D arrays, series)
Print the following N lines of pattern after reading value for N.
Find the Highest Common Factor (HCF) of given numbers using recursion.
Find the maximum of n numbers using pointers, utilizing the malloc() function.
Display a structure using the typedef keyword. The structure should contain fields for
name, id, age, and native.
Find the sum of an Arithmetic Progression (AP) series.
Print the transpose of a matrix.
EXERCISE-1
Write a C program to print the following N lines of pattern after reading value for N.
1
11
101
1001
10001
111111
Note
● Read N in the first line
● Print output in the rest of the lines
Constraint on inputs and output:
● N is non negative
● First and last lines contain sequence of 1 always
Sample Input -1
enter n value
2
Expected output-1
1
11
Sample Input -2
enter n value
3
Expected output-2
22
1
11
111
Sample Input- 3
enter n value
6
Expected output
1
11
101
1001
10001
111111
.
EXERCISE-2
Write a C program to find the Highest Common Factor (HCF) of given numbers using
recursion.
testcase-1
Enter Number 1: 34
Enter Number 2: 68
expected output-1
The Highest Common Factor is: 34
testcase-2
Enter Number 1: 1246
Enter Number 2: 6789
expected output-2
The Highest Common Factor is: 1
testcase-3
Enter Number 1: 14560.52
expected output-3(nil)
.
EXERCISE-3
Write a C program to find the maximum of n numbers using pointers, utilizing the
malloc() function.
testcase-1
How many numbers u want :: 5
Enter Number 1 :: 11
23
Enter Number 2 :: 2
Enter Number 3 :: 55
Enter Number 4 :: 77
Enter Number 5 :: 90
expected output-1
The Largest Number is 90
testcase-2
How many numbers u want :: 3
Enter Number 1 :: 778
Enter Number 2 :: 999
Enter Number 3 :: 234
expected output-2
The Largest Number is 999
testcase-3
How many numbers u want :: 3
Enter Number 1 :: 111
Enter Number 2 :: 99
Enter Number 3 :: 56
expected output-3
The Largest Number is 111
.
EXERCISE-4
Write a C program to display a structure using the typedef keyword. The structure should
contain fields for name, id, age, and native.
testcase-1
Enter empname, id, age and native
hithesh 101 18 chennai
expected output-1
Employee detail:
Name:hithesh
Age:18
id: 101
native: chennai
testcase-2
Enter empname, id, age and native
srikanth 102 19 vellore
24
expected output-2
Employee detail:
Name:srikanth
id:19
Age: 102
native: vellore
testcase-3
Enter empname, id, age and native
shankar 103 19 kanchipuram
expected output-3
Employee detail:
Name:shankar
id:19
Age: 103
native: kanchipuram
.
EXERCISE-5
Write a C program to find the sum of an Arithmetic Progression (AP) series.
testcase-1
Enter First Number of an A.P Series:
1
Enter the Total Numbers in this A.P Series:
5
Enter the Common Difference:
6
expected output-1
The Sum of Series A.P. :
1 + 7 + 13 + 19 + 25 = 65
testcase-2
Enter First Number of an A.P Series:
6
Enter the Total Numbers in this A.P Series:
6
Enter the Common Difference:
6
expected output-2
The Sum of Series A.P. :
6 + 12 + 18 + 24 + 30 + 36 = 126
testcase-3
Enter First Number of an A.P Series:
10
25
Enter the Total Numbers in this A.P Series:
10
Enter the Common Difference:
4
expected output-3
The Sum of Series A.P. :
10 + 14 + 18 + 22 + 26 + 30 + 34 + 38 + 42 + 46 = 280
EXERCISE-6
Write a C program to print the transpose of a matrix.
Testcase-1
Enter the number of rows and columns of the matrix:
2
2
Enter the elements of the matrix:
A[1][1] = 1
A[1][2] = 2
A[2][1] = 3
A[2][2] = 4
Expected output-1
Transpose of the matrix is:
1 3
2 4
Testcase-2
Enter the number of rows and columns of the matrix: 2
3
Enter the elements of the matrix:
A[1][1] = 11
A[1][2] = 22
A[1][3] = 33
A[2][1] = 44
A[2][2] = 55
A[2][3] = 66
Expected output-2
Transpose of the matrix is:
11 44
22 55
33 66
26
Testcase-3
Enter the number of rows and columns of the matrix: 1
3
Enter the elements of the matrix:
A[1][1] = 789
A[1][2] = 567
A[1][3] = 45
Expected output-3
Transpose of the matrix is:
789
567
45
RESULT
Thus, C programs were written for the following exercises, executed, and results were verified
with the given test cases
Print the following N lines of pattern after reading value for N.
Find the Highest Common Factor (HCF) of given numbers using recursion
Find the maximum of n numbers using pointers, utilizing the malloc() function.
Display a structure using the typedef keyword. The structure should contain fields for
name, id, age, and native.
Find the sum of an Arithmetic Progression (AP) series
Print the transpose of a matrix.
27
EX.NO.6 INTERMEDIATE LEVEL PROGRAMS IN C- WEEK-6
DATE:
AIM
To implement the following programs in C (use loops, recursion, structure, pointers, do-while
loop, header file)
Determine whether a given number is a perfect number or not. A positive number is said
to be a perfect number if it is equal to the sum of all its proper divisors. Proper divisors
include all the divisors of a number except the number itself.
Find the sum of array elements using recursion.
Concatenate two strings using pointers.
Add two distances in feet and inches using a structure.
Count the total number of alphabets, digits, and special characters in a string.
Calculate the sum of squares of digits using a do-while loop.
EXERCISE-1
Write a C program to determine whether a given number is a perfect number or not. A
positive number is said to be a perfect number if it is equal to the sum of all its proper
divisors. Proper divisors include all the divisors of a number except the number itself.
testcase-1
enter the number:
626
Expected output-1
626 is not a perfect number
28
testcase-2
enter the number:
496
Expected output-2
496 is a perfect number
testcase-3
enter the number:
8128
Expected output-3
8128 is a perfect number
.
EXERCISE-2
Write a C program to find the sum of array elements using recursion.
Test case-1
Enter size of the array: 5
Enter elements in the array: 1 2 3 4 5
Expected Output-1
Sum of array elements: 15
Test case-2
Enter size of the array: 8
Enter elements in the array: 1 2 3 4 5 6 7 8
Expected Output-2
Sum of array elements: 36
Test case-3
Enter size of the array: 10
Enter elements in the array: 1 2 3 4 5 6 7 8 9 10
Expected Output-3
Sum of array elements: 55
.
EXERCISE-3
Write a C program to concatenate two strings using pointers.
Testcase-1
Enter first string: WELCOME TO
Enter second string: PANIMALAR ENGG COLLEGE
Expected output-1
Concatenated string = WELCOME TO PANIMALAR ENGG COLLEGE
Testcase-2
Enter first string: today
29
Enter second string: holiday
Expected output-2
Concatenated string = todayholiday
Testcase-3
Enter first string: @@@
Enter second string: $$$
Expected output-3
Concatenated string = @@@$$$
.
EXERCISE-4
Write a C program to add two distances in feet and inches using a structure.
testcase-1
Enter first distance in feet & inches:23 45
Enter second distance in feet & inches:67 89
expected output-1
Total distance- Feet: 101, Inches: 2
testcase-2
Enter first distance in feet & inches:22 22
Enter second distance in feet & inches:33 33
expected output-2
Total distance- Feet: 59, Inches: 7
testcase-3
Enter first distance in feet & inches:10.2 5.2
Enter second distance in feet & inches:
expected output-3
Total distance- Feet: 10, Inches: 0
.
EXERCISE-5
Write a C program to count the total number of alphabets, digits, and special characters in
a string.
testcase-1
Enter any string: i love my country @#$% india 123
expected output-1
Alphabets = 19
Numbers = 3
Special Characters = 4
testcase-2
Enter any string: my name is !@#$ kumar 789
30
expected output-2
Alphabets = 13
Numbers = 3
Special Characters = 4
testcase-3
Enter any string: 12345 abcde ************(((((
expected output-3
Alphabets = 5
Numbers = 5
Special Characters = 17
.
EXERCISE-6
Write a C program to calculate the sum of squares of digits using a do-while loop.
Testcase-1
Input a positive integer: 6
expected output-1
Sum of the squares of each digit: 36
Testcase-2
Input a positive integer: 100
expected output-1
Sum of the squares of each digit: 1
Testcase-3
Input a positive integer: 234
expected output-1
Sum of the squares of each digit: 29
RESULT
Thus, C programs were written for the following exercises, executed, and results were verified
with the given test cases.
Determine whether a given number is a perfect number or not. A positive number is said
to be a perfect number if it is equal to the sum of all its proper divisors. Proper divisors
include all the divisors of a number except the number itself.
Find the sum of array elements using recursion
Concatenate two strings using pointers
Add two distances in feet and inches using a structure.
Count the total number of alphabets, digits, and special characters in a string.
Calculate the sum of squares of digits using a do-while loop.
31
EX.NO.7 ADVANCED LEVEL PROGRAMS IN C - WEEK-7
DATE:
AIM
Write C programs to implement the following exercises in C. (use - switch-case, 2D matrix,
array of structures, arithmetic operations, loops, pointers).
Implement banking operations using a switch-case statement. Assume a fixed interest
rate of 4% of the balance.
Perform matrix multiplication.
Define a structure called student that contains fields for name, registration number
(regno), marks of subjects, and percentage. Write a C program to read the name, regno,
and marks of 5 subjects for 5 students. Then, sort the students in ascending order based
on their total marks
Develop a program to implement a calculator in C.
Display the sum of series 1 + 1/2 + 1/3 + ..............+ 1/n.
Sort an array of integers using pointers.
EXERCISE-1
Write a C program to implement banking operations using a switch-case statement.
Assume a fixed interest rate of 4% of the balance.
Banking System
................
D ->Deposit
W ->Withdraw
B ->Balance
I ->Interest
Q ->Quit
Enter operation: B
Balance: Rs.10000
Banking System
................
D ->Deposit
W ->Withdraw
B ->Balance
32
I ->Interest
Q ->Quit
Enter operation: I
Interest: Rs400.0
Banking System
................
D ->Deposit
W ->Withdraw
B ->Balance
I ->Interest
Q ->Quit
Enter operation: W
Banking System
................
D ->Deposit
W ->Withdraw
B ->Balance
I ->Interest
Q ->Quit
Enter operation: B
Balance: Rs.7400
Banking System
................
D ->Deposit
W ->Withdraw
B ->Balance
I ->Interest
Q ->Quit
Enter operation: Q
Banking System
................
33
D ->Deposit
W ->Withdraw
B ->Balance
I ->Interest
Q ->Quit
Enter operation: D
Banking System
................
D ->Deposit
W ->Withdraw
B ->Balance
I ->Interest
Q ->Quit
Enter operation: B
Balance: Rs.3000
Banking System
................
D ->Deposit
W ->Withdraw
B ->Balance
I ->Interest
Q ->Quit
Enter operation: W
Banking System
................
D ->Deposit
W ->Withdraw
B ->Balance
I ->Interest
Q ->Quit
Enter operation: B
Balance: Rs.1500
Banking System
................
D ->Deposit
W ->Withdraw
B ->Balance
I ->Interest
Q ->Quit
Enter operation: I
Interest: Rs60.0
Banking System
................
D ->Deposit
34
W ->Withdraw
B ->Balance
I ->Interest
Q ->Quit
Enter operation: B
Balance: Rs.1560
Banking System
................
D ->Deposit
W ->Withdraw
B ->Balance
I ->Interest
Q ->Quit
Enter operation: Q
Banking System
................
D ->Deposit
W ->Wthdraw
B ->Balance
I ->Interest
Q ->Quit
Enter operation: I
Interest: Rs0.0
Banking System
................
D ->Deposit
W ->Withdraw
B ->Balance
I ->Interest
Q ->Quit
Enter operation: Q
35
EXERCISE-2
Write a C program to perform matrix multiplication.
TESTCASES
Testcase-1 and output-1
36
enter the second matrix element=
2
3
multiply of the matrix=
10
15
20
EXERCISE-3
Define a structure called student that contains fields for name, registration number
(regno), marks of subjects, and percentage. Write a C program to read the name, regno,
and marks of 5 subjects for 5 students. Then, sort the students in ascending order based on
their total marks.
37
Subject 3: 57
Subject 4: 54
Subject 5: 50
Enter details for student 5:
Name: KUMAR
Registration Number: 333
Enter marks for 5 subjects:
Subject 1: 35
Subject 2: 56
Subject 3: 67
Subject 4: 33
Subject 5: 52
38
Name: VISWA
Registration Number: 1109
Enter marks for 5 subjects:
Subject 1: 44
Subject 2: 55
Subject 3: 33
Subject 4: 34
Subject 5: 45
Enter details for student 5:
Name: SIVASAKTHI
Registration Number: 1111
Enter marks for 5 subjects:
Subject 1: 23
Subject 2: 24
Subject 3: 45
Subject 4: 43
Subject 5: 44
39
Subject 3: 55
Subject 4: 57
Subject 5: 58
Enter details for student 4:
Name: CHARAN
Registration Number: 90
Enter marks for 5 subjects:
Subject 1: 98
Subject 2: 97
Subject 3: 96
Subject 4: 95
Subject 5: 94
Enter details for student 5:
Name: KUMUTHA
Registration Number: 306
Enter marks for 5 subjects:
Subject 1: 11
Subject 2: 12
Subject 3: 13
Subject 4: 14
Subject 5: 15
EXERCISE-4
Develop a program to implement a calculator in C.
40
67
45.0 - 67.0 = -22.0
EXERCISE-5
Write a C program to display the sum of series 1 + 1/2 + 1/3 + .............. + 1/n.
41
EXERCISE-6
Write a program in C to sort an array of integers using pointers.
Testcase-1 and output-1
RESULT
Thus, C programs were written for the following exercises, executed, and results were verified
with the given test cases.
Implement banking operations using a switch-case statement. Assume a fixed interest
rate of 4% of the balance
Perform matrix multiplication
Define a structure called student that contains fields for name, registration number
(regno), marks of subjects, and percentage. Write a C program to read the name, regno,
and marks of 5 subjects for 5 students. Then, sort the students in ascending order based
on their total marks
Develop a program to implement a calculator in C.
Display the sum of series 1 + 1/2 + 1/3 + ..............+ 1/n.
Sort an array of integers using pointers.
42
EX.NO.8 ADVANCED LEVEL PROGRAMS IN C- WEEK-8
DATE:
AIM
Write C programs to implement the following exercises. (use- pass by reference, bitwise
operator, dynamic memory allocation, header files, arrays, files).
Sort a list of numbers using pass by reference.
Count the number of vowels and consonants in the given string.
Copy the content of one text file into another text file.
Find largest number using dynamic memory allocation.
Draw animated twinkling stars.
Merge two arrays entered by the user at run-time.
EXERCISE-1
Write a program in C to sort a list of numbers using pass by reference.
After Sorting. ..
1
44
66
76
90
After Sorting. ..
1
11
12
21
43
Testcase-3 and output-3
After Sorting. ..
1
8
9
12
34
36
56
78
EXERCISE-2
Write a C program to count the number of vowels and consonants in the given string.
44
EXERCISE-3
Write a C program to copy the content of one text file into another text file.
Testcase-1
file1.txt
INDIA IS MY COUNTRY. I LOVE MY COUNTRY
Output-1
File2.txt is created and contents of file1.txt is copied into it
Testcase-2
file1.txt
Hello how are you. I am fine here.
Output-2
File2.txt is created and contents of file1.txt is copied into it
EXERCISE-4
Write a C program to find largest number using dynamic memory allocation.
Testcase-1 and output-1
Enter the total number of elements: 5
Enter number1: 3.4
Enter number2: 2.4
Enter number3: -5
Enter number4: 24.2
Enter number5: 6.7
Largest number = 24.20
45
EXERCISE-5
Write a C program to draw animated twinkling stars.
Output
EXERCISE-6
Write a C Program to merge two arrays entered by the user at run-time.
46
Testcase-2 and output-2
Enter the size of first array: 3
Enter the array elements: 56
78
90
Enter the size of second array: 2
Enter the array elements: 13
45
The merged array: 56 78 90 13 45
Final array after sorting: 13 45 56 78 90
RESULT
Thus, C programs were written for the following exercises, executed, and results were verified
with the given test cases.
Sort a list of numbers using pass by reference.
Count the number of vowels and consonants in the given string.
Copy the content of one text file into another text file
Find largest number using dynamic memory allocation.
Draw animated twinkling stars
Merge two arrays entered by the user at run-time
47
EX.NO.9 ADVANCED LEVEL PROGRAMS IN C - WEEK-9
DATE:
AIM
To implement the following exercises in C language. (use -loops, strings, histograms, files,
functions, arrays)
EXERCISE-1
Write a C program to find prime numbers between two intervals, using a while loop.
48
EXERCISE-2
Write a C program to replace all occurrences of a character in a string.
EXERCISE-3
Write a C program to remove duplicates from a sorted array.
Testcase-1 and output-1
enter the size of the elements
6
enter the elements
11
11
11
11
11
111
49
Array Before Removing Duplicates: 11 11 11 11 11 111
Array After Removing Duplicates: 11 111
.
EXERCISE-4
Write a C program to display frequency histograms of each group.
TESTCASES
Testcase-1 and output-1
*************
50
FREQUENCY HISTOGRAM
GROUP 0 |
GROUP 1 |
GROUP 2 |
GROUP 3 |
GROUP 4 | *
GROUP 5 |
GROUP 6 |
GROUP 7 | * *
GROUP 8 | * * *
GROUP 9 | * * * *
*************
FREQUENCY HISTOGRAM
GROUP 0 | *
GROUP 1 | * *
GROUP 2 | *
GROUP 3 |
GROUP 4 |
GROUP 5 |
GROUP 6 |
GROUP 7 | * * * * * *
GROUP 8 |
GROUP 9 |
51
marks[8]= 90
marks[9]= 100
*************
FREQUENCY HISTOGRAM
GROUP 0 |
GROUP 1 | *
GROUP 2 | *
GROUP 3 | *
GROUP 4 | *
GROUP 5 | *
GROUP 6 | *
GROUP 7 | *
GROUP 8 | *
GROUP 9 | *
.
EXERCISE-5
Write a C program to delete a substring from a text.
52
EXERCISE-6
Write a C program that appends the contents in an existing binary file.
Testcase-1
101 selvam 10000 3000 670
Output-1
101 selvam 10000 3000 670
303 uma 30000 5000 670
Testcase-2
101 selvam 10000 3000 670
303 uma 30000 5000 670
Output-2
101 selvam 10000 3000 670
303 uma 30000 5000 670
401 santhosh 40000 5678 890
Testcase-3
101 selvam 10000 3000 670
303 uma 30000 5000 670
401 santhosh 40000 5678 890
Output-3
101 selvam 10000 3000 670
303 uma 30000 5000 670
401 santhosh 40000 5678 890
501 ramesh 60000 6000 980
RESULT
Thus, C programs were written for the following exercises, executed, and results were
verified with the given test cases.
Find prime numbers between two intervals, using a while loop.
Replace all occurrences of a character in a string.
Remove duplicates from a sorted array.
Display frequency histograms of each group.
Delete a substring from a text.
Appends the contents in an existing binary file.
***********************************************************************
53
SOLUTIONS
2. Write a C program to compute the perimeter and area of a rectangle, taking the length
and breadth as input.
#include<stdio.h>
#include<conio.h>
int main()
{
/* Declaring variables */
float length, breadth, area, perimeter;
54
perimeter = 2 * (length * breadth);
/* Displaying result */
printf("Area of rectangle = %f", area);
printf("\nPerimeter of rectangle = %f", perimeter);
return 0;
}
3. Write a C program to convert a specified number of days into years, weeks, and remaining
days. Note: Leap years are ignored.
#include <stdio.h>
int main()
{
int days, years, weeks;
days = 1329; // Total number of 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;
}
4. Write a C program that accepts an employee's ID, total worked hours in a month, and the
amount received per hour. Print the employee's ID and salary (rounded to two decimal
places) for a particular month.
#include <stdio.h>
int main()
{
char id[10]; // Variable to store employee ID (up to 10 characters)
int hour; // Variable to store working hours
double value, salary; // Variables for hourly salary and total salary
55
scanf("%lf", &value);
#include <stdio.h>
//if the least significant bit is 1 the number is odd and 0 the number is even
int checkOddEven(int n1)
{
return (n1 & 1);//The & operator does a bitwise and,
}
int main()
{
int n1;
printf("Input any number : ");
scanf("%d", &n1);
// If checkOddEven() function returns 1 then the number is odd
if(checkOddEven(n1))
{
printf("The entered number is odd.\n\n");
}
else
{
printf("The entered number is even.\n\n");
}
return 0;
}
6. Write a C program to read an amount (integer value) and display the amount using the
smallest possible number of banknotes (using typecasting).
#include <stdio.h>
int main()
{
int amt, total; // Declare variables for amount and total
56
// Calculate and print the number of each denomination
total = (int)amt/100;
printf("There are:\n");
printf("%d Note(s) of 100\n", total);
amt = amt-(total*100);
total = (int)amt/50;
printf("%d Note(s) of 50\n", total);
amt = amt-(total*50);
total = (int)amt/20;
printf("%d Note(s) of 20\n", total);
amt = amt-(total*20);
total = (int)amt/10;
printf("%d Note(s) of 10\n", total);
amt = amt-(total*10);
total = (int)amt/5;
printf("%d Note(s) of 5\n", total);
amt = amt-(total*5);
total = (int)amt/2;
printf("%d Note(s) of 2\n", total);
amt = amt-(total*2);
total = (int)amt/1;
printf("%d Note(s) of 1\n", total);
return 0;
}
*****************************************************************************
57
{
printf("The alphabet is a consonant.\n"); // Print message for consonant.
}
else
{
printf("The character is not an alphabet.\n");
}
}
#include <stdio.h>
int main()
{
float n1, n2, n3;
printf("Enter three different numbers: \n");
scanf("%f%f%f",&n1,&n2,&n3);
// if n1 is greater than both n2 and n3, n1 is the largest
if (n1 >= n2 && n1 >= n3)
printf("%.1f is the largest number.", n1);
// if n2 is greater than both n1 and n3, n2 is the largest
if (n2 >= n1 && n2 >= n3)
printf("%.1f is the largest number.", n2);
// if n3 is greater than both n1 and n2, n3 is the largest
if (n3 >= n1 && n3 >= n2)
printf("%.1f is the largest number.", n3);
return 0;
}
3. Write a C program to copy the content of one string, S1, into another string, S2, while
removing characters other than alphabets and spaces.
#include <stdio.h>
#include<ctype.h>
#include<string.h>
int main()
{
char s1[1000],s2[1000];
int i=0,j=0;
printf("enter the string\n");
gets(s1);
while(s1[i]!='\0')
{
if(isalpha(s1[i]) || isspace(s1[i]))
{
s2[j++]=s1[i];
}
i++;
}
58
s2[j]='\0';
puts(s2);
return 0;
}
4. Write a C program to read a string from the first line and print the middle three
characters if the length of the string is odd. Otherwise, print the middle two characters on
the next line as output.
#include <stdio.h>
#include <string.h>
int main()
{
char s[100];
int isOdd,mid,slength;
gets(s);
slength=strlen(s);
if(slength%2==0)
isOdd=0;
else
isOdd=1;
mid=slength/2;
if(isOdd)
printf("%c%c%c",s[mid-1],s[mid],s[mid+1]);
else
printf("%c%c",s[mid-1],s[mid]);
return 0;
}
5. Write a C program to read 'n' numbers into an array and calculate the sum of its
elements.
#include <stdio.h>
int main()
{
float a[100];
int i, n, sum = 0;
printf("Input the number of elements in the array :");
scanf("%d", &n);
printf("Input %d elements in the array :\n", n);
for (i = 0; i < n; i++)
{
printf("element - %d : ", i);
scanf("%f", &a[i]);
}
59
for (i = 0; i < n; i++)
{
sum += a[i];
}
printf("Sum of all elements stored in the array is : %d\n\n", sum);
return 0;
}
6. Write a C program to determine whether a given number is a power of two or not. If the
number is a power of two, print 'Yes'; otherwise, print 'No', using a break statement.
#include <stdio.h>
int main()
{
int n,flag=1;
scanf("%d",&n);
while(n!=1)
{
if(n%2!=0)
{
flag=0;
break;
}
n=n/2;
}
if(flag)
printf("Yes");
else
printf("No");
return 0;
}
*****************************************************************************
60
{
char name[20];
int rollno;
float marks;
};
int main()
{
struct student stu1, stu2, stu3;
printf("Enter name, rollno and marks for stu1 : ");
scanf("%s %d %f", stu1.name, &stu1.rollno, &stu1.marks);
printf("Enter name, rollno and marks for stu2 : ");
scanf("%s %d %f", stu2.name, &stu2.rollno, &stu2.marks);
printf("stu1 : %s %d %.2f\n", stu1.name, stu1.rollno, stu1.marks);
printf("stu2 : %s %d %.2f\n", stu2.name, stu2.rollno, stu2.marks);
return 0;
}
61
4. Write a C program to print the first n natural numbers in reverse order using recursion.
#include<stdio.h>
int numPrint(int);
void main()
{
int n;
printf(" print n value :");
scanf("%d",&n);
numPrint(n);
}
int numPrint(int n)
{ printf("\n");
if (n!=0)
{
printf("%d\n",n);
numPrint(n-1);
}
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
char str[100]; /* Declares a string of size 100 */
int l, i; // Declare variables for string length and loop iteration
printf("Input the string : ");
scanf("%s",str);
l = strlen(str); // Calculate the length of the string
printf("The characters of the string in reverse are : \n");
// Loop to print each individual character of the string in reverse order
for (i = l - 1; i >= 0; i--)
{
printf("%c ", str[i]); // Print each character in reverse order
}
}
62
printf("\n");
for (j = 0; j < i; j++) {
printf("%d ", count);
count++;
}
}
return(0);
}
**************************************************************
63
INTERMEDIATE LEVEL PROGRAMS-WEEK 4
1. Write a C program to find the sum of the series 1+11+111+1111+... up to n terms using a
for loop, where 1 <= n <= 10
#include<stdio.h>
int main()
{
long int n,sum=0, term=1,i;
printf("Enter the number of terms\n");
scanf("%ld", &n);
for(i=1;i<=n; i++)
{
printf("%ld ",term);
sum+=term;
term=term*10+1;
}
printf("\n%ld", sum);
return 0;
}
#include <stdio.h>
int main()
{
int arr[100];
int i, N, even, odd;
printf("Enter size of the array: ");
scanf("%d", &N);
printf("\nEnter %d elements in array :: ", N);
for(i=0; i<N; i++)
{
printf("\nEnter %d element in array :: ", i+1);
scanf("%d", &arr[i]);
}
even = 0;
odd = 0;
for(i=0; i<N; i++)
{
/* If the current element of array is even then increment even count */
if(arr[i]%2 == 0)
even++;
else
odd++;
}
printf("\nTotal even elements: %d\n", even);
64
printf("\nTotal odd elements: %d\n", odd);
return 0;
}
3. Write a C program to find the sum of N integer numbers using command line
arguments.(Note: store the name of the program as example.c)
//example.c
#include <stdio.h>
int main(int argc, char *argv[])
{
int a, b, sum;
int i; //for loop counter
if(argc<2)
{
printf("please use \"program name value1 value2 ... \"\n");
return -1;
}
sum=0;
for(i=1; i<argc; i++)
{
printf("arg[%d]: %d\n",i, atoi(argv[i]));
sum += atoi(argv[i]);
}
printf("Sum of all values: %d\n",sum);
return 0;
}
if((fp=fopen(a,"r"))==NULL)
printf("\nFile dosen't exist.");
else
{
while(1)
{
c=fgetc(fp);
65
if(feof(fp))
break;
cnt++;
}
printf("\nFile have %ld characters. \n",cnt);
}
fclose(fp);
return 0;
}
6. Print Write a C program to print all leap years from the start year 's' to the ending year
'd’.
#include <stdio.h>
//function to check leap year
int check(int year)
{
if( (year % 400==0)||(year%4==0 && year%100!=0) )
return 1;
else
return 0;
}
int main()
{
66
int i,s,d;
printf("Enter the value of starting year and ending year: ");
scanf("%d %d",&s,&d);
**************************************************************************
1. Write a C program to print the following N lines of pattern after reading value for N.
#include <stdio.h>
int main()
{
int n,i,j;
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
if(i==1 || i==n ||j==1 || j==i)
printf("1");
else
printf("0");
}
printf("\n");
}
return 0;
}
2. Write a C program to find the Highest Common Factor (HCF) of given numbers using
recursion.
#include <stdio.h>
int HCF(int num1, int num2)
{
67
while (num1 != num2)
{
if (num1 > num2)
return HCF(num1 - num2, num2);
else
return HCF(num1, num2 - num1);
}
return num1;
}
int main()
{
int num1 = 0;
int num2 = 0;
3. Write a C program to find the maximum of n numbers using pointers, utilizing the
malloc() function.
#include <stdio.h>
#include <conio.h>
#include<stdlib.h>
int main()
{
int n,*p,i,h=0;
printf("How many numbers u want :: ");
scanf("%d",&n);
p=(int *) malloc(sizeof(int));
for(i=0;i<n;i++)
{
printf("Enter Number %d :: ",i+1);
scanf("%d",p+i);
}
h=*p;
for(i=1;i<n;i++)
{
if(*(p+i)>h)
h =*(p+i);
}
printf("\nThe Largest Number is %d \n",h);
return 0;
}
68
4. Write a C program to display a structure using the typedef keyword. The structure
should contain fields for name, id, age, and native.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct
{
char name[30];
int id;
int age;
char native[50];
} employee;
void main()
{
employee emp;
//assign values to emp
printf("\n Enter empname, id, age and native\n");
scanf("%s %d %d %s", emp.name, emp.id, emp.age, emp.native);
printf("Employee detail:\n");
printf("Name: %s\n",emp.name);
printf("Age: %d\n",emp.age);
printf("id: %d\n",emp.id);
printf("native: %s\n",emp.native);
}
69
6. Write a C program to print the transpose of a matrix.
#include <stdio.h>
int main()
{
int m, n, i, j;
// Requesting the dimensions of the matrix from the user
printf("Enter the number of rows and columns of the matrix: ");
scanf("%d%d", &m, &n);
int A[m][n], Transposed[n][m];
// Capturing the matrix elements from the user
printf("Enter the elements of the matrix:\n");
for(i = 0; i < m; i++) {
for(j = 0; j < n; j++) {
printf("A[%d][%d] = ", i+1, j+1);
scanf("%d", &A[i][j]);
}
}
// Calculating the transpose
for(i = 0; i < m; i++) {
for(j = 0; j < n; j++) {
Transposed[j][i] = A[i][j];
}
}
// Displaying the transpose
printf("\nTranspose of the matrix is:\n");
for(i = 0; i < n; i++) {
for(j = 0; j < m; j++) {
printf("%d ", Transposed[i][j]);
}
printf("\n");
}
return 0;
}
***************************************************************************
70
INTERMEDIATE LEVEL PROGRAMS-WEEK 6
1. Write a C program to determine whether a given number is a perfect number or not. A
positive number is said to be a perfect number if it is equal to the sum of all its proper
divisors. Proper divisors include all the divisors of a number except the number itself.
#include <stdio.h>
int main()
{
int num,x;
int sum=0;
printf("\nenter the number : ");
scanf("%d",&num);
for(x=1; x<num;x++)
{
if(num%x==0)
sum+=x;
}
if(sum==num)
printf("\n%d is a perfect number",num);
else
printf("\n%d is not a perfect number.\n",num);
return 0;
}
71
3. Write a C program to concatenate two strings using pointers.
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100 // Maximum string size
int main()
{
char str1[MAX_SIZE], str2[MAX_SIZE];
char *s1 = str1;
char *s2 = str2;
4. Write a C program to add two distances in feet and inches using a structure.
#include <stdio.h>
struct distance
{
int feet;
int inch;
};
int main()
{
struct distance d1, d2;
printf("Enter first distance in feet & inches:");
scanf("%d%d", &d1.feet, &d1.inch);
72
printf("Enter second distance in feet & inches:");
scanf("%d%d", &d2.feet, &d2.inch);
5. Write a C program to count the total number of alphabets, digits, and special characters
in a string.
#include <stdio.h>
#include <ctype.h>
void main()
{
int i=0,alphabets=0,numbers=0,special=0;
char str[100];
printf("Enter any string: ");
gets(str);
while(str[i] != '\0')
{
if(isalpha(str[i]) != 0) alphabets++;
else if(isdigit(str[i]) != 0) numbers++;
else if(isspace(str[i]) != 0) ;
else special++;
i++;
}
printf("Alphabets = %d",alphabets);
printf("\nNumbers = %d",numbers);
printf("\nSpecial Characters = %d",special);
}
6. Write a C program to calculate the sum of squares of digits using a do-while loop.
#include <stdio.h>
int main()
{
int num, digit, sum = 0;
// Prompt the user to enter a positive integer
printf("Input a positive integer: ");
scanf("%d", &num);
// Check if the entered number is positive
if (num<= 0)
{
printf("Please input a positive integer.\n");
return 1; // Return an error code
73
}
// Calculate the sum of the squares of each digit
do
{
digit = num % 10; // Extract the last digit
sum += digit * digit; // Add the square of the digit to the sum
num /= 10; // Remove the last digit
} while (num != 0); // Continue the loop until there are no more digits
// Print the sum of the squares of each digit
printf("Sum of the squares of each digit: %d\n", sum);
return 0; // Indicate successful program execution
}
****************************************************************************
74
ADVANCED LEVEL PROGRAMS-WEEK 7
1. Write a C program to implement banking operations using a switch-case statement.
Assume a fixed interest rate of 4% of the balance.
#include<stdio.h>
void main()
{
int balance=0, deposit, withdraw;
float ci;
char op;
while(1)
{
printf("\nBanking System");
printf("\n. ............. ");
printf("\nD ->Deposit");
printf("\nW ->Withdraw");
printf("\nB ->Balance");
printf("\nI ->Interest");
printf("\nQ ->Quit");
printf("\nEnter operation: ");
scanf(" %c", &op);
switch(op)
{
case 'D':
printf("\nEnter deposit amount: ");
scanf("%d", &deposit);
balance += deposit;
break;
case 'W':
printf("\nEnter withdraw amount ");
scanf("%d", &withdraw);
if (balance>withdraw)
{
balance -= withdraw;
break;
}
else
{
printf("withdraw impossible as low balance\n");
break;
}
case 'B':
printf("Balance: Rs.%d", balance);
break;
case 'I':
ci = (float)balance*4/100;
balance += ci;
printf("\nInterest: Rs%.1f", ci);
break;
case 'Q':
75
return;
default:
printf("Invalid Operation!");
}
} }
#include<stdio.h>
#include<stdlib.h>
int main()
{
int a[10][10],b[10][10],mul[10][10],row1, col1, row2, col2,i,j,k;
printf("enter the number of rows in first matrix=");
scanf("%d",&row1);
printf("enter the number of columns in second matrix=");
scanf("%d",&col1);
printf("enter the first matrix element=\n");
for(i=0;i<row1;i++)
{
for(j=0;j<col1;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("enter the number of rows in second matrix=");
scanf("%d",&row2);
printf("enter the number of columns in second matrix=");
scanf("%d",&col2);
if (col1!=row2)
{
printf("matrix multiplication impossible\n");
return 0;
}
printf("enter the second matrix element=\n");
for(i=0;i<row2;i++)
{
for(j=0;j<col2;j++)
{
scanf("%d",&b[i][j]);
}
}
printf("multiply of the matrix=\n");
for(i=0;i<row1;i++)
{
for(j=0;j<col2;j++)
{
mul[i][j]=0;
76
for(k=0;k<row2;k++)
{
mul[i][j]+=a[i][k]*b[k][j];
}
}
}
//for printing result
for(i=0;i<row1;i++)
{
for(j=0;j<col2;j++)
{
printf("%d\t",mul[i][j]);
}
printf("\n");
}
return 0;
}
3. Define a structure called student that contains fields for name, registration number
(regno), marks of subjects, and percentage. Write a C program to read the name, regno,
and marks of 5 subjects for 5 students. Then, sort the students in ascending order based on
their total marks.
#include <stdio.h>
struct Student
{
char name[50];
int regno;
int marks[5];
float percentage;
int totalMarks;
};
// Function to calculate total marks and percentage
void calculate(struct Student *student)
{
student->totalMarks = 0;
for (int i = 0; i < 5; ++i)
{
student->totalMarks += student->marks[i];
}
student->percentage = (float)student->totalMarks / 5;
}
77
*b = temp;
}
void sortStudents(struct Student students[], int n)
{
for (int i = 0; i< n - 1; ++i) {
for (int j = 0; j < n - i - 1; ++j) {
if (students[j].totalMarks> students[j + 1].totalMarks)
{
swap(&students[j], &students[j + 1]);
} }}
}
int main()
{
// Declare an array of 5 students
struct Student students[5];
for(int i = 0; i < 5; ++i)
{
printf("Enter details for student %d:\n", i + 1);
printf("Name: ");
scanf("%s", students[i].name);
printf("Registration Number: ");
scanf("%d", &students[i].regno);
printf("Enter marks for 5 subjects:\n");
for(int j = 0; j < 5; ++j)
{
printf("Subject %d: ", j + 1);
scanf("%d", &students[i].marks[j]);
}
calculate(&students[i]);
}
sortStudents(students, 5);
printf("\nSorted list of students in ascending order of total marks:\n");
for(int i = 0; i < 5; ++i)
{
printf("Name: %s, Registration Number: %d, Total Marks: %d,Percentage: %.2f%%\n",
students[i].name, students[i].regno, students[i].totalMarks, students[i].percentage);
}
return 0;
}
78
char ch;
double a, b;
while (1)
{
printf("Enter an operator (+, -, *, /), "
"if want to exit press x: ");
scanf(" %c", &ch);
// to exit
if (ch == 'x')
exit(0);
printf("Enter two first and second operand: ");
scanf("%lf %lf", &a, &b);
// For Addition
case '+':
printf("%.1lf + %.1lf = %.1lf\n", a, b, a + b);
break;
// For Subtraction
case '-':
printf("%.1lf - %.1lf = %.1lf\n", a, b, a - b);
break;
// For Multiplication
case '*':
printf("%.1lf * %.1lf = %.1lf\n", a, b, a * b);
break;
// For Division
case '/':
printf("%.1lf / %.1lf = %.1lf\n", a, b, a / b);
break;
printf("\n");
}
}
79
5. Write a C program to display the sum of series 1 + 1/2 + 1/3 + .............. + 1/n.
#include<stdio.h>
int main()
{
int num,i, sum =0;
// Prompt the user to input a number
printf("Input the number of terms\n");
scanf("%d",&num);
// Display the initial part of the series
printf("1 + ");
// Print the series
for(i=2;i<=num-1;i++)
printf(" 1/%d +",i);
80
}
}
}
printf("\n Sorted Values : ");
for(i=0;i<n;i++)
{
printf("%d ",*(p+i));
}
return 0;
}
***************************************************************************
2. Write a C program to count the number of vowels and consonants in the given string.
#include <stdio.h>
81
void count(char* str)
{
// Declare the variable vowels and consonant
int vowels = 0, consonants = 0;
int i;
char ch;
// Take each character from this string to check
for (i = 0; str[i] != '\0'; i++)
{
ch = str[i];
if (ch == 'a' || ch == 'e'|| ch == 'i' || ch == 'o'|| ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I'|| ch == 'O'
|| ch == 'U')
vowels++;
else if (ch == ' ')
continue;
else
consonants++;
}
// Print the total count of vowels and consonants
printf("\nVowels: %d", vowels);
printf("\nConsonants: %d", consonants);
}
int main()
{
char* str = "india is my country";
printf("String: %s", str);
count(str);
return 0;
}
3. Write a C program to copy the content of one text file into another text file.
#include <stdio.h>
#include <stdlib.h> // For exit()
int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;
82
{
printf("Cannot open file %s \n", filename);
exit(0);
}
// Read contents from file
c = fgetc(fptr1);
while (c != EOF)
{
fputc(c, fptr2);
c = fgetc(fptr1);
}
printf("\nContents copied to %s", filename); }
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n;
double *data;
printf("Enter the total number of elements: ");
scanf("%d", &n);
// Allocating memory for n elements
data = (double *)calloc(n, sizeof(double));
if (data == NULL) {
printf("Error!!! memory not allocated.");
exit(0);
}
// Storing numbers entered by the user.
for (int i = 0; i< n; ++i) {
printf("Enter number%d: ", i + 1);
scanf("%lf", data + i);
}
free(data);
return 0;
}
83
5. Write a C program to draw animated twinkling stars.
#include <graphics.h>
#include <dos.h>
#include <stdlib.h>
int main()
{
int gd=DETECT,gm;
int i, x, y;
initgraph(&gd, &gm,"..\\BGI");
while (!kbhit())
{
/* color 500 random pixels on screen */
for(i=0; i<=500; i++)
{
x=rand()%getmaxx();
y=rand()%getmaxy();
putpixel(x,y,15);
}
delay(500);
/* clears screen */
cleardevice();
}
closegraph();
return 0;
}
6. Write a C Program in c to merge any two arrays entered by the user at run-time.
#include <stdio.h>
int main()
{
int n1,n2,n3; //Array Size Declaration
int a[10000], b[10000], c[20000];
printf("Enter the size of first array: ");
scanf("%d",&n1);
printf("Enter the array elements: ");
for(int i = 0; i < n1; i++)
scanf("%d", &a[i]);
printf("Enter the size of second array: ");
scanf("%d",&n2);
printf("Enter the array elements: ");
for(int i = 0; i < n2; i++)
scanf("%d", &b[i]);
n3 = n1 + n2;
for(int i = 0; i < n1; i++)
c[i] = a[i];
84
for(int i = 0; i < n2; i++)
c[i + n1] = b[i];
***************************************************************************
1. Write a C Program to find prime numbers between two intervals, using a while loop.
#include<stdio.h>
#include<math.h>
int main()
{
int start, end, count, prime, inum;
printf("Enter start and end value\n");
scanf("%d%d", &start, &end);
printf("\n\nPrime Numbers from %d to %d are:\n", start, end);
while(start <= end)
{
inum = sqrt(start);
count = 2;
prime = 1;
85
if(start%count == 0)
{
prime = 0;
break;
}
count++;
}
if(prime) printf("%d, ", start);
start++;
}
printf("\n\n");
return 0;
}
#include <stdio.h>
#define MAX_SIZE 100 // Maximum string size
/* Function declaration */
void replaceAll(char * str, char oldChar, char newChar);
int main()
{
char str[MAX_SIZE], oldChar, newChar;
printf("Enter any string: ");
gets(str);
printf("Enter character to replace: ");
oldChar = getchar();
// Dummy getchar() to eliminate extra ENTER character
getchar();
printf("Enter character to replace '%c' with: ", oldChar);
newChar = getchar();
printf("\nString before replacing: \n%s", str);
replaceAll(str, oldChar, newChar);
printf("\n\nString after replacing '%c' with '%c' : \n%s", oldChar, newChar, str);
return 0;
}
void replaceAll(char * str, char oldChar, char newChar)
{
int i = 0;
/* Run till end of string */
while(str[i] != '\0')
{
/* If occurrence of character is found */
if(str[i] == oldChar)
{
str[i] = newChar;
}
i++;
} }
86
3. Write a C program to remove duplicates from a sorted array.
#include <stdio.h>
int remove_duplicate(int arr[], int n)
{
if (n == 0 || n == 1)
return n;
int temp[n];
int j = 0;
int i;
for (i = 0; i< n - 1; i++)
if (arr[i] != arr[i + 1])
temp[j++] = arr[i];
temp[j++] = arr[n - 1];
return j;
}
int main()
{
int n, arr[100], i;
printf("enter the size of the elements\n");
scanf("%d", &n);
printf("enter the elements\n");
for (i = 0; i< n; i++)
{
scanf("%d", &arr[i]);
}
printf("\nArray Before Removing Duplicates: ");
for (i = 0; i< n; i++)
printf("%d ", arr[i]);
n = remove_duplicate(arr, n);
printf("\nArray After Removing Duplicates: ");
for (i = 0; i< n; i++)
printf("%d ", arr[i]);
return 0;
}
87
int marks[50],i,index;
int group[10]={0};
printf("\n enter the marks of 10 students :\n");
for(i=0; i<10; i++)
{
printf("marks[%d]= ", i);
scanf("%d", &marks[i]);
++group[(int)(marks[i])/10];
}
printf("\n *************");
i=0;
printf("\n\n FREQUENCY HISTOGRAM");
for (index=0; index<10; index++)
{
printf("\n GROUP %d | ", index);
for(i=0; i<group[index]; i++)
printf(" * ");
}
return 0;
}
for(i=0;str[i]!='\0' ; i++)
{
k = i;
while(str[i] == word[j])
{
i++,j++;
if(j == strlen(word))
{
flag = 1;
break;
}
88
}
j = 0;
if(flag == 0)
i = k;
else
flag = 0;
neww[n++] = str[i];
}
neww[n] = '\0';
6. Write a C program that appends the contents of one binary file to another.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{ int i,ec,found=0;
typedef struct employee
{
int empcode;
char name[20];
int hra,da,ta;
};
FILE *fp;
struct employee e;
fp=fopen("emp.txt","ab");
if (fp==NULL)
{
printf("\n error opening file");
exit(1);
}
printf("\n\n enter the employee code");
scanf("%d", &e.empcode);
printf("\n\n enter the employee name");
scanf("%s",&e.name);
printf("enter HRA,DA,TA");
scanf("%d %d %d", &e.hra, &e.da,&e.ta);
fclose(fp);
printf("record appended\n");
}
**************************************************************************
89