0% found this document useful (0 votes)
40 views68 pages

Cool

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)
40 views68 pages

Cool

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

1.

Write a C program to read 3 integer numbers and find the average of those 3
numbers?

CODE:
#include <stdio.h>

int main()
{
int a,b,c;
float avg;
scanf("%d %d %d",&a,&b,&c);
avg=(a+b+c)/3.0;
printf("Average of 3 nos. is: %.2f",avg);

return 0;
}
OUTPUT:

2. Write a C program to check whether the given no. is even or odd using ternary
operator?

CODE:
#include <stdio.h>

int main()
{
int n;
scanf("%d",&n);
(n%2==0)?printf("n is even no."):printf("n is odd no.");

return 0;
}
OUTPUT SCREENSHOTS:

3. Write a C program to read 4 integers and display max no. & min no.?

CODE:
#include <stdio.h>

int main()
{
int a,b,c,d;
scanf("%d %d %d %d",&a,&b,&c,&d);
int max,min;
max=min=a;
if(max<a)
max=a;
else if(min>a)
min=a;
if(max<b)
max=b;
else if(min>b)
min=b;
if(max<c)
max=c;
else if(min>c)
min=c;
if(max<d)
max=d;
else if(min>d)
min=d;
printf("Max no. is %d",max);
printf("\nMin no. is %d",min);

return 0;
}

OUTPUT:

4. Write a C program for opting the program offered by VIT University? The students
are eligible for choosing the program when he/she gets the rank less than 1,00,000.
Programs offered:
1) 1 to 1000 rank can choose B.Tech CSE
2) 1001 to 10000 rank can choose B.Tech Electronics
3) 10001 to 50000 rank can choose B.Tech Mechanical
4) 50001 to 100000 rank can choose B.Tech Civil.

CODE:
#include <stdio.h>

int main()
{
int rank;
printf("Enter the Rank\n");
scanf("%d",&rank);
if(rank > 100000)
{
printf("Not elgible to get Admission in VIT University");
return 0;
}
else
{
if(rank>0 && rank<=1000)
{
printf("Programs that you are eligible to choose are:\n");
printf("1. B.Tech CSE\n");
printf("2. B.Tech EEE\n");
printf("3. B.Tech ME\n");
printf("4. B.Tech CE\n");
return 0;
}
else if(rank>1000 && rank<=10000)
{
printf("Programs that you are eligible to choose are:\n");
printf("1. B.Tech EEE\n");
printf("2. B.Tech ME\n");
printf("3. B.Tech CE\n");
return 0;
}
else if(rank>10000 && rank<=50000)
{
printf("Programs that you are eligible to choose are:\n");
printf("1. B.Tech ME\n");
printf("2. B.Tech CE\n");
return 0;
}
else
{
printf("Programs that you are eligible to choose are:\n");
printf("Only B.Tech CE\n");
return 0;
}
}
}
OUTPUT:
5. Write a C program to print whether the give no. is prime or not in the range of 200
to 500?
CODE:
#include <stdio.h>
#include <stdbool.h>

int main()
{
for(int i=200;i<=500;i++)
{
if(i%2 !=0 && i%3!=0)
{
bool isPrime=true;
for(int j=5;j*j<=i;j+=6)
{
if(i%j==0 || i%(j+2)==0)
{
isPrime=false;
break;
}
}
if(isPrime)
printf("%d ",i);
}
}
return 0;
}

OUTPUT:
6. Write a C program to print the following pattern for n time consider test case as
n=5?
A
AB
ABC
ABCD
ABCDE

CODE:
/*5. Write a C program to print the following pattern for n time consider test case as n=5?
A
AB
ABC
ABCD
ABCDE
*/
#include <stdio.h>

int main()
{
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
char ch ='A';
for(int j=0;j<=i;j++)
{
printf("%c ",ch);
ch++;
}
printf("\n");
}

return 0;
}
OUTPUT:

7. Write a C program to find sum of even nos. & sum of odd nos. in an array?

CODE:
#include<stdio.h>

int main()
{
int n;
scanf("%d",&n);
int a[n];
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
int e=0,o=0;
for(int i=0;i<n;i++)
{
if(a[i]%2==0)
e+=a[i];
else
o+=a[i];
}
printf("Even sum is: %d",e);
printf("\nOdd sum is: %d",o);
return 0;
}

OUTPUT:

