0% found this document useful (0 votes)
59 views89 pages

TSP Lab Record With Solutions

The document contains 6 exercises to implement basic programs in C language using loops, arithmetic operators, functions and typecasting. The exercises include programs to check digit occurrence in a number, calculate rectangle perimeter and area, convert days to years/weeks/days, calculate employee salary, determine even/odd number and display amount in minimum banknotes.

Uploaded by

Vijay Anand.V
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)
59 views89 pages

TSP Lab Record With Solutions

The document contains 6 exercises to implement basic programs in C language using loops, arithmetic operators, functions and typecasting. The exercises include programs to check digit occurrence in a number, calculate rectangle perimeter and area, convert days to years/weeks/days, calculate employee salary, determine even/odd number and display amount in minimum banknotes.

Uploaded by

Vijay Anand.V
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/ 89

PANIMALAR ENGINEERING COLLEGE

(AN AUTONOMOUS INSTITUTION)


JAISAKTHI EDUCATIONAL TRUST

ACCREDITED BY NATIONAL BOARD OF ACCREDITATION


AN ISO 9001:2000 CERTIFIED INSTITUTION
Bangalore Trunk Road,
Varadharajapuram, Nasarathpettai,
Poonamallee, Chennai – 600123

DEPARTMENT OF
ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING

I YEAR – II SEMESTER

LAB RECORD

23ES1212 - TECHNICAL SKILL PRACTICES I

Name: Roll No :
Reg. No.: Section:

1
PANIMALAR ENGINEERING COLLEGE
(AN AUTONOMOUS INSTITUTION)
JAISAKTHI EDUCATIONAL TRUST

ACCREDITED BY NATIONAL BOARD OF ACCREDITATION


AN ISO 9001:2000 CERTIFIED INSTITUTION
Bangalore Trunk Road,
Varadharajapuram, Nasarathpettai,
Poonamallee, Chennai – 600 123.

DEPARTMENT OF

ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING

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

INTERNAL EXAMINER EXTERNAL EXAMINER

2
SYLLABUS
Module 1
INTRODUCTION TO PROGRAMMING

Overview of C: History and importance of C, Basic structure of C program, compiling and


executing a C program. Constants, Variable and Data Types: Introduction, character set, C
tokens, keywords, identifiers, constants, defining symbolic constants, variables, declaration of
variables, assigning values to variables, data-types. Input and Output Operations: printf(),
scanf(), Formatted I/O. Operators and expressions: Arithmetic operator, Relational operator,
Logical or Boolean operator, Assignment Operator, Ternary operator, Bitwise operator,
Increment or Decrement operator, Conditional operator, arithmetic expressions, evaluation of
expressions, operator precedence and associativity, type conversions.

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

To transform the budding Engineers into academically excellent, highly


intellectual, and self disciplined engineering graduates to mould them as
good citizens with the spirit of integrity and morality that would cater to
the needs of our Nation.

Mission

To impart quality education with high standards of excellence in


engineering and technology, to provide an excellent infrastructure in a
serene and conducive atmosphere that would motivate the students in
their pursuit of knowledge in the field of engineering and technology.

4
INDEX

EX.NO DATE NAME OF THE PYTHON PAGE FACULTY


PROGRAM NO. SIGN
1 BASIC LEVEL PROGRAMS IN C 6
WEEK-1

2 BASIC LEVEL PROGRAMS IN C 10


WEEK-2

3 BASIC LEVEL PROGRAMS IN C 14


WEEK-3

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

7 ADVANCED LEVEL PROGRAMS IN 32


C - WEEK 7

8 ADVANCED LEVEL PROGRAMS IN 43


C -WEEK 8

9 ADVANCED LEVEL PROGRAMS IN 48


C -WEEK 9

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

Constraint on inputs and output:


 N is non negative

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:

To implement the following exercises in C language(use - structure, functions, pointers,


recursion, patterns).

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

//create a file called file1.txt and the contents of the file is


WELCOME TO PANIMALAR ENGINEERING COLLEGE
testcase-3
Type a file name : FILE2.TXT
expected output-3
File has 40 characters.
.
EXERCISE-5
Write a C program to swap two strings using the strcpy() function.
testcase-1
Enter the First String: hello
Enter the Second String: welcome
expected output-1
String before Swap:
First String = hello Second String = welcome
String after Swap:
First String = welcome Second String = hello

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.

