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

Ai&ds-E Programming in C - Practical-Record

Uploaded by

sarathsince1997
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Ai&ds-E Programming in C - Practical-Record

Uploaded by

sarathsince1997
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

KARPAGAM ACADEMY OF HIGHER EDUCATION

(Deemed to be University)
(Established Under section 3 of UGC act 1956)
Accredited with A+ Grade by NAAC in the Second Cycle
Coimbatore-641021.

DEPARTMENT OF COMPUTER APPLICATIONS


I B.Sc. Computer Science-(AI&DS)

Programming in C– Practical
(24ADU101)
SEMESTER: I
(2024-2027 Batch)

NAME:

REG.NO:
KARPAGAM ACADEMY OF HIGHER EDUCATION
(Deemed to be University)
(Established Under section 3 of UGC act 1956)
Accredited with A+ Grade by NAAC in the Second Cycle
Coimbatore-641021.
DEPARTMENT OF COMPUTER APPLICATIONS

BONAFIDE CERTIFICATE

REGISTER NUMBER:

This is to certify that this is a Bonafide record work done by

of I B.Sc. Computer Science- (AI&DS) during the

academic year July 2024 to November– 2024 and submitted for the practical examination

in Programming in C – Practical (24ADU101) held on ------------------------

Staff-in-charge Head of the Department

Internal Examiner External Examiner


INDEX

PAGE STAFF
S.NO DATE TITLE
NO SIGNATURE

10

11

12
EX.NO: 1 SUM, AVERAGE, STANDARD DEVIATION
Date:

AIM:
To Write a C program to find the sum, average, standard deviation for a given set of numbers.

ALGORITHM:
Step 1:.Calculate the sum of all numbers in the set.
Step 2: Calculate the average by dividing the sum by the total number of elements in the set.
Step 3: Calculate the variance, which is the average of the squared differences between each
number and the average.
Step 4: Calculate the standard deviation, which is the square root of the variance.
Step5: Stop the program
SOURCE CODE

#include <stdio.h>
#include <math.h>
#define MAX_SIZE 100
int main() {
int n, i;
float numbers[MAX_SIZE], sum = 0.0, mean, deviation = 0.0;
printf("Enter the number of elements: ");
scanf("%d", &n);
printf("Enter %d numbers:\n", n);
for (i = 0; i < n; ++i) {
scanf("%f", &numbers[i]);
sum += numbers[i];
}
mean = sum / n;
for (i = 0; i < n; ++i) {
deviation += pow(numbers[i] - mean, 2);
}
deviation = sqrt(deviation / n);
printf("Sum = %.2f\n", sum);
printf("Average = %.2f\n", mean);
printf("Standard Deviation = %.2f\n", deviation);
return 0;
}
OUTPUT :
Enter the number of elements: 5
Enter 5 numbers:
2
4
6
8
10
Sum = 30.00
Average = 6.00
Standard Deviation = 2.83

RESULT:

This program prompts the user to enter the number of elements and the elements themselves.
Then, it calculates and prints the sum, average, and standard deviation of the given set of numbers.
EX NO: 2 PRIME, PERFECT, ARMSTRONG NUMBERS
Date:

AIM:

To Write a C program to generate n prime, perfect, Armstrong numbers.

ALGORITHM:
**Generate 'n' Prime Numbers:**
Step 1 : Start with a variable `num` initialized to 2.
Step 2 : Use a while loop to keep generating prime numbers until 'n' prime numbers are found.
Step 3 : Use a function to check if a number is prime or not.
Step 4: Increment `num` and check for the next prime number.
**Generate 'n' Perfect Numbers:**
Step 5: Start with a variable `num` initialized to 1.
Step 6: Use a while loop to keep generating perfect numbers until 'n' perfect numbers are found.
Step 7: Use a function to check if a number is perfect or not.
Step 8: Increment `num` and check for the next perfect number.
**Generate 'n' Armstrong Numbers:**
Step 8: Start with a variable `num` initialized to 1.
Step 9: Use a while loop to keep generating Armstrong numbers until 'n' Armstrong numbers are found.
Step 10: Use a function to check if a number is Armstrong or not.
Step 11: Increment `num` and check for the next Armstrong number.
SOURCE CODE:
#include <stdio.h>
#include <stdbool.h>
#include <math.h>