8. Write a C program to calculate max and 2nd max from the given 10 nos. without
using sorting techniques?
CODE:
#include<stdio.h>
int main()
{
int n;
scanf("%d",&n);
int a[n];
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
int m1=a[0],m2=a[0];
for(int i=0;i<n;i++)
{
if(a[i]>m1)
{
m2=m1;
m1=a[i];
}
}
printf("Max element is: %d",m1);
printf("\n2nd Max element is: %d",m2);
}
OUTPUT:
9. Write a C program for 2x2 matrix and display sum, subtraction,
multiplication of 2 matrices.
CODE:
#include <stdio.h>

int main()
{
int a[2][2],b[2][2],add[2][2],sub[2][2],mul[2][2];
printf("Give input for 1st matrix:\n");
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
scanf("%d",&a[i][j]);
printf("Give input for 2nd matrix:\n");
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
scanf("%d",&b[i][j]);

// ADDITION of two matrices


for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
{
add[i][j]=a[i][j]+b[i][j];
sub[i][j]=a[i][j]-b[i][j];
mul[i][j] = 0;
for (int k = 0; k < 2; k++) {
mul[i][j] += a[i][k] * b[k][j];
}
}
printf("Addition result is:\n");
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
printf("%d ",add[i][j]);
printf("\n");
}
printf("Subtraction result is:\n");
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
printf("%d ",sub[i][j]);
printf("\n");
}
printf("multiplication result is:\n");
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
printf("%d ",mul[i][j]);
printf("\n");
}
return 0;
}
OUTPUT:
10. Write a C program to compute transpose of a given matrix Transpose(A) where let
A be 3x3 matrix?
CODE:
#include<stdio.h>

int main()
{
int a[3][3];
for(int i=0;i<3;i++)
for( int j=0;j<3;j++)
scanf("%d",&a[i][j]);
printf("\nTransposed Matrix is:\n");
for(int i=0;i<3;i++)
{
for( int j=0;j<3;j++)
printf("%d ",a[j][i]);
printf("\n");
}
return 0;
}
OUTPUT:

11. Write a C program to compute sum of left diagonal & right diagonal elements?
CODE:
#include <stdio.h>

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

for(int i=0;i<3;i++)
{
left_Dsum+=a[i][i];
if(i!=(3/2))
right_Dsum+=a[i][3-i-1];
}
printf("Total of Left and Right diagonal including centre element only once
is:\n%d",left_Dsum+right_Dsum);
return 0;
}
OUTPUT:

12. Write a C program to display a 2D Array of 5x5 with following constraints


if the no. in the matrix is prime print it with “*”
if the no. in the matrix is even print it with “+”
if the no. in the matrix is odd print it with “-”
Inputs of 5x5 matrix are

5 10 15 12 11
4 2 7 9 10
55 20 17 18 19
13 12 15 11 16
7 6 3 1 2

CODE:
#include <stdio.h>
#include <stdbool.h>

bool isPrime(int x);


bool EvenOdd(int x)
{
if(x%2==0) return true;
else return 0=false;
}

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

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

printf("\n\n");
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(isPrime(a[i][j]))
printf("* ");
else
{
if(EvenOdd(a[i][j])) printf("+ ");
else printf("- ");
}
}
printf("\n");
}
return 0;
}
OUTPUT:

13. Write a C program for the following


a. Factorial of given no.
CODE:
#include <stdio.h>

int main()
{
int n,fact=1;
scanf("%d",&n);
for(int i=1;i<=n;i++)
fact*=i;
printf("\nFactorial of the given n is: %d",fact);
return 0;
}
OUTPUT:

b. Fibonacci sequence upto given integer n.


CODE:
#include <stdio.h>

int main()
{
int a=0,b=1,c,n;
scanf("%d",&n);
for(int i=2;i<n;i++)
{
c=a+b;
a=b;
b=c;
}
printf("\nNth Fibonacci is: %d",c);
return 0;
}
OUTPUT:

c. 1+ 1/1! + 2/2! + 3/3! + 4/4! + ………+ n/n!


CODE:
#include <stdio.h>

int fact(int x)
{
int f=1;
for(int i=1;i<=x;i++)
f*=i;
return f;
}

int main()
{
int n;
scanf("%d",&n);
float sum=1;
for(int i=1;i<=n;i++)
sum+= (float) i/fact(i);
printf("\nSum of the sequence upto n is: %f",sum);
return 0;
}
OUTPUT:

d. Compute the given no. in reverse order


CODE:
#include <stdio.h>