For example find whether 28 is a perfect number


Step1: Divisors of 28 are 1, 2, 4, 7, 14 and 28
Step 2: Sum of all proper divisor of 28 is
1 + 2 + 4 + 7 + 14 = 28
So 28 is a perfect number.

Example of other perfect numbers are:


Perfect Number Sum of Divisors
6 1+2+3
28 1 + 2 + 4 + 7 + 14
496 1 + 2 + 4 + 8 + 16 + 31 + 62 + 124 + 248
8128 1 + 2 + 4 + 8 + 16 + 32 + 64 + 127 + 254 + 508 + 1016 + 2032 + 4064

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.

Testcase-1 and output-1


Banking System
................
D ->Deposit
W ->Withdraw
B ->Balance
I ->Interest
Q ->Quit
Enter operation: D

Enter deposit amount: 10000

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

Enter withdraw amount: 3000

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

Testcase-2 and output-2


Banking System
................
D ->Deposit
W ->Withdraw
B ->Balance
I ->Interest
Q ->Quit
Enter operation: D

Enter deposit amount: 1000

Banking System
................

33
D ->Deposit
W ->Withdraw
B ->Balance
I ->Interest
Q ->Quit
Enter operation: D

Enter deposit amount: 2000

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

Enter withdraw amount: 15000

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

Testcase-3 and output-3


Banking System
................
D ->Deposit
W ->Withdraw
B ->Balance
I ->Interest
Q ->Quit
Enter operation: W

Enter withdraw amount 10000


withdraw impossible as low balance

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

enter the number of rows in first matrix=2


enter the number of columns in second matrix=3
enter the first matrix element=
1
2
3
4
5
6
enter the number of rows in second matrix=4
enter the number of columns in second matrix=5
matrix multiplication impossible

Testcase-2 and output-2


enter the number of rows in first matrix=2
enter the number of columns in second matrix=2
enter the first matrix element=
12
12
12
12
enter the number of rows in second matrix=2
enter the number of columns in second matrix=2
enter the second matrix element=
12
12
12
12
multiply of the matrix=
288 288
288 288

Testcase-3 and output-3


enter the number of rows in first matrix=3
enter the number of columns in second matrix=2
enter the first matrix element=
2
2
3
3
4
4
enter the number of rows in second matrix=2
enter the number of columns in second matrix=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.

Testcase-1 and output-1


Enter details for student 1:
Name: SELVAN
Registration Number: 101
Enter marks for 5 subjects:
Subject 1: 90
Subject 2: 98
Subject 3: 98
Subject 4: 87
Subject 5: 86
Enter details for student 2:
Name: KRISH
Registration Number: 302
Enter marks for 5 subjects:
Subject 1: 98
Subject 2: 88
Subject 3: 87
Subject 4: 86
Subject 5: 85
Enter details for student 3:
Name: VINAYKUMAR
Registration Number: 102
Enter marks for 5 subjects:
Subject 1: 76
Subject 2: 68
Subject 3: 66
Subject 4: 88
Subject 5: 77
Enter details for student 4:
Name: RANJITH
Registration Number: 222
Enter marks for 5 subjects:
Subject 1: 55
Subject 2: 56

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

Sorted list of students in ascending order of total marks:


Name: KUMAR, Registration Number: 333, Total Marks: 243,Percentage: 48.60%
Name: RANJITH, Registration Number: 222, Total Marks: 272,Percentage: 54.40%
Name: VINAYKUMAR, Registration Number: 102, Total Marks: 375,Percentage: 75.00%
Name: KRISH, Registration Number: 302, Total Marks: 444,Percentage: 88.80%
Name: SELVAN, Registration Number: 101, Total Marks: 459,Percentage: 91.80%

Testcase-2 and output-2


Enter details for student 1:
Name: SELVI
Registration Number: 1101
Enter marks for 5 subjects:
Subject 1: 89
Subject 2: 99
Subject 3: 12
Subject 4: 78
Subject 5: 88
Enter details for student 2:
Name: KIRAN
Registration Number: 1105
Enter marks for 5 subjects:
Subject 1: 87
Subject 2: 86
Subject 3: 85
Subject 4: 98
Subject 5: 90
Enter details for student 3:
Name: RAVI
Registration Number: 1106
Enter marks for 5 subjects:
Subject 1: 56
Subject 2: 57
Subject 3: 58
Subject 4: 59
Subject 5: 56
Enter details for student 4:

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