// Function to check if a number is prime


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

// Function to check if a number is perfect


bool isPerfect(int num) {
int sum = 1;
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
if (i * i != num)
sum = sum + i + num / i;
else
sum = sum + i;
}
}
if (sum == num && num != 1)
return true;
return false;
}

// Function to check if a number is Armstrong


bool isArmstrong(int num) {
int originalNum, remainder, result = 0, n = 0;
originalNum = num;

// store the number of digits of num in n


while (originalNum != 0) {
originalNum /= 10;
++n;
}
originalNum = num;
// check if a number is Armstrong
while (originalNum != 0) {
remainder = originalNum % 10;
result += pow(remainder, n);
originalNum /= 10;
}

if (result == num)
return true;
return false;
}

int main() {
int n;
printf("Enter the limit (n): ");
scanf("%d", &n);

printf("Prime numbers up to %d:\n", n);


for (int i = 2; i <= n; i++) {
if (isPrime(i))
printf("%d ", i);
}

printf("\nPerfect numbers up to %d:\n", n);


for (int i = 2; i <= n; i++) {
if (isPerfect(i))
printf("%d ", i);
}

printf("\nArmstrong numbers up to %d:\n", n);


for (int i = 1; i <= n; i++) {
if (isArmstrong(i))
printf("%d ", i);
}

return 0;
}
OUTPUT:
Enter the limit (n): 100
Prime numbers up to 100:
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
Perfect numbers up to 100:
6 28
Armstrong numbers up to 100:
1 2 3 4 5 6 7 8 9 153 370 371 407

RESULT:

The above program to generate n prime, perfect, Armstrong numbers successfully.


EX NO: 3 FIBONACCI SERIES
Date:

AIM:
To Write a C program to generate Fibonacci series

ALGORITHM:

Step 1: Generate 'n' Prime Numbers


Step 2: To generate 'n' prime numbers, we iterate over numbers starting from 2 and check each
number if it's prime.
Step 3: Once we find a prime number, we increment the count until we reach 'n'.
Step 4: Generate 'n' Perfect Numbers
Step 5: To generate 'n' perfect numbers, we iterate over numbers starting from 1 and check each
number if it's perfect.
Step 6: Once we find a perfect number, we increment the count until we reach 'n'.
Step 7: Generate 'n' Armstrong Numbers
Step 8:To generate 'n' Armstrong numbers, we iterate over numbers starting from 1 and check
each number if it's an Armstrong number.
Step 9: Once we find an Armstrong number, we increment the count until we reach 'n'.
SOURCE CODE:
#include <stdio.h>

void fibonacci(int n) {
int first = 0, second = 1, next, i;

printf("Fibonacci Series up to %d terms:\n", n);

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


if (i <= 1)
next = i;
else {
next = first + second;
first = second;
second = next;
}
printf("%d ", next);
}
}

int main() {
int n;
printf("Enter the number of terms: ");
scanf("%d", &n);
fibonacci(n);
return 0;
}
OUTPUT:

Enter the number of terms: 10


Fibonacci Series up to 10 terms:
0 1 1 2 3 5 8 13 21 34

Result:
Thus the above program has been executed successfully.
EX NO: 4 MAGIC SQUARE
Date:

AIM:
To Write a C program to print magic square of order n where n>3and n is odd.

ALGORITHM:
Step 1: Initialize the square with all elements as 0.
Step 2: Start from the middle column of the first row.
Step 3: Place the number 1 in the middle of the top row.
Step 4: Move diagonally up and to the right, placing the next number in the next cell. If moving
up or to the right would put you outside the square, wrap around to the opposite side.
Step 5: If the cell is already filled, move down one cell and continue.
Step 6: Repeat step 4 until all cells are filled with numbers from 1 to n^2.
SOURCE CODE:

#include <stdio.h>
void generateMagicSquare(int n) {
int magicSquare[n][n];

// Initialize all cells with 0


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
magicSquare[i][j] = 0;
}
}

// Start from the middle column of the first row


int row = 0, col = n / 2, num = 1;

// Fill the magic square


while (num <= n * n) {
// Place the number in the current cell
magicSquare[row][col] = num;

// Move to the next cell diagonally up and to the right


int nextRow = (row - 1 + n) % n;
int nextCol = (col + 1) % n;

// If the next cell is already filled or out of bounds, move down


if (magicSquare[nextRow][nextCol] != 0) {
row = (row + 1) % n;
} else {
row = nextRow; col = nextCol;
}

num++;
}

// Print the magic square


printf("Magic Square of order %d:\n", n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%d\t", magicSquare[i][j]);
}
printf("\n");
}
}

int main() {
int n;
// Prompt the user to enter the order of the magic square
printf("Enter the order of the magic square (n > 3 and n is odd): ");
scanf("%d", &n);

// Check if n is odd and greater than 3


if (n % 2 == 0 || n <= 3) {
printf("Invalid input! Please enter an odd number greater than 3.\n");
return 1;
}

// Generate and print the magic square


generateMagicSquare(n);

return 0;
}
OUTPUT:

Enter the order of the magic square (n > 3 and n is odd): 5


Magic Square of order 5:
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9

RESULT:
This code generates a magic square of order n and prints it out
EX NO: 5 SORTING
Date:

AIM:
To Write a C program to sort the given set of numbers in ascending order.

ALGORITHM:
Step 1: Start the program.
Step 2: Read the number of elements, n.
Step 3: Input n elements into an array number.
Step 4: Use nested loops to compare and swap elements to sort the array in ascending order.
Step 5: Print the sorted array.
Step 6: End the program.
SOURCE CODE:

#include<stdio.h>
#include<conio.h>
void main()
{
int i, j, a, n, number[30];

printf("Enter the value of N \n");


scanf("%d", &n);
printf("Enter the numbers \n");
for (i = 0; i < n; ++i)
scanf("%d", &number[i]);
for (i = 0; i < n; ++i)
{
for (j = i + 1; j < n; ++j)
{
if (number[i] > number[j])
{
a = number[i];
number[i] = number[j];
number[j] = a;
}
}
}
printf("The numbers arranged in ascending order are given below \n");
for (i = 0; i < n; ++i)
printf("%d\n", number[i]);
}
OUTPUT:

Enter the value of N:

Enter the numbers:

17 5 45 8 13

The numbers arranged in ascending order are given below

5 8 13 17 45

RESULT:
Thus the above program has been executed successfully
EX No: 6
PALINDROME
Date:

AIM:
To write a C program to check whether the given string is a palindrome or not using pointers

ALGORITHM:
Step 1: Start the Program
Step 2: initialize the two pointer variable ptr and rev.
Step 3: Initialize ptr to the base address of the string and move it forward to point to the last
character of the string.
Step 4: Now, initialize rev to the base address of the string and start moving rev in forward
direction and ptr in backward direction simultaneously until middle of the string is reached.
Step 5: If at any point the character pointed by ptr and rev does not match, then break from the
loop.
Step 6: Check if ptr and rev crossed each other, i.e. rev > ptr. If so, then the string is
palindrome otherwise not.
Step 7: End
SOURCE CODE:

// C program to check if a string is palindrome


// using pointers
#include <stdio.h>
// Function to check if the string is palindrome
// using pointers
void isPalindrome(char* string)
{
char *ptr, *rev;

ptr = string;

while (*ptr != '\0') {


++ptr;
}
--ptr;

for (rev = string; ptr >= rev;) {


if (*ptr == *rev) {
--ptr;
rev++;
}
else
break;
}
if (rev > ptr)
printf("String is Palindrome");
else
printf("String is not a Palindrome");
}
// Driver code
int main()
{
char str[1000] = "madam";

isPalindrome(str);

return 0;
}
OUTPUT:

Enter a String : radar


radar is a Palindrome

RESULT:
Thus the program has been successfully check the given string is a palindrome or not using
pointers
EX No:7 COUNT THE NUMBER OF VOWELS
Date:

AIM:
To write a C program to count the number of Vowels in the given sentence

ALGORITHM:

Step 1: Start the Program


Step 2: Initialize the variable in char str,
Step 3: Initialize the variable in int i and vowels
Step 4: Read the input values.
Step 5: Initialize for loop.
Step 6: Check and count the vowels.
Step 7: Terminate for loop.
Step 8: Print total count.
Step 9: Stop the process
SOURCE CODE :

#include <stdio.h>
#include <ctype.h>
int main()
{
// Initializing variable.
char str[100];
int i, vowels = 0;
// Accepting input.
printf("Enter the string: ");
// best way to read string rather than gets/fgets
scanf("%[^\n]s",&str);
//Initializing for loop.
for(i = 0; str[i]; i++)
{
//Counting the vowels.
if(str[i]=='a'|| str[i]=='e'||str[i]=='i'||
str[i]=='o'|| str[i]=='u'||str[i]=='A'||
str[i]=='E'||str[i]=='I'||str[i]=='O' ||str[i]=='U')
{
vowels++;
}
}
//Printing the count of vowels.
printf("Total number of vowels: = %d\n", vowels);
return 0;
}
OUTPUT:

Enter the string: I am human


Total number of vowels: = 4

RESULT:
Thus the program has been successfully count the number of Vowels in the given sentence.
EX No:8 FACTORIAL USING RECURSIVE FUNCTION
Date:

Aim:
Write a C program to find the factorial of a given number using recursive function

Algorithms:
Step 1: Start the program
Step 2: Ask the user to enter an integer to find the factorial
Step 3: Read the integer and assign it to a variable
Step 4: From the value of the integer up to 1, multiply each digit and update the final value
Step 5: The final value at the end of all the multiplication till 1 is the factorial
Step 6: End
SOURCE CODE:

#include<stdio.h>
long int multiplyNumbers(int n);
int main() {
int n;
printf("Enter a positive integer: ");
scanf("%d",&n);
printf("Factorial of %d = %ld", n, multiplyNumbers(n));
return 0;
}
long int multiplyNumbers(int n) {
if (n>=1)
return n*multiplyNumbers(n-1);
else
return 1;
}
OUTPUT:

Enter a positive integer: 6


Factorial of 6 = 720

RESULT:

Thus the Program has been successfully finding the factorial of a given number using recursive
function
EX No:9 STUDENTS MARK SHEET
Date:

AIM:
To write a C program to print the students Mark sheet assuming roll no, name, and marks in
5 subjects in a structure. Create an array of structures and print the mark sheet in the University
pattern

ALGORITHM:

Step 1: Start the program


Step 2: Initialize the variable firstName, roll,m1,m2,m3,m4 and m5
Step 3: Initialize the for loop
Step 4: read the input values
Step 5: Declare the array of structure
Step 6: Print and display the given values
Step 7: End
SOURCE CODE:

#include <stdio.h>
struct student {
char firstName[50];
int roll;
float m1,m2,m3,m4,m5;
} s[5];
int main()
{
int i;
printf("Enter information of students:\n");

// storing information
for (i = 0; i < 5; ++i) {
s[i].roll = i + 1;
printf("\nFor roll number%d,\n", s[i].roll);
printf("Enter first name: ");
scanf("%s", s[i].firstName);
printf("Enter mark1 English: ");
scanf("%f", &s[i].m1);
printf("Enter mark2 Tamil: ");
scanf("%f", &s[i].m2);
printf("Enter mark3 C Program: ");
scanf("%f", &s[i].m3);
printf("Enter mark4 DCP: ");
scanf("%f", &s[i].m4);
printf("Enter mark5 office automation: ");
scanf("%f", &s[i].m5);
}
printf("Displaying Information:\n\n");
// displaying information
for (i = 0; i < 5; ++i) {
printf("\nRoll number: %d\n", i + 1);
printf("First name: ");
puts(s[i].firstName);
printf("Marks: %.1f", s[i].m1);
printf("\n");
printf("Marks: %.1f", s[i].m2);
printf("\n");
printf("Marks: %.1f", s[i].m3);
printf("\n");
printf("Marks: %.1f", s[i].m4);
printf("\n");
printf("Marks: %.1f", s[i].m5);
printf("\n");
}
return 0;
OUTPUT:

Enter the number of students: 2


Enter details for student 1:
Roll No: 101
Name: John
Enter marks for 5 subjects:
Subject 1: 85
Subject 2: 76
Subject 3: 90
Subject 4: 88
Subject 5: 92

Enter details for student 2:


Roll No: 102
Name: Emily
Enter marks for 5 subjects:
Subject 1: 78
Subject 2: 82
Subject 3: 79
Subject 4: 85
Subject 5: 90

University Mark Sheet


==========================================================================
==
Roll No Name Subject 1 Subject 2 Subject 3 Subject 4 Subject 5 Total
==========================================================================
==
101 John 85.00 76.00 90.00 88.00 92.00 431.00
102 Emily 78.00 82.00 79.00 85.00 90.00 414.00
==========================================================================
==

RESULT:

Thus the program has been successfully print the students details.
EX No:10 MATRICES USING POINTER TO FUNCTION
Date:

AIM:
To write a function using pointers to add two matrices and to return the resultant matrix to the
calling function.

ALGORITHM:
Step 1: Start the program
Step 2: Initialize the two dimensional array variable a,b , row and col
Step 3: Initialize the Function declaration
Step 4: Read the input values
Step 5: Initialize the for loop
Step 6: Print the entered values
Step 7: Declare return 0
Step 8: End
SOURCE CODE:

#include<stdio.h>
#include<conio.h>
int a[5][5],b[5][5],row, col;
void add(int(*)[5]);
int main()
{
int c[5][5],i,j;
clrscr();
printf(“Enter row : “);
scanf(“%d”,&row);
printf(“Enter column : “);
scanf(“%d”,&col);
printf(“Enter matrix A :\n”);
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“Enter matrix B :\n”);
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
scanf(“%d”,&b[i][j]);
}
}
add(c);
printf(“Addition :\n”);
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf(“%d\t”,c[i][j]);
}
printf(“\n”);
}
getch();
return 0;
}
void add(int c[5][5])
{
int i,j;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
}
OUTPUT:

Enter row : 3
Enter column : 3
Enter matrix A :
333
333
333
Enter matrix B :
555
555
555
Addition :
8
8
8
8
8
8
8
8
8

RESULT:

Thus the program has been successfully executed the function using pointers to add two matrices
and to return the resultant matrix to the calling function.
EX No:11 COMPARE TWO FILES
Date:

AIM:
To write a C program which receives two filenames as arguments and check whether the file
contents are same or not. If same delete the second file.

ALGORITHM:

Step 1: Start the program