int main()
{
int n;
scanf("%d",&n);
int rev=0;
while(n>0)
{
int rem=n%10;
rev=rev*10+rem;
n/=10;
}
printf("\nReverse of the given no. is: %d",rev);
return 0;
}
OUTPUT:

14. Write a C program to read 5 students names print the names of the given students?
CODE:
#include <stdio.h>

int main()
{
char str[5][20];
for(int i=0;i<5;i++)
scanf("%19s",str[i]);
for(int i=0;i<5;i++)
printf("\nThe names are: %s\n",str[i]);
return 0;
}
OUTPUT:
15. Write a C program to find length of a given string without using length function?
CODE:
#include <stdio.h>

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

char str[n][20];

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


for (int j = 0; j < n; j++)
scanf("%s", str[j]);

int i = 0;
while (str[0][i] != '\0') {
i++;
}
printf("Length of the first string is: %d\n", i);
return 0;
}
OUTPUT:

16. Write a C program to check the given string is palindrome or not?


CODE:
#include <stdio.h>
#include <stdbool.h>
#include <string.h>

int main() {
int n;

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


scanf("%d", &n);

char strings[n][20];
printf("Enter %d strings:\n", n);
for (int i = 0; i < n; i++) {
scanf("%s", strings[i]);
}

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


int length = strlen(strings[i]);
bool isPalindrome = true;

for (int j = 0, k = length - 1; j < k; j++, k--) {


if (strings[i][j] != strings[i][k]) {
isPalindrome = false;
break;
}
}

if (isPalindrome) {
printf("%s is a palindrome.\n", strings[i]);
} else {
printf("%s is not a palindrome.\n", strings[i]);
}
}

return 0;
}

OUTPUT:
1. Write a program to read 10 students fname and lname and combine them and then
print?

CODE:
#include <stdio.h>

void concatenate(char destination[], char source[]) {


int i, j;

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

for (j = 0; source[j] != '\0'; j++) {


destination[i + j] = source[j];
}
destination[i + j] = '\0';
}

int main() {

char first_names[10][20];
char last_names[10][20];
char full_names[10][40];

for (int i = 0; i < 10; i++) {


printf("Enter student's first name: ");
scanf("%s", first_names[i]);

printf("Enter student's last name: ");


scanf("%s", last_names[i]);

concatenate(full_names[i], first_names[i]);
concatenate(full_names[i], " ");
concatenate(full_names[i], last_names[i]);
}

printf("Combined names of 10 students:\n");


for (int i = 0; i < 10; i++) {
printf("%s\n", full_names[i]);
}

return 0;
}

OUTPUT:
2. Write a program to compute SI function with 3 arguments?

CODE:
#include <stdio.h>

float calculateSI(float principal, float rate, float time) {


return (principal * rate * time) / 100.0;
}

int main() {
float principal, rate, time;
printf("Enter principal amount: ");
scanf("%f", &principal);

printf("Enter rate of interest (in percentage): ");


scanf("%f", &rate);

printf("Enter time period (in years): ");


scanf("%f", &time);

float si = calculateSI(principal, rate, time);

printf("Simple Interest = %.2f\n", si);

return 0;
}

OUTPUT SCREENSHOTS:

3. Write a function to calculate factorial of a given no.?

CODE:
#include <stdio.h>

int factorial(int n) {
int result = 1;

for (int i = n; i >= 1; i--) {


result *= i;
}
return result;
}
int main() {
int number;

printf("Enter a number: ");


scanf("%d", &number);

int fact = factorial(number);

printf("Factorial of %d is %d\n", number, fact);

return 0;
}

OUTPUT:

4. Write a c program to swap given 2 values using funtions pass by value and
reference?

CODE:
#include <stdio.h>
int swapbyRef(int *a,int *b)
{
return *b=*a+*b-(*a=*b);
}

void swapbyVal(int a, int b)


{
printf("%d %d\n",a,b=a+b-(a=b));
}
int main()
{
int a,b;
scanf("%d %d",&a,&b);
printf("First Swapping via Call by Value:\n");
swapbyVal(a,b);
printf("Second Swapping via Call by Reference:\n");
swapbyRef(&a,&b);
printf("%d %d\n",a,b);
return 0;
}

OUTPUT:

5. Write a recursive funtion to calculate sum of n nos.


CODE:
#include <stdio.h>
int sum(int n)
{
int c=0;
if(n<1) return c;
c+=n;
return c+sum(n-1);
}
int main()
{
int n;
scanf("%d",&n);
int result = sum(n);
printf("Sum of n numbers using Recursion is: %d", result);
return 0;
}