Sorted list of students in ascending order of total marks:


Name: SIVASAKTHI, Registration Number: 1111, Total Marks: 179,Percentage: 35.80%
Name: VISWA, Registration Number: 1109, Total Marks: 211,Percentage: 42.20%
Name: RAVI, Registration Number: 1106, Total Marks: 286,Percentage: 57.20%
Name: SELVI, Registration Number: 1101, Total Marks: 366,Percentage: 73.20%
Name: KIRAN, Registration Number: 1105, Total Marks: 446,Percentage: 89.20%

Testcase-3 and output-3


Enter details for student 1:
Name: NAGALATHA
Registration Number: 89
Enter marks for 5 subjects:
Subject 1: 100
Subject 2: 99
Subject 3: 99
Subject 4: 99
Subject 5: 98
Enter details for student 2:
Name: JEYANTHI
Registration Number: 302
Enter marks for 5 subjects:
Subject 1: 88
Subject 2: 87
Subject 3: 76
Subject 4: 78
Subject 5: 79
Enter details for student 3:
Name: VIJI
Registration Number: 303
Enter marks for 5 subjects:
Subject 1: 55
Subject 2: 56

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

Sorted list of students in ascending order of total marks:


Name: KUMUTHA, Registration Number: 306, Total Marks: 65,Percentage: 13.00%
Name: VIJI, Registration Number: 303, Total Marks: 281,Percentage: 56.20%
Name: JEYANTHI, Registration Number: 302, Total Marks: 408,Percentage: 81.60%
Name: CHARAN, Registration Number: 90, Total Marks: 480,Percentage: 96.00%
Name: NAGALATHA, Registration Number: 89, Total Marks: 495,Percentage: 99.00%

EXERCISE-4
Develop a program to implement a calculator in C.

Testcase-1 and output-1


Enter an operator (+, -, *, / ) if want to exit press x: !
Enter two first and second operand: 12
23
Error! please write a valid operator

Enter an operator (+, -, *, / ) if want to exit press x:

Testcase-2 and output-2


Enter an operator (+, -, *, / ) if want to exit press x: +
Enter two first and second operand: 12
23
12.0 + 23.0 = 35.0

Enter an operator (+, -, *, / ) if want to exit press x: -


Enter two first and second operand: 45

40
67
45.0 - 67.0 = -22.0

Enter an operator (+, -, *, / ) if want to exit press x: *


Enter two first and second operand: 12
23
12.0 * 23.0 = 276.0

Enter an operator (+, -, *, / ) if want to exit press x: /


Enter two first and second operand: 12
12
12.0 / 12.0 = 1.0

Enter an operator (+, -, *, / ) if want to exit press x: x

Testcase-3 and output-3


Enter an operator (+, -, *, / ) if want to exit press x: =_++
Enter two first and second operand: 678
678
678.0 + 678.0 = 1356.0

Enter an operator (+, -, *, / ) if want to exit press x: -


Enter two first and second operand: 345
678
345.0 - 678.0 = -333.0

Enter an operator (+, -, *, / ) if want to exit press x: x

EXERCISE-5
Write a C program to display the sum of series 1 + 1/2 + 1/3 + .............. + 1/n.

Testcase-1 and output-1


Input any number: 7
1 + 1/2 + 1/3 + 1/4 + 1/5 + 1/6 + 1/7
Sum = 1/28

Testcase-2 and output-2


Input the number of terms: 5
1 + 1/2 + 1/3 + 1/4 + 1/5
Sum = 1/15

Testcase-3 and output-3


Input the number of terms: 8
1 + 1/2 + 1/3 + 1/4 + 1/5 + 1/6 + 1/7 + 1/8
Sum = 1/36

41
EXERCISE-6
Write a program in C to sort an array of integers using pointers.
Testcase-1 and output-1

enter the number of elements


4
enter the elements one by one
76
54
88
99
Sorted Values : 54 76 88 99

Testcase-2 and output-2


enter the number of elements
7
enter the elements one by one
345
67
89
12
1
44
55
Sorted Values : 1 12 44 55 67 89 345

Testcase-3 and output-3


enter the number of elements
5
enter the elements one by one
11
77
33
22
24.6
Sorted Values : 11 22 24 33 77

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.