Step 2: Initialize the function declaration
Step 3: Open the files in read mode
Step 4: Compare the contents of the two files byte by byte until the end of either file is reached.
Step 5: If any byte differs between the files, return false.
Step 6: If both files reach the end simultaneously, return true indicating that the files have the
same content.
Step 7: Use the remove function from the standard C library to delete the file.
Step 8: Print a message indicating whether the deletion was successful.
Step 9: Close both files
Step 10: End
SOURCE CODE:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 1024
int compareFiles(const char *file1, const char *file2);
int deleteFile(const char *filename);
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: %s <file1> <file2>\n", argv[0]);
return 1;
}
if (compareFiles(argv[1], argv[2])) {
printf("Files %s and %s have the same contents.\n", argv[1], argv[2]);
if (deleteFile(argv[2]))
printf("File %s deleted successfully.\n", argv[2]);
else
printf("Unable to delete file %s.\n", argv[2]);
} else {
printf("Files %s and %s do not have the same contents.\n", argv[1], argv[2]);
}
return 0;
}
int compareFiles(const char *file1, const char *file2) {
FILE *fp1, *fp2;
char buffer1[BUFFER_SIZE];
char buffer2[BUFFER_SIZE];
fp1 = fopen(file1, "r");
if (fp1 == NULL) {
perror("Error opening file 1");
exit(1);
}
fp2 = fopen(file2, "r");
if (fp2 == NULL) {
perror("Error opening file 2");
exit(1);
}
while (!feof(fp1) && !feof(fp2)) {
size_t bytesRead1 = fread(buffer1, 1, BUFFER_SIZE, fp1);
size_t bytesRead2 = fread(buffer2, 1, BUFFER_SIZE, fp2);
if (bytesRead1 != bytesRead2 || memcmp(buffer1, buffer2, bytesRead1) != 0) {
fclose(fp1);
fclose(fp2);
return 0; // Files are different
}
}
// Check if both files have reached EOF
if (feof(fp1) && feof(fp2)) {
fclose(fp1);
fclose(fp2);
return 1; // Files are the same
} else {
fclose(fp1);
fclose(fp2);
return 0; // Files are different
}
}
int deleteFile(const char *filename) {
if (remove(filename) == 0)
return 1; // Success
else
return 0; // Failure
}
OUTPUT:

File1.txt
This is file1.txt.

File2.txt
This is file1.txt.

./file_compare file1.txt file2.txt

File contents are the same. Deleting file2.txt...


file2.txt deleted successfully.

RESULT:

Thus the program has been successfully receives two filenames as arguments and check whether
the file contents are same or not. If same delete the second file.
EX No:12 COPY A FILE AND APPEND ITS CHARACTER, WORD, AND LINE COUNTS
Date:

AIM:
To write a program which takes a file as command line argument and copy it to another file. At
the end of the second file write the total i) no.of chars ii) no.of words and iii)no.of lines.

ALGORITHM:
Step 1: Start the program
Step 2: Declare the file
Step 3: Initialize the variable
Step 4: Read the input of source file
Step 5: Initialize the if condition to check the file is exists
Step 6: Initialize the while loop to check the characters , words and lines
Step 8: Close the files
Step 9: End
SOURCE CODE:

#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * file;
char path[100];
char ch;
int characters, words, lines;
/* Input path of files to merge to third file */
printf("Enter source file path: ");
scanf("%s", path);
/* Open source files in 'r' mode */
file = fopen(path, "r");
/* Check if file opened successfully */
if (file == NULL)
{
printf("\nUnable to open file.\n");
printf("Please check if file exists and you have read privilege.\n");
exit(EXIT_FAILURE);
}
characters = words = lines = 0;
while ((ch = fgetc(file)) != EOF)
{
characters++;
if (ch == '\n' || ch == '\0')
lines++;
if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\0')
words++;
}
/* Increment words and lines for last word */
if (characters > 0)
{
words++;
lines++;
}

/* Print file statistics */


printf("\n");
printf("Total characters = %d\n", characters);
printf("Total words = %d\n", words);
printf("Total lines = %d\n", lines);
/* Close files to release resources */
fclose(file);
return 0;
}
INPUTS :

I love programming.
Working with files in C programming is fun.
I am learning C programming at Code for win.

OUTPUTS :

Enter source file path: data\file3.txt


Total characters = 106
Total words = 18
Total lines =3

RESULT:

Thus the program has been successfully takes a file as command line argument and copy it to
another file. At the end of the second file write the total.

You might also like