OUTPUT:

6. Write a recursive funtions to find the following


A) Factorial of a given no.
B) Fibanocci sequence

CODE:
A) Factorial of a given no.
#include <stdio.h>

int fact(int n)
{
int f = 1;
if(n<2) return f;
f *=n;
return f*fact(n-1);
}
int main()
{
int n;
scanf("%d",&n);
int result = fact(n);
printf("Factorial of the given number using Recursion is: %d",result );
return 0;
}

OUTPUT:

B) Nth Fibanacci using recursive


#include <stdio.h>
int fib(int n)
{
if(n<=1) return n;
return fib(n-1)+fib(n-2);
}
int main()
{
int n;
scanf("%d",&n);
int result = fib(n);
printf("Nth Fibanacci using Recursive approach is: %d",result);
return 0;
}

OUTPUT:
7. Write a program to read a line of text and calculate or display no. of vowels and no.
of consonants apart from that display the no. of spaces in the given line.

CODE:
#include <stdio.h>
#include <string.h>

int main()
{
char c[75];
scanf("%s",c);
int vowels=0,spaces=0,consonants=0;

for(int i=0;i<strlen(c);i++)
{
if(c[i] == 'a' || c[i]=='e'||c[i]=='i'||c[i]=='o' || c[i] =='u')
vowels++;
else if(c[i]==' ') spaces++;
else if(c[i]>='a' && c[i]<='z') consonants++;
}

printf("Number of Vowels in the given string is: %d\n",vowels);


printf("Number of Consonants in the given string is: %d\n",consonants);
printf("Number of Spaces in the given string is: %d\n",spaces);

return 0;
}

OUTPUT:
8. Write a program to check whether the given string is a substring of given line of
text.
CODE:

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

int main()
{
char str[20],check[20];
printf("Enter original String\n");
scanf("%s",str);
printf("Enter Sub String\n");
scanf("%s",check);
for(int i=0;i<=strlen(str)-strlen(check);i++)
{
int j;
for(j=0;j<strlen(check);j++)
{
while (str[i] == ' ')
i++;
if(str[i+j]!=check[j]) break;
}
if(j==strlen(check))
{
printf("yes it is sub string");
exit(0);
}
}
printf("Not a Sub String");
return 0;
}

OUTPUT:
9. Write a c program to compute sum of N elements using dynamic
memory allocation?
CODE:
#include <stdio.h>
#include<stdlib.h>

int main()
{
int n,sum=0,*array;

printf("Enter number of elements\n");


scanf("%d",&n);

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

for(int i=0;i<n;i++)
{
scanf("%d",&array[i]);
sum+=array[i];
}
printf("Sum of elements\n");
printf("%d",sum);

return 0;

}
OUTPUT:

10. Writ a c program to find maximum and minimum of given n elements using
Dynamic Memory Allocation?
CODE:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n;
printf("Enter number of elements\n");
scanf("%d",&n);
int *array;
array = (int *)malloc(n*sizeof(int));
for(int i=0;i<n;i++)
{
scanf("%d",&array[i]);
}
int min=array[0],max = array[0];
for(int i=0;i<n;i++)
{
if(array[i]<min) min=array[i];
else if(array[i]>max) max = array[i];
}

printf("Max value in the array is: %d \nMin value in the array is: %d",max,min);
return 0;
}

OUTPUT:
1. Write a case-insensitive function that will take a string and count of each letter in the
string.
E.g: VIT Preparing for RIVERA
condition: you function should take single string argument and return a dynamically
allocated array of 26 integers representing the count of each of the letter A-z respectively.

CODE:
#include<stdio.h>
#include<string.h>
#include<ctype.h>
#include <stdlib.h>

int* count(char str[])


{
int *array = (int*)malloc(26 * sizeof(int));
if (array == NULL) {
printf("Memory allocation failed!\n");
exit(1);
}
for (int i = 0; i < 26; i++) {
array[i] = 0;
}
for(int i=0;i<str[i]!='\0';i++)
{
int x = tolower(str[i]);
if(x>=97 && x<=122)
array[x - 'a']++;
}
return array;
}

int main()
{
char str[50];
fgets(str, sizeof(str), stdin);
int *array = count(str);

for(int i=0;i<26;i++)
{
if(array[i]>0)
printf("%c %d\n",(char) (97+i),array[i]);
}

free(array);
}