Testcase-1 and output-1


Enter the Number of Elements in an array : 5

Enter the Array elements


76
66
44
90
1

After Sorting. ..
1
44
66
76
90

Testcase-2 and output-2


Enter the Number of Elements in an array : 4

Enter the Array elements


12
21
11
01

After Sorting. ..
1
11
12
21

43
Testcase-3 and output-3

Enter the Number of Elements in an array : 8

Enter the Array elements


56
12
36
34
78
1
9
8

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.

Testcase-1 and output-1


enter the string
india is my country
String: india is my country
Vowels: 6
Consonants: 10

Testcase-2 and output-2


enter the string
String: PANIMALAR ENGINEERING COLLEGE, CHENNAI
Vowels: 15
Consonants: 20

Testcase-3 and output-3


enter the string
String: MY EXAMS WILL COMMENCE FROM MONTH OF MAY
Vowels: 10
Consonants: 23

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

Testcase-2 and output-2


Enter the total number of elements: 3
Enter number1: 45
Enter number2: 67
Enter number3: 29.5
Largest number = 67.00

Testcase-3 and output-3


Enter the total number of elements: 7
Enter number1: 12
Enter number2: 56
Enter number3: 34
Enter number4: 22
Enter number5: 90
Enter number6: 10
Enter number7: 5.7
Largest number = 90.00

45
EXERCISE-5
Write a C program to draw animated twinkling stars.

Just browse to Options>Linker>Libraries> and select the option "Graphics Libraries" IN


TURBOC

Output

EXERCISE-6
Write a C Program to merge two arrays entered by the user at run-time.

Testcase-1 and output-1


Enter the size of first array: 5
Enter the array elements: 66
44
88
98
12
Enter the size of second array: 4
Enter the array elements: 87
65
43
21
The merged array: 66 44 88 98 12 87 65 43 21
Final array after sorting: 12 21 43 44 65 66 87 88 98

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

Testcase-3 and output-3


Enter the size of first array: 4
Enter the array elements: 67
89
11
22
Enter the size of second array: 3
Enter the array elements: 44
55
66
The merged array: 67 89 11 22 44 55 66
Final array after sorting: 11 22 44 55 66 67 89

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)

 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.
 Append the contents in an existing binary file.

EXERCISE-1
Write a C program to find prime numbers between two intervals, using a while loop.

Testcase-1 and output-1


Enter start and end value
2
50

Prime Numbers from 2 to 50 are:


2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47

Testcase-2 and output-2


Enter start and end value
34
78

Prime Numbers from 34 to 78 are:


37, 41, 43, 47, 53, 59, 61, 67, 71, 73

Testcase-3 and output-3


Enter start and end value
1
1000

Prime Numbers from 1 to 100 are:


1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,

48
EXERCISE-2
Write a C program to replace all occurrences of a character in a string.

Testcase-1 and output-1


Enter any string: i love india
Enter character to replace: i
Enter character to replace 'i' with: p

String before replacing:


i love india

String after replacing 'i' with 'p' :


p love pndpa

Testcase-2 and output-2


Enter any string: WHERE ARE YOU, I AM FINE HERE
Enter character to replace: E
Enter character to replace 'E' with: )

String before replacing:


WHERE ARE YOU, I AM FINE HERE

String after replacing 'E' with ')' :


WH)R) AR) YOU, I AM FIN) H)R)

Testcase-3 and output-3


Enter any string: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
Enter character to replace: A
Enter character to replace 'A' with: I

String before replacing:


AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
String after replacing 'A' with 'I' :
IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII
.

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

Testcase-2 and output-2


enter the size of the elements
5
enter the elements
67
67
56
45
3

Array Before Removing Duplicates: 67 67 56 45 3


Array After Removing Duplicates: 67 56 45 3

Testcase-3 and output-3


enter the size of the elements
7
enter the elements
87
88
99
66
55
44
44

Array Before Removing Duplicates: 87 88 99 66 55 44 44


Array After Removing Duplicates: 87 88 99 66 55 44

.
EXERCISE-4
Write a C program to display frequency histograms of each group.
TESTCASES
Testcase-1 and output-1

enter the marks of 10 students :


marks[0]= 98
marks[1]= 80
marks[2]= 99
marks[3]= 78
marks[4]= 92
marks[5]= 93
marks[6]= 45
marks[7]= 88
marks[8]= 80
marks[9]= 76