OUTPUT:
2. Write a c program to need N student records and calculate the average marks of each
student and also display it by calling the function called display? passing structure
into function arguments
The attributes of student record are
Student no. - int
Student name - string of length 25

M1 - int
M2 - int
M3 - int
Average - float?

CODE:
#include <stdio.h>
#include <string.h>
// Define a structure for student record
struct StudentRecord {
int studentNo;
char studentName[25];
int m1;
int m2;
int m3;
float average;
};

// Function to calculate average marks for a student record


void calculateAverage(struct StudentRecord *student) {
student->average = (student->m1 + student->m2 + student->m3) / 3.0;
}

// Function to display student record


void display(struct StudentRecord student) {
printf("Student No: %d\n", student.studentNo);
printf("Student Name: %s\n", student.studentName);
printf("Marks: M1=%d, M2=%d, M3=%d\n", student.m1, student.m2, student.m3);
printf("Average: %.2f\n\n", student.average);
}

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

// Declare an array of structures to hold student records


struct StudentRecord students[n];

// Input student records


for (int i = 0; i < n; i++) {
printf("\nEnter details for student %d:\n", i + 1);
printf("Student No: ");
scanf("%d", &students[i].studentNo);
printf("Student Name: ");
scanf("%s", students[i].studentName);
printf("Marks for M1: ");
scanf("%d", &students[i].m1);
printf("Marks for M2: ");
scanf("%d", &students[i].m2);
printf("Marks for M3: ");
scanf("%d", &students[i].m3);

// Calculate average marks for each student


calculateAverage(&students[i]);
}
// Display student records
printf("\nStudent Records:\n");
for (int i = 0; i < n; i++) {
printf("\nDetails of student %d:\n", i + 1);
display(students[i]);
}

return 0;
}

OUTPUT SCREENSHOTS:

3. Write a c program to read 2 distances in feet and inches and display the sum of two
distances. Using structure?

CODE:

#include <stdio.h>

// Define a structure to represent a distance


struct Distance {
int feet;
int inches;
};

// Function to add two distances


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

// Add inches
sum.inches = d1.inches + d2.inches;

// Convert excess inches to feet


sum.feet = d1.feet + d2.feet + (sum.inches / 12);
sum.inches %= 12; // Update inches if greater than 12

return sum;
}

// Function to display a distance


void displayDistance(struct Distance d) {
printf("Sum of distances: %d feet %d inches\n", d.feet, d.inches);
}

int main() {
struct Distance distance1, distance2, sum;

// Input distance 1
printf("Enter distance 1 (feet inches): ");
scanf("%d %d", &distance1.feet, &distance1.inches);

// Input distance 2
printf("Enter distance 2 (feet inches): ");
scanf("%d %d", &distance2.feet, &distance2.inches);

// Add distances
sum = addDistances(distance1, distance2);

// Display sum of distances


displayDistance(sum);

return 0;
}
OUTPUT:
4. Write a C program to maintain a list of N elements dynamically and implement the
following operations

1) Insert
2) Delete
3) Display

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

typedef struct Node


{
int val;
struct Node* next;
} Node;

Node* head = NULL;

void insertEnd(int data)


{
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->val = data;
newNode->next = NULL;

if (head == NULL)
{
head = newNode;
}
else
{
Node* current = head;
while (current->next != NULL)
{
current = current->next;
}
current->next = newNode;
}
}

void delete(int data)


{
if (head == NULL)
{
printf("Linked list is empty\n");
return;
}

Node* current = head;


Node* prev = NULL;

while (current != NULL && current->val != data)


{
prev = current;
current = current->next;
}

if (current == NULL)
{
printf("Node not found\n");
return;
}

if (prev == NULL)
{
head = current->next;
}
else
{
prev->next = current->next;
}

free(current);
}

void display()
{
Node* current = head;
if (current == NULL)
{
printf("Linked list is empty\n");
}
else
{
while (current != NULL)
{
printf("%d ", current->val);
current = current->next;
}
printf("\n");
}
}