*************

50
FREQUENCY HISTOGRAM
GROUP 0 |
GROUP 1 |
GROUP 2 |
GROUP 3 |
GROUP 4 | *
GROUP 5 |
GROUP 6 |
GROUP 7 | * *
GROUP 8 | * * *
GROUP 9 | * * * *

Testcase-2 and output-2

enter the marks of 10 students :


marks[0]= 76
marks[1]= 6
marks[2]= 78
marks[3]= 79
marks[4]= 75
marks[5]= 74
marks[6]= 73
marks[7]= 23
marks[8]= 11
marks[9]= 13

*************

FREQUENCY HISTOGRAM
GROUP 0 | *
GROUP 1 | * *
GROUP 2 | *
GROUP 3 |
GROUP 4 |
GROUP 5 |
GROUP 6 |
GROUP 7 | * * * * * *
GROUP 8 |
GROUP 9 |

Testcase-3 and output-3


enter the marks of 10 students :
marks[0]= 11
marks[1]= 23
marks[2]= 34
marks[3]= 45
marks[4]= 56
marks[5]= 67
marks[6]= 78
marks[7]= 89

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.

Testcase-1 and output-1


Enter Any String to Remove a Word from String: hello how are you

Enter Any Word You Want to be Removed: hello how

After Removing Word From String: are you

Testcase-2 and output-2


Enter Any String to Remove a Word from String: i love my country india

Enter Any Word You Want to be Removed: india

After Removing Word From String: i love my country

Testcase-3 and output-3


Enter Any String to Remove a Word from String: A Friend In Need Is A Friend Indeed

Enter Any Word You Want to be Removed: friend

After Removing Word From String: A Friend In Need Is A Friend Indeed

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

BASIC LEVEL –WEEK1


1. Write a C program to check the occurrence of a digit in a given number using a while loop
#include<stdio.h>
#include<conio.h>
int main()
{
int num,i,n,k,num1;
printf("Enter any number :: ");
scanf("%d",&num);
n=num;
i=0;
printf("\nEnter the digit :: ");
scanf("%d",&num1);
while(n!=0)
{
k=n%10;
n=n/10;
if(k==num1)
{
i++;
}
}
printf("\nThe occurrence of %d is %d times",num1,i);
return 0;
}

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;

/* Reading length and breadth from user */


printf("Enter length of the rectangle = ");
scanf("%f", &length);
printf("Enter breadth of the rectangle = ");
scanf("%f", &breadth);

/* Calculating area and perimeter */


area = length * breadth;

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

// Prompt user for employee ID


printf("Input the Employees ID(Max. 10 chars): ");
scanf("%s", id);

// Prompt user for working hours


printf("\nInput the working hrs: ");
scanf("%d", &hour);

// Prompt user for hourly salary


printf("\nSalary amount/hr: ");

55
scanf("%lf", &value);

// Calculate total salary


salary = value * hour;

// Print employee ID and salary


printf("\nEmployees ID = %s\nSalary = Rs.0.%.2lf\n", id, salary);
return 0;
}

5. Write a C program to determine whether a given number is even or odd using a


function

#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

// Prompt user for the amount and store it in 'amt'


printf("Input the amount: ");
scanf("%d",&amt);

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

*****************************************************************************

BASIC LEVEL –WEEK 2


1. Write a C program to check whether a given character is a vowel or a consonant.
#include <stdio.h> // Include the standard input/output header file.
void main()
{
char ch; // Declare a variable to store a single character.
printf("Input any alphabet : "); // Prompt user for input.
scanf("%c", &ch); // Read and store the character input.

if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u' || ch=='A' || ch=='E' || ch=='I' || ch=='O' ||


ch=='U')
{
printf("The alphabet is a vowel.\n"); // Print message for vowel.
}
else if((ch>='a' && ch<='z') || (ch>='A' && ch<='Z'))

57
{
printf("The alphabet is a consonant.\n"); // Print message for consonant.
}
else
{
printf("The character is not an alphabet.\n");
}
}

2. Write a C program to find the maximum of 3 numbers.

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

*****************************************************************************

BASIC LEVEL –WEEK 3


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.

/* Program to display the values of structure members*/


#include<stdio.h>
#include<string.h>
struct student

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

2. Write a C program to find the square of a number using a function.


#include <stdio.h>
double square(double num)
{
return (num * num);
}
int main()
{
int num;
double n;
printf("Input any number for square : ");
scanf("%d", &num);
n = square(num);
printf("The square of %d is : %.2f\n", num, n);
return 0;
}

3. Write a C program to add two numbers using pointers.


#include <stdio.h>
int main()
{
int fno, sno, *ptr, *qtr, sum;
printf(" Input the first number : ");
scanf("%d", &fno);
printf(" Input the second number : ");
scanf("%d", &sno);
ptr = &fno;
qtr = &sno;
sum = *ptr + *qtr;
printf(" The sum of the entered numbers is : %d\n\n", sum);
}

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

5. Write a C program to print individual characters of a string in reverse order.

#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
}
}

6. Write a C program to print numbers in a pyramid using a for loop


#include<stdio.h>
int main()
{
int i,j,n;
int count = 1;
printf("\n enter the value of n\n");
scanf("%d",&n);
for (i = 0; i <= n; i++) {

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

2. Write a C program to count even and odd elements in an array.

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

4. Write a C program to count the number of characters in a file.


#include<stdio.h>
int main()
{
FILE *fp;
char a[100];
long cnt=0;
int c;

printf("Type a file name : ");


gets(a);

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

5. Write a C program to swap two strings using the strcpy() function.


#include<stdio.h>
#include<string.h>
int main()
{
char str1[50], str2[50], temp[50];
printf("Enter the First String: ");
gets(str1);
printf("Enter the Second String: ");
gets(str2);
printf("\nString before Swap:\n");
printf("First String = %s\tSecond String = %s", str1, str2);
strcpy(temp, str1);
strcpy(str1, str2);
strcpy(str2, temp);
printf("\n\nString after Swap:\n");
printf("First String = %s\tSecond String = %s", str1, str2);
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);

printf("Leap years from %d to %d:\n",s,d);


for(i=s;i<=d;i++)
{
if(check(i))
printf("%d\t",i);
}
return 0;
}

**************************************************************************

INTERMEDIATE LEVEL PROGRAMS-WEEK 5

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;

printf("Enter Number1: ");


scanf("%d", &num1);

printf("Enter Number2: ");


scanf("%d", &num2);

printf("The Highest Common Factor is: %d\n", HCF(num1, num2));


}

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

5. Write a C program to find the sum of an Arithmetic Progression (AP) series.


#include <stdio.h>
int main()
{
int a,n,d,tn,i; //Variable Declaration
int sum = 0; //Sum declaration and initialization
printf("Enter First Number of an A.P Series:\n");
scanf("%d",&a); //First element initialization
printf("Enter the Total Numbers in this A.P Series:\n");
scanf("%d",&n); //total number of elements initialization
printf("Enter the Common Difference:\n");
scanf("%d", &d); //Common difference initialization
sum=(n*(2*a+(n-1)*d))/2; //total sum Formula
tn=a+(n-1)*d; //Last term formula
printf("\nThe Sum of Series A.P. :\n ");
for(i=a;i<= tn;i=i+d)
{
if(i!= tn)
printf("%d + ", i);
else
printf("%d = %d", i, sum);
}
printf("\n");
return 0;}

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

2. Write a C program to find the sum of array elements using recursion.


#include <stdio.h>
int sum(int arr[], int start, int len);
int main()
{
int arr[100];
int N, i,soa;
printf("Enter size of the array: ");
scanf("%d",&N);
printf("Enter elements in the array: ");
for(i=0; i<N; i++)
{
scanf("%d",&arr[i]);
}
soa = sum(arr,0,N);
printf("Sum of array elements: %d", soa);
}
int sum(int arr[],int start,int len)
{
if(start >= len) return 0;
return (arr[start]+sum(arr,start+1,len));
}

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;

/* Input two strings from user */


printf("Enter first string: ");
gets(str1);
printf("Enter second string: ");
gets(str2);

/* Move till the end of str1 */


while(*(++s1));

/* Copy str2 to str1 */


while(*(s1++) = *(s2++));

printf("Concatenated string = %s", str1);


return 0;
}

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

void add(struct distance d1, struct distance d2)