int main()
{
int choice, data;

while (1)
{
printf("\nMenu:\n");
printf("1. Insert at the end\n");
printf("2. Delete a value\n");
printf("3. Display\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice)
{
case 1:
printf("Enter value to insert: ");
scanf("%d", &data);
insertEnd(data);
break;
case 2:
printf("Enter value to delete: ");
scanf("%d", &data);
delete(data);
break;
case 3:
printf("Linked list: ");
display();
break;
case 4:
printf("Exiting program.\n");
exit(0);
default:
printf("Invalid choice. Please try again.\n");
}
}

return 0;
}

OUTPUT:
1. Write a C program to compute maximum of n values using varaidic functions?

CODE:
#include <stdio.h>
#include <stdarg.h>
#include <limits.h>

int max(int number, ...) {


va_list list;
va_start(list, number);
int max_value = INT_MIN;

for (int i = 0; i < number; i++) {


int current = va_arg(list, int);
max_value = (current > max_value) ? current : max_value;
}

va_end(list);
return max_value;
}

int main() {
printf("Maximum value: %d\n", max(6, 113, 1, 222, 5, 6, 99));
return 0;
}

OUTPUT:
2. Write a C program to compute sum of n values using varaidic functions?

CODE:

#include <stdio.h>
#include <stdarg.h>

// Function to compute the sum of n values using variadic functions


int sum(int n, ...) {
va_list args;
va_start(args, n);

int total = 0;
for (int i = 0; i < n; i++) {
total += va_arg(args, int);
}

va_end(args);
return total;
}

int main() {
// Example usage of sum function
printf("Sum: %d\n", sum(5, 10, 20, 30, 40, 50)); // Sum: 150
printf("Sum: %d\n", sum(3, 1, 2, 3)); // Sum: 6

return 0;
}

OUTPUT SCREENSHOTS:
3. Write a C program to read the contents of the file named "sample.txt" and print the
contents into the console ?

CODE:

#include <stdio.h>

int main() {
FILE *file;
char ch;

// Open the file in read mode


file = fopen("sample.txt", "r");

// Check if file opened successfully


if (file == NULL) {
printf("Error: Unable to open the file.\n");
return 1;
}

// Read and print the contents of the file


printf("Contents of the file:\n");
while ((ch = fgetc(file)) != EOF) {
printf("%c", ch);
}

// Close the file


fclose(file);
return 0;
}

OUTPUT:

4. Describe all formatted and unformatted i/p o/p statements and show implemented
examples of each Statement?

CODE:
#include <stdio.h>
#include <string.h>

int main() {
// Formatted Input
int num;
printf("Formatted Input: Enter an integer: ");
scanf("%d", &num);

// Formatted Output
printf("Formatted Output: The number you entered is: %d\n", num);

// Unformatted Input
char ch;
printf("Unformatted Input: Enter a character: ");
ch = getchar(); // Consume newline character from previous scanf
ch = getchar(); // Read the actual character entered by the user

// Unformatted Output
printf("Unformatted Output: You entered the character: ");
putchar(ch);
putchar('\n');

// Formatted Input (String)


char str[100];
printf("Formatted Input (String): Enter a string: ");
scanf("%s", str);

// Formatted Output (String)


printf("Formatted Output (String): You entered the string: %s\n", str);

// Unformatted Input (String)


char str2[100];
printf("Unformatted Input (String): Enter a string: ");
getchar(); // Consume newline character left by previous input
fgets(str2, 100, stdin); // Read string including spaces

// Remove trailing newline if present


if ((strlen(str2) > 0) && (str2[strlen(str2) - 1] == '\n')) {
str2[strlen(str2) - 1] = '\0';
}

// Unformatted Output (String)


printf("Unformatted Output (String): You entered the string: %s\n", str2);

return 0;
}

OUTPUT SCREENSHOTS:

5. Write a c program to write sample text information into a file and display the same
on the screen along with number of vowels and no. Of consonants count.

CODE:

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

void countVowelsAndConsonants(const char *text, int *vowels, int *consonants) {


*vowels = *consonants = 0;
while (*text) {
char ch = *text;
if (isalpha(ch)) {
ch = tolower(ch); // Convert to lowercase for easier comparison
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
(*vowels)++;
else
(*consonants)++;
}
text++;
}
}

int main() {
// Write sample text information into a file
FILE *file = fopen("sample.txt", "w");
if (file == NULL) {
printf("Error: Could not open the file.\n");
return 1;
}

const char *text = "This is a sample text for demonstration purposes.";


fprintf(file, "%s", text);
fclose(file);
printf("Sample text information written to file successfully.\n");

// Read the file and display the text along with vowel and consonant counts
file = fopen("sample.txt", "r");
if (file == NULL) {
printf("Error: Could not open the file.\n");
return 1;
}

char buffer[1000];
fgets(buffer, sizeof(buffer), file);
fclose(file);

int vowels, consonants;


countVowelsAndConsonants(buffer, &vowels, &consonants);

printf("\nText from file:\n%s\n", buffer);


printf("Number of vowels: %d\n", vowels);
printf("Number of consonants: %d\n", consonants);

return 0;
}

OUTPUT:
6. Write a c program to write the text into the file consisting of special characters and
calculate or compute no. Of special characters available in the given file..

CODE:

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

int countSpecialCharacters(const char *text) {


int count = 0;
while (*text) {
if (!isalnum(*text) && !isspace(*text)) {
count++;
}
text++;
}
return count;
}

int main() {
// Write text with special characters into a file
FILE *file = fopen("special.txt", "w");
if (file == NULL) {
printf("Error: Could not open the file.\n");
return 1;
}

const char *text = "This is a sample text with special characters: !@#$%^&*()";
fprintf(file, "%s", text);
fclose(file);
printf("Text with special characters written to file successfully.\n");

// Read the file and calculate the number of special characters


file = fopen("special.txt", "r");
if (file == NULL) {
printf("Error: Could not open the file.\n");
return 1;
}

char buffer[1000];
fgets(buffer, sizeof(buffer), file);
fclose(file);

int specialCharacters = countSpecialCharacters(buffer);

printf("\nText from file:\n%s\n", buffer);


printf("Number of special characters: %d\n", specialCharacters);

return 0;
}

OUTPUT:

7. Write a c program to read or write a line of text in the position of nth line?

CODE:

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

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


if (argc != 5) {
printf("Usage: %s <input_file> <output_file> <line_number> <text>\n", argv[0]);
return 1;
}

// Open the input file for reading


FILE *input_file = fopen(argv[1], "r");
if (input_file == NULL) {
printf("Error: Unable to open the input file.\n");
return 1;
}

// Open the output file for writing


FILE *output_file = fopen(argv[2], "w");
if (output_file == NULL) {
printf("Error: Unable to open the output file.\n");
fclose(input_file);
return 1;
}

int line_number = atoi(argv[3]); // Convert string argument to integer


if (line_number <= 0) {
printf("Error: Invalid line number.\n");
fclose(input_file);
fclose(output_file);
return 1;
}

// Read and copy lines from input file to output file


char buffer[1000];
int current_line = 1;
while (fgets(buffer, sizeof(buffer), input_file) != NULL) {
if (current_line == line_number) {
fprintf(output_file, "%s\n", argv[4]); // Write the text at the nth line
}
fprintf(output_file, "%s", buffer);
current_line++;
}

// If line_number is greater than the number of lines in the input file,


// write the text at the end of the output file
if (line_number > current_line) {
fprintf(output_file, "%s\n", argv[4]);
}

// Close the files


fclose(input_file);
fclose(output_file);

printf("Text inserted successfully at line %d.\n", line_number);


return 0;
}
OUTPUT:

Usage: ./a.out <input_file> <output_file> <line_number> <text>

8. Write a c program to display last n characters of from the given file “sample.txt”.

CODE:

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

void createSampleFile(const char *filename) {


FILE *file = fopen(filename, "w");
if (file == NULL) {
printf("Error: Unable to create the sample file.\n");
exit(1);
}

fprintf(file, "This is a sample text file.\n");


fprintf(file, "It contains some text for testing.\n");
fprintf(file, "We will read the last n characters from this file.\n");

fclose(file);
}

int main() {
FILE *fp;
int n;
char ch;

// Create the sample text file


createSampleFile("sample.txt");
printf("Sample text file created successfully.\n");

// Open the sample text file for reading


fp = fopen("sample.txt", "r");
if (fp == NULL) {
printf("Unable to open the sample file.\n");
exit(1);
}

// Prompt the user to enter the number of characters to read from the file
printf("Enter number of characters to read from the file: ");
scanf("%d", &n);

// Move the file pointer to the appropriate position to read the last n characters
fseek(fp, -n, SEEK_END);

// Read and print the last n characters from the file


printf("Last %d characters from the file:\n", n);
while ((ch = fgetc(fp)) != EOF) {
printf("%c", ch);
}

// Close the file


fclose(fp);

return 0;
}

OUTPUT:
Q) Write a function count(number, array, length) that counts the number of times number
appears in array. The array has length elements. The function should be recursive.

Code:

int count(int num,int arr[],int len)

if(len==0) return 0;

int freq=(arr[len - 1] == num);

return (freq + count(num,arr,len-1));