{
struct distance d3;
d3.feet = d1.feet + d2.feet;
d3.inch = d1.inch + d2.inch;
d3.feet = d3.feet + d3.inch / 12; //1 feet has 12 inches
d3.inch = d3.inch % 12;
printf("\nTotal distance- Feet: %d, Inches: %d", d3.feet, d3.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);

/*add two distances*/


add(d1, d2);
return 0;
}

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!");
}
} }

2. Write a C program to perform matrix multiplication

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

// Function to swap two students


void swap(struct Student *a, struct Student *b)
{
struct Student temp;
temp= *a;
*a = *b;

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

4. Develop a program to implement a calculator in C.


#include <stdio.h>
#include <stdlib.h>
// Driver code
int main()
{

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

// Using switch case we will differentiate


// operations based on different operator
switch (ch) {

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

// If operator doesn't match any case constant


default:
printf(
"Error! please write a valid operator\n");
}

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

// Calculate the sum of the series


for(i=1;i<=num;i++)
sum = sum + i;

// Display the last term of the series


printf(" 1/%d",num);

// Calculate and display the sum


printf("\nSum = 1/%d", sum +1/num);
return0;
}

6. Write a program in C to sort an array of integers using pointers.


#include <stdio.h>
int main(void)
{
int a[10];
int *p,i=0,j=0, n;
printf("\n enter the number of elements\n");
scanf("%d",&n);
printf("enter the elements one by one \n");
for(i=0;i<n;i++)
{
scanf("%d", &a[i]);
}
p=&a[0];
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(*(p+i)>*(p+j))
{
*(p+i) = *(p+i)+ *(p+j);
*(p+j) = *(p+i)- *(p+j);
*(p+i) = *(p+i)- *(p+j);

80
}
}
}
printf("\n Sorted Values : ");
for(i=0;i<n;i++)
{
printf("%d ",*(p+i));
}
return 0;
}

***************************************************************************

ADVANCED LEVEL PROGRAMS-WEEK 8

1. Write a program in C to sort a list of numbers using pass by reference.


#include <stdio.h>
void main()
{
int n,a[100],i;
void sortarray(int*,int);
printf("\nEnter the Number of Elements in an array : ");
scanf("%d",&n);
printf("\nEnter the Array elements\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
sortarray(a,n);
printf("\nAfter Sorting. .. \n");
for(i=0;i<n;i++)
printf("%d\n",a[i]);
}
void sortarray(int* arr,intnum)
{
int i,j,temp;
for(i=0;i<num;i++)
for(j=i+1;j<num;j++)
if(arr[i] >arr[j])
{
temp=arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}

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;

// Open one file for reading


fptr1 = fopen("file1.txt", "r");
if (fptr1 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
// Open another file for writing
fptr2 = fopen("file2.txt", "w");
if (fptr2 == NULL)

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

4. Write a C program to find largest number using dynamic memory allocation.

#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);
}

// Finding the largest number


for (int i = 1; i < n; ++i) {
if (*data < *(data + i)) {
*data = *(data + i);
}
}
printf("Largest number = %.2lf", *data);

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

printf("The merged array: ");


for(int i = 0; i < n3; i++)
printf("%d ", c[i]); //Print the merged array

printf("\nFinal array after sorting: ");


for(int i = 0; i < n3; i++)
{
int temp;
for(int j = i + 1; j < n3; j++)
{
if(c[i] > c[j])
{
temp = c[i];
c[i] = c[j];
c[j] = temp;
}
}
}
for(int i = 0; i < n3 ; i++) //Print the sorted Array
printf(" %d ",c[i]);
return 0;
}

***************************************************************************

ADVANCED LEVEL PROGRAMS-WEEK 9

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;

while(count <= inum)


{

85
if(start%count == 0)
{
prime = 0;
break;
}
count++;
}
if(prime) printf("%d, ", start);
start++;
}
printf("\n\n");
return 0;
}

2. Write a C program to replace all occurrences of a character in a string.

#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];

for (i = 0; i< j; i++)


arr[i] = temp[i];

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

4. Write a C program to display frequency histograms of each group.


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

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

5. Write a C program to delete a substring from a text.


#include<stdio.h>
#include<string.h>
int main()
{
int i, j = 0, k = 0,n = 0;
int flag = 0;
char str[100], neww[100], word[100];
printf("Enter Any String to Remove a Word from String: ");
gets(str);
printf("\nEnter Any Word You Want to be Removed: ");
gets(word);

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

printf("\nAfter Removing Word From String: %s",neww);


}

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

You might also like