Q) A Martian leap year is all years divisible by 5 or divisible by 7, but not divisible by both.
Write a C function it reads in the year from the user to consider, it prints out “YES” if the year is
a Martian leap year and “NO” otherwise.

Code:

if((n%5 == 0 && n%7 != 0) || (n%5 != 0 && n%7 == 0)) printf("Yes");

else printf("No");

Q) Create a structure(typedef) of employees of ABC Company consisting the following


memebrs; Empno, Empname, Age, Basic, DA,HRA, Medical allowance (MA), PT, Tax, EPF.
Note: DA-30% of Basic, HRA-10% of Basic, Medical allowance (MA)-1% of Basic PT-500,
Tax-5% of Gross, EPF-1% of Gross Read N employee’s data and compute Gross and Net salary.
The output should be in the following format: ABC Company Vellore
**********************************************************
************************ Employee Number: Employee Name :
**********************************************************
********************** Earnings: Deductions: Basic: PT : DA: Tax: HRA: EPF: MA: Total:
Total: **********************************************************
******************** Gross Salary: Net Salary:
********************************************************** *****************

Code:

#include <stdio.h>

// Define the structure for employees

typedef struct {

int Empno;

char Empname[50];

int Age;

float Basic;

float DA;

float HRA;

float MA;

float PT;

float Tax;

float EPF;

} Employee;
// Function to compute Gross salary

float computeGross(Employee emp) {

return emp.Basic + emp.DA + emp.HRA + emp.MA;

// Function to compute Net salary

float computeNet(Employee emp) {

return computeGross(emp) - emp.PT - emp.Tax - emp.EPF;

int main() {

int N;

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

scanf("%d", &N);

// Array to hold employee data

Employee employees[N];

// Input employee data

for (int i = 0; i < N; i++) {

printf("\nEnter details for employee %d:\n", i+1);

printf("Employee Number: ");

scanf("%d", &employees[i].Empno);

printf("Employee Name : ");

scanf("%s", employees[i].Empname);
printf("Age : ");

scanf("%d", &employees[i].Age);

printf("Basic : ");

scanf("%f", &employees[i].Basic);

// Compute other components based on Basic

employees[i].DA = 0.3 * employees[i].Basic;

employees[i].HRA = 0.1 * employees[i].Basic;

employees[i].MA = 0.01 * employees[i].Basic;

employees[i].PT = 500;

employees[i].Tax = 0.05 * computeGross(employees[i]);

employees[i].EPF = 0.01 * computeGross(employees[i]);

// Output

printf("\nABC Company\n\nVellore\n");

printf("**********************************************************\n");

for (int i = 0; i < N; i++) {

printf("**********************************************************\n");

printf("Employee Number: %d\n", employees[i].Empno);

printf("Employee Name : %s\n", employees[i].Empname);

printf("**********************************************************\n");

printf("Earnings: Deductions:\n");

printf("Basic: %.2f PT : %.2f\n", employees[i].Basic, employees[i].PT);

printf("DA : %.2f Tax : %.2f\n", employees[i].DA, employees[i].Tax);


printf("HRA : %.2f EPF : %.2f\n", employees[i].HRA, employees[i].EPF);

printf("MA : %.2f\n", employees[i].MA);

printf("Total: %.2f Total: %.2f\n", computeGross(employees[i]),


employees[i].PT + employees[i].Tax + employees[i].EPF);

printf("**********************************************************\n");

printf("Gross Salary: %.2f Net Salary: %.2f\n", computeGross(employees[i]),


computeNet(employees[i]));

printf("**********************************************************\n");

return 0;

Q) Design a structure to store time and date. Write a function to find the difference between two
times in minutes.

Code:

#include <stdio.h>

// Structure to store time and date

typedef struct {

int day;

int month;

int year;

int hour;

int minute;
} DateTime;

// Function to convert date and time to total minutes

int timeToMinutes(DateTime dt) {

return dt.minute + dt.hour * 60 + dt.day * 24 * 60 + dt.month * 30 * 24 * 60 + dt.year * 365 *


24 * 60;

// Function to find the difference between two times in minutes

int timeDifference(DateTime start, DateTime end) {

int startMinutes = timeToMinutes(start);

int endMinutes = timeToMinutes(end);

return endMinutes - startMinutes;

int main() {

DateTime start = {23, 4, 2024, 10, 15};

DateTime end = {23, 4, 2024, 12, 30};

int difference = timeDifference(start, end);

printf("The difference between the two times is %d minutes.\n", difference);

return 0;

You might also like