0% found this document useful (0 votes)
11 views71 pages

Data Handling and Control Statements in C

The document provides a series of C programming exercises focused on data handling, control statements, decision making, patterns, and number crunching. Each exercise includes code snippets that demonstrate how to accept user input and perform various operations, such as printing characters, calculating sums, and generating patterns. The document serves as a practical guide for beginners to learn and practice programming concepts in C.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views71 pages

Data Handling and Control Statements in C

The document provides a series of C programming exercises focused on data handling, control statements, decision making, patterns, and number crunching. Each exercise includes code snippets that demonstrate how to accept user input and perform various operations, such as printing characters, calculating sums, and generating patterns. The document serves as a practical guide for beginners to learn and practice programming concepts in C.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

QUESTIONS ON DATA HANDLING

1. Accept a character as input and print it:


#include <stdio.h>
int main() {
char ch;
printf("Enter a character: ");
scanf("%c", &ch);
printf("You entered: %c\n", ch);
return 0;
}

2. Accept a number as input and print it:


#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("You entered: %d\n", num);
return 0;
}

3. Accept a float value as input and print it:


#include <stdio.h>
int main() {
float num;
printf("Enter a float value: ");
scanf("%f", &num);
printf("You entered: %.2f\n", num);
return 0;
}

4. Accept a message as input and print it:

#include <stdio.h>
int main() {
char message[100];
printf("Enter a message: ");
scanf(" %[^\n]", message); // to accept a line with spaces
printf("You entered: %s\n", message);
return 0;
}

5. Accept a message and print it in 3 different lines:


#include <stdio.h>
int main() {
char message[100];
printf("Enter a message: ");
scanf(" %[^\n]", message);
printf("%s\n%s\n%s\n", message, message, message);
return 0;
}

6. Accept 2 numbers and print their sum:


#include <stdio.h>
int main() {
int num1, num2, sum;
printf("Enter two numbers: ");
scanf("%d%d", &num1, &num2);
sum = num1 + num2;
printf("Sum: %d\n", sum);
return 0;
}

7. Accept 2 numbers and print their product:

#include <stdio.h>
int main() {
int num1, num2, product;
printf("Enter two numbers: ");
scanf("%d%d", &num1, &num2);
product = num1 * num2;
printf("Product: %d\n", product);
return 0;
}

8. Accept Celsius temperature, convert to Fahrenheit, and print:


#include <stdio.h>
int main() {
float celsius, fahrenheit;
printf("Enter temperature in Celsius: ");
scanf("%f", &celsius);
fahrenheit = (celsius * 9/5) + 32;
printf("Temperature in Fahrenheit: %.2f\n", fahrenheit);
return 0;
}

9. Accept radius and print the area of the circle:


#include <stdio.h>#define PI 3.14159
int main() {
float radius, area;
printf("Enter the radius of the circle: ");
scanf("%f", &radius);
area = PI * radius * radius;
printf("Area of the circle: %.2f\n", area);
return 0;
}

10. Accept a character and print its ASCII value:


#include <stdio.h>
int main() {
char ch;
printf("Enter a character: ");
scanf("%c", &ch);
printf("ASCII value of '%c' is %d\n", ch, ch);
return 0;
}

QUESTIONS ON CONTROL STATEMENTS - LOOPING


1. Print all characters from 'a' to 'z':
#include <stdio.h>
int main() {
char ch;
for(ch = 'a'; ch <= 'z'; ch++) {
printf("%c ", ch);
}
return 0;
}

2. Print all characters from 'Z' to 'A':


#include <stdio.h>
int main() {
char ch;
for(ch = 'Z'; ch >= 'A'; ch--) {
printf("%c ", ch);
}
return 0;
}

3. Print all characters from 'A' to 'Z' 3 times:


#include <stdio.h>
int main() {
int i;
char ch;
for(i = 1; i <= 3; i++) {
for(ch = 'A'; ch <= 'Z'; ch++) {
printf("%c ", ch);
}
printf("\n");
}
return 0;
}

4. Print the first N natural numbers:


#include <stdio.h>
int main() {
int N, i;
printf("Enter N: ");
scanf("%d", &N);
for(i = 1; i <= N; i++) {
printf("%d ", i);
}
return 0;
}

5. Print first N natural numbers and their sum:


#include <stdio.h>
int main() {
int N, i, sum = 0;
printf("Enter N: ");
scanf("%d", &N);
for(i = 1; i <= N; i++) {
printf("%d ", i);
sum += i;
}
printf("\nSum = %d\n", sum);
return 0;
}

6. Print all odd numbers between 1 and N:


#include <stdio.h>
int main() {
int N, i;
printf("Enter N: ");
scanf("%d", &N);
for(i = 1; i <= N; i++) {
if(i % 2 != 0) {
printf("%d ", i);
}
}
return 0;
}

7. Print all even numbers between 1 and N:


#include <stdio.h>
int main() {
int N, i;
printf("Enter N: ");
scanf("%d", &N);
for(i = 1; i <= N; i++) {
if(i % 2 == 0) {
printf("%d ", i);
}
}
return 0;
}

8. Print squares of the first N natural numbers:


#include <stdio.h>
int main() {
int N, i;
printf("Enter N: ");
scanf("%d", &N);
for(i = 1; i <= N; i++) {
printf("Square of %d = %d\n", i, i * i);
}
return 0;
}

9. Print cubes of the first N natural numbers:


#include <stdio.h>
int main() {
int N, i;
printf("Enter N: ");
scanf("%d", &N);
for(i = 1; i <= N; i++) {
printf("Cube of %d = %d\n", i, i * i * i);
}
return 0;
}

10. Print squares of every 5th number from 1 to N:


#include <stdio.h>
int main() {
int N, i;
printf("Enter N: ");
scanf("%d", &N);
for(i = 5; i <= N; i += 5) {
printf("Square of %d = %d\n", i, i * i);
}
return 0;
}
QUESTIONS ON CONTROL STATEMENTS – DECISION
MAKING

1. Accept two numbers and check if they are equal:


#include <stdio.h>
int main() {
int a, b;
printf("Enter two numbers: ");
scanf("%d%d", &a, &b);
if(a == b)
printf("Numbers are equal.\n");
else
printf("Numbers are not equal.\n");
return 0;
}

2. Accept two characters and check if they are equal:


#include <stdio.h>
int main() {
char ch1, ch2;
printf("Enter two characters: ");
scanf(" %c %c", &ch1, &ch2);
if(ch1 == ch2)
printf("Characters are equal.\n");
else
printf("Characters are not equal.\n");
return 0;
}

3. Accept two numbers and print the greater:


#include <stdio.h>
int main() {
int a, b;
printf("Enter two numbers: ");
scanf("%d%d", &a, &b);
if(a > b)
printf("Greater number: %d\n", a);
else
printf("Greater number: %d\n", b);
return 0;
}

4. Accept two numbers and print the lesser:


#include <stdio.h>
int main() {
int a, b;
printf("Enter two numbers: ");
scanf("%d%d", &a, &b);
if(a < b)
printf("Lesser number: %d\n", a);
else
printf("Lesser number: %d\n", b);
return 0;
}

5. Accept three numbers and print the maximum:


#include <stdio.h>
int main() {
int a, b, c, max;
printf("Enter three numbers: ");
scanf("%d%d%d", &a, &b, &c);
max = a;
if(b > max)
max = b;
if(c > max)
max = c;
printf("Maximum number: %d\n", max);
return 0;
}

6. Accept three numbers and print the minimum:


#include <stdio.h>
int main() {
int a, b, c, min;
printf("Enter three numbers: ");
scanf("%d%d%d", &a, &b, &c);
min = a;
if(b < min)
min = b;
if(c < min)
min = c;
printf("Minimum number: %d\n", min);
return 0;
}

7. Accept a number and print EVEN if even, ODD if


odd:
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if(num % 2 == 0)
printf("EVEN\n");
else
printf("ODD\n");
return 0;
}

8. Accept a number and check divisibility by 3:


#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if(num % 3 == 0)
printf("YES\n");
else
printf("NO\n");
return 0;
}

9. Accept a number and check divisibility by both 3 &


5:
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if(num % 3 == 0 && num % 5 == 0)
printf("YES\n");
else
printf("NO\n");
return 0;
}

10. Accept a number and check if positive, negative or


zero:
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if(num > 0)
printf("Positive\n");
else if(num < 0)
printf("Negative\n");
else
printf("Zero\n");
return 0;
}

QUESTIONS ON PATTERNS

1. Square of stars (N x N):

Write a program to accept a number N as input from the user and


print the following pattern. Sample N = 5.
*****
*****
*****
*****
*****
#include <stdio.h>
int main() {
int i, j, N;
printf("Enter N: ");
scanf("%d", &N);
for(i = 0; i < N; i++) {
for(j = 0; j < N; j++) {
printf("*");
}
printf("\n");
}
return 0;
}

2. Hollow square pattern:

Write a program to accept a number N as input from the user and


print the following pattern. Sample N = 5.
*****
* *
* *
* *
*****
#include <stdio.h>
int main() {
int i, j, N;
printf("Enter N: ");
scanf("%d", &N);
for(i = 0; i < N; i++) {
for(j = 0; j < N; j++) {
if(i == 0 || i == N-1 || j == 0 || j == N-1)
printf("*");
else
printf(" ");
}
printf("\n");
}
return 0;
}

3. Left-aligned increasing triangle of stars:


Write a program to accept a number N as input from the user and
print the following pattern. Sample N = 5.
*
**
***
****
*****
#include <stdio.h>
int main() {
int i, j, N;
printf("Enter N: ");
scanf("%d", &N);
for(i = 1; i <= N; i++) {
for(j = 1; j <= i; j++) {
printf("*");
}
printf("\n");
}
return 0;
}

4. Right-aligned increasing triangle of stars:


Write a program to accept a number N as input from the user and
print the following pattern. Sample N = 5.
*
**
***
****
*****

#include <stdio.h>
int main() {
int i, j, N;
printf("Enter N: ");
scanf("%d", &N);
for(i = 1; i <= N; i++) {
for(j = 1; j <= N - i; j++)
printf(" ");
for(j = 1; j <= i; j++)
printf("*");
printf("\n");
}
return 0;
}

5. Left-aligned triangle with increasing numbers:


Write a program to accept a number N as input from the user and
print the following pattern. Sample N = 5.
1
12
123
1234
12345
#include <stdio.h>
int main() {
int i, j, N;
printf("Enter N: ");
scanf("%d", &N);
for(i = 1; i <= N; i++) {
for(j = 1; j <= i; j++) {
printf("%d", j);
}
printf("\n");
}
return 0;
}

6. Left-aligned triangle with repeated numbers:


Write a program to accept a number N as input from the user and
print the following pattern. Sample N = 5.
1
22
333
4444
55555
#include <stdio.h>
int main() {
int i, j, N;
printf("Enter N: ");
scanf("%d", &N);
for(i = 1; i <= N; i++) {
for(j = 1; j <= i; j++) {
printf("%d", i);
}
printf("\n");
}
return 0;
}
7. Reverse decreasing triangle of numbers:
Write a program to accept a number N as input from the user and
print the following pattern. Sample N = 5.
54321
4321
321
21
1
#include <stdio.h>
int main() {
int i, j, N;
printf("Enter N: ");
scanf("%d", &N);
for(i = N; i >= 1; i--) {
for(j = i; j >= 1; j--) {
printf("%d", j);
}
printf("\n");
}
return 0;
}

8. Triangle with increasing start number each line:


Write a program to accept a number N as input from the user and
print the following pattern. Sample N = 5.
12345
2345
345
45
5

#include <stdio.h>
int main() {
int i, j, N;
printf("Enter N: ");
scanf("%d", &N);
for(i = 0; i < N; i++) {
for(j = 1 + i; j <= N; j++) {
printf("%d", j);
}
printf("\n");
}
return 0;
}
9. Triangle with A to Z (increasing alphabet rows):
Write a program to accept a number N as input from the user and
print the following pattern. Sample N = 5.
A
AB
ABC
ABCD
ABCDE
#include <stdio.h>
int main() {
int i, j, N;
char ch;
printf("Enter N: ");
scanf("%d", &N);
for(i = 0; i < N; i++) {
ch = 'A';
for(j = 0; j <= i; j++) {
printf("%c", ch++);
}
printf("\n");
}
return 0;
}

10. Triangle with continuous increasing letters:


Write a program to accept a number N as input from the user and
print the following pattern. Sample N = 5.
A
BC
DEF
GHIJ
KLMNO
#include <stdio.h>
int main() {
int i, j, N;
char ch = 'A';
printf("Enter N: ");
scanf("%d", &N);
for(i = 1; i <= N; i++) {
for(j = 1; j <= i; j++) {
printf("%c", ch++);
}
printf("\n");
}
return 0;
}

QUESTIONS NUMBER CRUNCHING


1. Accept a number and print the number of digits:
#include <stdio.h>
int main() {
int num, count = 0;
printf("Enter a number: ");
scanf("%d", &num);
if(num == 0) count = 1;
while(num != 0) {
num /= 10;
count++;
}
printf("Number of digits: %d\n", count);
return 0;
}

Input:
Enter a number: 12345
Output:
Number of digits: 5

2. Accept a number and print the sum of its digits:


#include <stdio.h>
int main() {
int num, sum = 0, digit;
printf("Enter a number: ");
scanf("%d", &num);
while(num != 0) {
digit = num % 10;
sum += digit;
num /= 10;
}
printf("Sum of digits: %d\n", sum);
return 0;
}

Input:
Enter a number: 253
Output:
Sum of digits: 10

3. Accept a number, reverse it and print:


#include <stdio.h>
int main() {
int num, reversed = 0, digit;
printf("Enter a number: ");
scanf("%d", &num);
while(num != 0) {
digit = num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}
printf("Reversed number: %d\n", reversed);
return 0;
}

Input:
Enter a number: 1234
Output:
Reversed number: 4321

4. Accept a number and a digit, and find number of


occurrences:
#include <stdio.h>
int main() {
int num, digit, count = 0, rem;
printf("Enter a number: ");
scanf("%d", &num);
printf("Enter digit to find: ");
scanf("%d", &digit);
while(num != 0) {
rem = num % 10;
if(rem == digit)
count++;
num /= 10;
}
printf("Digit %d occurs %d times\n", digit, count);
return 0;
}

Input:
Enter a number: 52525Enter digit to find: 5
Output:
Digit 5 occurs 3 times
5. Accept a number and check if it is an Armstrong
number:
(Armstrong number: sum of cubes of digits = number, eg: 153 → 1³ + 5³ + 3³ = 153)

#include <stdio.h>
int main() {
int num, original, sum = 0, digit;
printf("Enter a number: ");
scanf("%d", &num);
original = num;
while(num != 0) {
digit = num % 10;
sum += digit * digit * digit;
num /= 10;
}
if(sum == original)
printf("Armstrong number\n");
else
printf("Not an Armstrong number\n");
return 0;
}
Input:
Enter a number: 153
Output:
Armstrong number
Input:
Enter a number: 123
Output:
Not an Armstrong number

6. Accept a number and check if it is an Adam


number:
(Adam number: reverse square of reverse = square of original, eg: 12 → 21 → 21² =
441 → reverse 441 = 144 → 12² = 144)
#include <stdio.h>
int reverse(int n) {
int rev = 0;
while(n != 0) {
rev = rev * 10 + n % 10;
n /= 10;
}
return rev;
}
int main() {
int num, rev_num, sqr, rev_sqr;
printf("Enter a number: ");
scanf("%d", &num);
rev_num = reverse(num);
sqr = num * num;
rev_sqr = reverse(rev_num * rev_num);
if(sqr == rev_sqr)
printf("Adam number\n");
else
printf("Not an Adam number\n");
return 0;
}

Input:
Enter a number: 12
Output:
Adam number
Input:
Enter a number: 15
Output:
Not an Adam number

7. Accept a number and check if it is a prime number:


#include <stdio.h>
int main() {
int num, i, flag = 1;
printf("Enter a number: ");
scanf("%d", &num);
if(num <= 1)
flag = 0;
else {
for(i = 2; i <= num/2; i++) {
if(num % i == 0) {
flag = 0;
break;
}
}
}
if(flag)
printf("Prime number\n");
else
printf("Not a prime number\n");
return 0;
}
Input:
Enter a number: 17
Output:
Prime number
Input:
Enter a number: 20
Output:
Not a prime number

8. Accept 2 numbers and check if they are amicable:


(Amicable numbers: sum of divisors of one number = other number and vice versa)
#include <stdio.h>
int main() {
int num1, num2, sum1 = 0, sum2 = 0, i;
printf("Enter two numbers: ");
scanf("%d%d", &num1, &num2);
for(i = 1; i < num1; i++) {
if(num1 % i == 0)
sum1 += i;
}
for(i = 1; i < num2; i++) {
if(num2 % i == 0)
sum2 += i;
}
if(sum1 == num2 && sum2 == num1)
printf("Amicable numbers\n");
else
printf("Not amicable numbers\n");
return 0;
}

Input:
Enter two numbers: 220 284
Output:
Amicable numbers
Input:
Enter two numbers: 30 50

Output:
Not amicable numbers
9. Accept a number and check if it is a power of 2:
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if(num > 0 && (num & (num - 1)) == 0)
printf("Power of 2\n");
else
printf("Not a power of 2\n");
return 0;
}

Input:
Enter a number: 16
Output:
Power of 2
Input:
Enter a number: 20

Output:
Not a power of 2

10. Accept 2 numbers and find their LCM:


(LCM = (num1 * num2) / GCD)
#include <stdio.h>
int main() {
int num1, num2, a, b, gcd, lcm;
printf("Enter two numbers: ");
scanf("%d%d", &num1, &num2);
a = num1;
b = num2;
while(b != 0) {
int temp = b;
b = a % b;
a = temp;
}
gcd = a;
lcm = (num1 * num2) / gcd;
printf("LCM = %d\n", lcm);
return 0;
}

Input:
Enter two numbers: 12 15
Output:
LCM = 60
Input:
Enter two numbers: 7 5
Output:
LCM = 35

1. Product of digits
#include <stdio.h>
int main() {
int num, digit, product = 1;
printf("Enter a number: ");
scanf("%d", &num);
int temp = num;
while (temp != 0) {
digit = temp % 10;
product *= digit;
temp /= 10;
}
printf("Product of digits of %d = %d\n", num, product);
return 0;
}
Input: 123
Output: Product of digits of 123 = 6

2. Check if number is palindrome


#include <stdio.h>
int main() {
int num, rev = 0, digit, original;
printf("Enter a number: ");
scanf("%d", &num);
original = num;
while (num != 0) {
digit = num % 10;
rev = rev * 10 + digit;
num /= 10;
}
if (original == rev)
printf("Palindrome number\n");
else
printf("Not a palindrome\n");
return 0;
}
Input: 121
Output: Palindrome number

3. Frequency of each digit


#include <stdio.h>
int main() {
int num, freq[10] = {0};
printf("Enter a number: ");
scanf("%d", &num);
while (num != 0) {
freq[num % 10]++;
num /= 10;
}
for (int i = 0; i < 10; i++) {
if (freq[i] > 0)
printf("Digit %d occurs %d times\n", i, freq[i]);
}
return 0;
}
Input: 221433
Output:
Digit 1 occurs 1 times
Digit 2 occurs 2 times
Digit 3 occurs 2 times
Digit 4 occurs 1 times

4. Print factors of a number


#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("Factors of %d: ", num);
for (int i = 1; i <= num; i++) {
if (num % i == 0)
printf("%d ", i);
}
printf("\n");
return 0;
}
Input: 12
Output: Factors of 12: 1 2 3 4 6 12

5. Print prime factors


#include <stdio.h>
int main() {
int num, i = 2;
printf("Enter a number: ");
scanf("%d", &num);
printf("Prime factors of %d: ", num);
while (num > 1) {
if (num % i == 0) {
printf("%d ", i);
num /= i;
} else {
i++;
}
}
printf("\n");
return 0;
}
Input: 30
Output: Prime factors of 30: 2 3 5

6. Check if perfect square


#include <stdio.h>#include <math.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
int root = sqrt(num);
if (root * root == num)
printf("Perfect square\n");
else
printf("Not a perfect square\n");
return 0;
}
Input: 49
Output: Perfect square

7. Check if betrothed numbers


(Betrothed: sum of proper divisors of A = B + 1 and vice versa)
#include <stdio.h>
int sum_of_divisors(int n) {
int sum = 0;
for (int i = 1; i <= n/2; i++) {
if (n % i == 0)
sum += i;
}
return sum;
}
int main() {
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
if (sum_of_divisors(a) == b + 1 && sum_of_divisors(b) == a + 1)
printf("Betrothed numbers\n");
else
printf("Not betrothed numbers\n");
return 0;
}
Input: 48 75
Output: Betrothed numbers

8. Find HCF of two numbers


#include <stdio.h>
int main() {
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
int min = (a < b) ? a : b;
int hcf = 1;
for (int i = 1; i <= min; i++) {
if (a % i == 0 && b % i == 0)
hcf = i;
}
printf("HCF = %d\n", hcf);
return 0;
}
Input: 20 30
Output: HCF = 10

9. Check if strong number


(A number is strong if sum of factorials of digits equals the number, e.g. 145 = 1! + 4!
+ 5!)
#include <stdio.h>
int factorial(int n) {
int fact = 1;
for (int i = 1; i <= n; i++)
fact *= i;
return fact;
}
int main() {
int num, sum = 0, digit, temp;
printf("Enter a number: ");
scanf("%d", &num);
temp = num;
while (temp != 0) {
digit = temp % 10;
sum += factorial(digit);
temp /= 10;
}
if (sum == num)
printf("Strong number\n");
else
printf("Not a strong number\n");
return 0;
}
Input: 145
Output: Strong number

10. Generate primes between two intervals


#include <stdio.h>
int is_prime(int n) {
if (n <= 1) return 0;
for (int i = 2; i <= n/2; i++)
if (n % i == 0) return 0;
return 1;
}
int main() {
int start, end;
printf("Enter interval: ");
scanf("%d %d", &start, &end);
printf("Prime numbers between %d and %d:\n", start, end);
for (int i = start; i <= end; i++) {
if (is_prime(i))
printf("%d ", i);
}
printf("\n");
return 0;
}
Input: 10 20
Output: Prime numbers between 10 and 20: 11 13 17 19
QUESTIONS ON ARRAYS

1. Print array from left to right


#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5}, n = 5;
printf("Array from left to right: ");
for(int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
Output: Array from left to right: 1 2 3 4 5

2. Print array from right to left


#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5}, n = 5;
printf("Array from right to left: ");
for(int i = n - 1; i >= 0; i--)
printf("%d ", arr[i]);
return 0;
}
Output: Array from right to left: 5 4 3 2 1

3. Sum of array elements


#include <stdio.h>
int main() {
int arr[] = {4, 2, 6, 1, 7}, sum = 0, n = 5;
for(int i = 0; i < n; i++)
sum += arr[i];
printf("Sum of array: %d\n", sum);
return 0;
}
Output: Sum of array: 20

4. Find maximum element


#include <stdio.h>
int main() {
int arr[] = {3, 8, 2, 7, 4}, max = arr[0], n = 5;
for(int i = 1; i < n; i++)
if(arr[i] > max) max = arr[i];
printf("Maximum element: %d\n", max);
return 0;
}
Output: Maximum element: 8

5. Find minimum element


#include <stdio.h>
int main() {
int arr[] = {3, 8, 2, 7, 4}, min = arr[0], n = 5;
for(int i = 1; i < n; i++)
if(arr[i] < min) min = arr[i];
printf("Minimum element: %d\n", min);
return 0;
}
Output: Minimum element: 2

6. Find average of array elements


#include <stdio.h>
int main() {
int arr[] = {4, 5, 6, 7, 8}, sum = 0, n = 5;
for(int i = 0; i < n; i++)
sum += arr[i];
printf("Average: %.2f\n", (float)sum / n);
return 0;
}
Output: Average: 6.00

7. Count number of 0s and 1s


#include <stdio.h>
int main() {
int arr[] = {1, 0, 1, 1, 0, 0, 1}, n = 7, zero = 0, one = 0;
for(int i = 0; i < n; i++) {
if(arr[i] == 0) zero++;
else if(arr[i] == 1) one++;
}
printf("Zeros: %d, Ones: %d\n", zero, one);
return 0;
}
Output: Zeros: 3, Ones: 4

8. Count elements less than a key element


#include <stdio.h>
int main() {
int arr[] = {5, 1, 8, 2, 7}, key = 6, count = 0, n = 5;
for(int i = 0; i < n; i++)
if(arr[i] < key) count++;
printf("Elements less than %d: %d\n", key, count);
return 0;
}
Output: Elements less than 6: 3

9. Print elements less than a key


#include <stdio.h>
int main() {
int arr[] = {9, 3, 6, 1, 8}, key = 7, n = 5;
printf("Elements less than %d: ", key);
for(int i = 0; i < n; i++)
if(arr[i] < key) printf("%d ", arr[i]);
return 0;
}
Output: Elements less than 7: 3 6 1

10. Find repeated elements in a sorted array


#include <stdio.h>
int main() {
int arr[] = {1, 2, 2, 3, 4, 4, 5}, n = 7;
printf("Repeated elements: ");
for(int i = 1; i < n; i++) {
if(arr[i] == arr[i-1])
printf("%d ", arr[i]);
}
return 0;
}
Output: Repeated elements: 2 4

1. Sum of maximum and minimum numbers in an


unsorted array
#include <stdio.h>
int main() {
int arr[] = {5, 1, 9, 2, 7}, n = 5, min = arr[0], max = arr[0];
for(int i = 1; i < n; i++) {
if(arr[i] < min) min = arr[i];
if(arr[i] > max) max = arr[i];
}
printf("Sum of max and min = %d + %d = %d\n", max, min, max
+ min);
return 0;
}
Output: Sum of max and min = 9 + 1 = 10

2. Replace every element with the sum of every other


element
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4}, n = 4, sum = 0;
for(int i = 0; i < n; i++) sum += arr[i];
for(int i = 0; i < n; i++) arr[i] = sum - arr[i];
printf("Updated array: ");
for(int i = 0; i < n; i++) printf("%d ", arr[i]);
return 0;
}
Output: Updated array: 9 8 7 6

3. Replace every element with the sum of its right side


elements
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4}, n = 4;
for(int i = 0; i < n; i++) {
int sum = 0;
for(int j = i+1; j < n; j++)
sum += arr[j];
arr[i] = sum;
}
printf("Right side sum array: ");
for(int i = 0; i < n; i++) printf("%d ", arr[i]);
return 0;
}
Output: Right side sum array: 9 7 4 0

4. Replace every element with the sum of its left side


elements
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4}, n = 4;
for(int i = n-1; i >= 0; i--) {
int sum = 0;
for(int j = 0; j < i; j++)
sum += arr[j];
arr[i] = sum;
}
printf("Left side sum array: ");
for(int i = 0; i < n; i++) printf("%d ", arr[i]);
return 0;
}
Output: Left side sum array: 0 1 3 6

5. Reverse array (in-place)


#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5}, n = 5;
for(int i = 0; i < n/2; i++) {
int temp = arr[i];
arr[i] = arr[n-1-i];
arr[n-1-i] = temp;
}
printf("Reversed array: ");
for(int i = 0; i < n; i++) printf("%d ", arr[i]);
return 0;
}
Output: Reversed array: 5 4 3 2 1

6. Reverse the first half of the array


#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50, 60}, n = 6, mid = n/2;
for(int i = 0; i < mid/2; i++) {
int temp = arr[i];
arr[i] = arr[mid - 1 - i];
arr[mid - 1 - i] = temp;
}
printf("First half reversed: ");
for(int i = 0; i < n; i++) printf("%d ", arr[i]);
return 0;
}
Output: First half reversed: 30 20 10 40 50 60

7. Reverse the second half of the array


#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50, 60}, n = 6, mid = n/2;
for(int i = 0; i < (n-mid)/2; i++) {
int temp = arr[mid + i];
arr[mid + i] = arr[n - 1 - i];
arr[n - 1 - i] = temp;
}
printf("Second half reversed: ");
for(int i = 0; i < n; i++) printf("%d ", arr[i]);
return 0;
}
Output: Second half reversed: 10 20 30 60 50 40

8. Find second largest element


#include <stdio.h>
int main() {
int arr[] = {8, 5, 9, 1, 6}, n = 5;
int max = arr[0], second = -1;
for(int i = 1; i < n; i++)
if(arr[i] > max) {
second = max;
max = arr[i];
} else if(arr[i] > second && arr[i] != max)
second = arr[i];
printf("Second largest: %d\n", second);
return 0;
}
Output: Second largest: 8

9. Find second smallest element


#include <stdio.h>
int main() {
int arr[] = {8, 5, 9, 1, 6}, n = 5;
int min = arr[0], second = 1e9;
for(int i = 1; i < n; i++)
if(arr[i] < min) {
second = min;
min = arr[i];
} else if(arr[i] < second && arr[i] != min)
second = arr[i];
printf("Second smallest: %d\n", second);
return 0;
}
Output: Second smallest: 5

10. Count number of odd and even numbers


#include <stdio.h>
int main() {
int arr[] = {1, 4, 7, 8, 3, 6}, n = 6, even = 0, odd = 0;
for(int i = 0; i < n; i++) {
if(arr[i] % 2 == 0) even++;
else odd++;
}
printf("Even: %d, Odd: %d\n", even, odd);
return 0;
}
Output: Even: 3, Odd: 3
QUESTIONS ON STRINGS

1. Accept a string and print it


#include <stdio.h>
int main() {
char str[100];
printf("Enter a string: ");
gets(str);
printf("You entered: %s\n", str);
return 0;
}
Input: Hello World
Output: You entered: Hello World

2. Count number of vowels


#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int count = 0;
printf("Enter a string: ");
gets(str);
for(int i = 0; str[i]; i++) {
char ch = tolower(str[i]);
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
count++;
}
printf("Number of vowels: %d\n", count);
return 0;
}
Input: Education
Output: Number of vowels: 5

3. Count number of consonants


#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int count = 0;
printf("Enter a string: ");
gets(str);
for(int i = 0; str[i]; i++) {
char ch = tolower(str[i]);
if((ch >= 'a' && ch <= 'z') && !(ch == 'a'||ch=='e'||ch=='i'||
ch=='o'||ch=='u'))
count++;
}
printf("Number of consonants: %d\n", count);
return 0;
}
Input: Education
Output: Number of consonants: 4
4. Print the length of a string
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
printf("Enter a string: ");
gets(str);
printf("Length of string: %lu\n", strlen(str));
return 0;
}
Input: Computer
Output: Length of string: 8

5. Print reversed string


#include <stdio.h>
#include <string.h>
int main() {
char str[100];
printf("Enter a string: ");
gets(str);
int len = strlen(str);
printf("Reversed string: ");
for(int i = len-1; i >= 0; i--)
putchar(str[i]);
printf("\n");
return 0;
}
Input: Hello
Output: Reversed string: olleH

6. Check if two strings are the same


#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100];
printf("Enter first string: ");
gets(str1);
printf("Enter second string: ");
gets(str2);
if(strcmp(str1, str2) == 0)
printf("Strings are the same.\n");
else
printf("Strings are different.\n");
return 0;
}
Input: Apple, Apple
Output: Strings are the same.

7. Copy one string to another


#include <stdio.h>
#include <string.h>
int main() {
char original[100], copy[100];
printf("Enter a string: ");
gets(original);
strcpy(copy, original);
printf("Copied string: %s\n", copy);
return 0;
}
Input: Sunshine
Output: Copied string: Sunshine

8. Concatenate two strings


#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100], result[200];
printf("Enter first string: ");
gets(str1);
printf("Enter second string: ");
gets(str2);
strcpy(result, str1);
strcat(result, str2);
printf("Concatenated string: %s\n", result);
return 0;
}
Input: Good, Morning
Output: Concatenated string: GoodMorning

9. Check if a string is a palindrome


#include <stdio.h>
#include <string.h>
int main() {
char str[100];
printf("Enter a string: ");
gets(str);
int len = strlen(str), isPalindrome = 1;
for(int i = 0; i < len / 2; i++) {
if(str[i] != str[len - 1 - i]) {
isPalindrome = 0;
break;
}
}
if(isPalindrome)
printf("The string is a palindrome.\n");
else
printf("The string is not a palindrome.\n");
return 0;
}
Input: madam
Output: The string is a palindrome.

10. Check if second string is a substring of the first


#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100];
printf("Enter main string: ");
gets(str1);
printf("Enter substring to search: ");
gets(str2);
if(strstr(str1, str2) != NULL)
printf("Substring found.\n");
else
printf("Substring not found.\n");
return 0;
}
Input:
Main string: HelloWorld
Substring: World
Output: Substring found.
1. Implement the string length function
#include <stdio.h>
int stringLength(char str[]) {
int i = 0;
while(str[i] != '\0') i++;
return i;
}int main() {
char str[100];
printf("Enter a string: ");
gets(str);
printf("Length: %d\n", stringLength(str));
return 0;
}
Input: hello
Output: Length: 5

2. Implement the string copy function


#include <stdio.h>
void stringCopy(char dest[], char src[]) {
int i = 0;
while((dest[i] = src[i]) != '\0') i++;
}
int main() {
char src[100], dest[100];
printf("Enter a string: ");
gets(src);
stringCopy(dest, src);
printf("Copied string: %s\n", dest);
return 0;
}
Input: OpenAI
Output: Copied string: OpenAI

3. Implement the string concatenate function


#include <stdio.h>
void stringConcat(char result[], char str1[], char str2[]) {
int i = 0, j = 0;
while(str1[i] != '\0') {
result[i] = str1[i];
i++;
}
while(str2[j] != '\0') {
result[i++] = str2[j++];
}
result[i] = '\0';
}
int main() {
char str1[100], str2[100], result[200];
printf("Enter first string: ");
gets(str1);
printf("Enter second string: ");
gets(str2);
stringConcat(result, str1, str2);
printf("Concatenated string: %s\n", result);
return 0;
}
Input: Good, Luck
Output: Concatenated string: GoodLuck
4. Implement the string compare function
#include <stdio.h>
int stringCompare(char str1[], char str2[]) {
int i = 0;
while(str1[i] && str2[i]) {
if(str1[i] != str2[i]) return str1[i] - str2[i];
i++;
}
return str1[i] - str2[i];
}int main() {
char str1[100], str2[100];
printf("Enter two strings:\n");
gets(str1);
gets(str2);
int res = stringCompare(str1, str2);
if(res == 0)
printf("Strings are equal.\n");
else if(res > 0)
printf("First string is greater.\n");
else
printf("Second string is greater.\n");
return 0;
}
Input: abc, abc
Output: Strings are equal.

5. Implement the vowel count function


#include <stdio.h>
#include <ctype.h>
int countVowels(char str[]) {
int count = 0;
for(int i = 0; str[i]; i++) {
char ch = tolower(str[i]);
if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u') count++;
}
return count;
}int main() {
char str[100];
printf("Enter a string: ");
gets(str);
printf("Vowels: %d\n", countVowels(str));
return 0;
}
Input: Education
Output: Vowels: 5
6. Implement the consonant count function
#include <stdio.h>
#include <ctype.h>
int countConsonants(char str[]) {
int count = 0;
for(int i = 0; str[i]; i++) {
char ch = tolower(str[i]);
if(ch >= 'a' && ch <= 'z' && !(ch=='a'||ch=='e'||ch=='i'||
ch=='o'||ch=='u'))
count++;
}
return count;
}int main() {
char str[100];
printf("Enter a string: ");
gets(str);
printf("Consonants: %d\n", countConsonants(str));
return 0;
}
Input: Education
Output: Consonants: 4

7. Implement the count words function


#include <stdio.h>
#include <ctype.h>
int countWords(char str[]) {
int count = 0, inWord = 0;
for(int i = 0; str[i]; i++) {
if(!isspace(str[i]) && inWord == 0) {
inWord = 1;
count++;
} else if(isspace(str[i])) {
inWord = 0;
}
}
return count;
}int main() {
char str[100];
printf("Enter a sentence: ");
gets(str);
printf("Word count: %d\n", countWords(str));
return 0;
}
Input: Hello world from C
Output: Word count: 4
8. Implement string reverse function
#include <stdio.h>
void strReverse(char str[]) {
int len = 0;
while(str[len] != '\0') len++;
for(int i = 0; i < len/2; i++) {
char temp = str[i];
str[i] = str[len-1-i];
str[len-1-i] = temp;
}
}int main() {
char str[100];
printf("Enter a string: ");
gets(str);
strReverse(str);
printf("Reversed: %s\n", str);
return 0;
}
Input: CProgram
Output: Reversed: margorPC

9. Implement strstr function (search substring)


#include <stdio.h>
int myStrstr(char text[], char pat[]) {
for(int i = 0; text[i]; i++) {
int j = 0;
while(pat[j] && text[i+j] == pat[j]) j++;
if(pat[j] == '\0') return i; // Match found
}
return -1; // Not found
}int main() {
char text[100], pattern[100];
printf("Enter text: ");
gets(text);
printf("Enter pattern: ");
gets(pattern);
int pos = myStrstr(text, pattern);
if(pos != -1)
printf("Pattern found at index %d\n", pos);
else
printf("Pattern not found.\n");
return 0;
}
Input:
Text: This is OpenAI GPT
Pattern: OpenAI
Output: Pattern found at index 8
10. Check if string is palindrome using custom
functions
#include <stdio.h>
#include <string.h>
void stringCopy(char dest[], char src[]) {
int i = 0;
while((dest[i] = src[i]) != '\0') i++;
}
void strReverse(char str[]) {
int len = 0;
while(str[len] != '\0') len++;
for(int i = 0; i < len/2; i++) {
char temp = str[i];
str[i] = str[len-1-i];
str[len-1-i] = temp;
}
}
int stringCompare(char str1[], char str2[]) {
int i = 0;
while(str1[i] && str2[i]) {
if(str1[i] != str2[i]) return 0;
i++;
}
return str1[i] == str2[i];
}
int main() {
char str[100], reversed[100];
printf("Enter a string: ");
gets(str);
stringCopy(reversed, str);
strReverse(reversed);
if(stringCompare(str, reversed))
printf("The string is a palindrome.\n");
else
printf("The string is not a palindrome.\n");
return 0;
}
Input: madam
Output: The string is a palindrome.

1. Swap Two Given Strings


#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100], temp[100];
printf("Enter first string: ");
scanf("%s", str1);
printf("Enter second string: ");
scanf("%s", str2);

strcpy(temp, str1);
strcpy(str1, str2);
strcpy(str2, temp);

printf("After swapping:\nString 1: %s\nString 2: %s\n", str1,


str2);
return 0;
}
Input:
abc
xyz
Output:
String 1: xyz
String 2: abc

2. Swap Two Words in a Sentence


#include <stdio.h>
#include <string.h>
int main() {
char str[100], word1[20], word2[20];
printf("Enter a sentence: ");
fgets(str, sizeof(str), stdin);
printf("Enter first word to swap: ");
scanf("%s", word1);
printf("Enter second word to swap: ");
scanf("%s", word2);

char *pos1 = strstr(str, word1);


char *pos2 = strstr(str, word2);

if (pos1 && pos2) {


char temp[100];
strcpy(temp, word1);
strncpy(pos1, word2, strlen(word2));
strncpy(pos2, temp, strlen(temp));
}

printf("After swapping: %s", str);


return 0;
}
Input:
I love apples
love
apples
Output:
I apples love

3. Maximum Occurring Character


#include <stdio.h>
#include <string.h>
int main() {
char str[100];
int count[256] = {0}, max = 0;
char result;

printf("Enter a string: ");


scanf("%s", str);

for (int i = 0; str[i]; i++)


count[(unsigned char)str[i]]++;

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


if (count[i] > max) {
max = count[i];
result = i;
}
}

printf("Maximum occurring character: %c\n", result);


return 0;
}
Input: banana
Output: a

4. Character Count in String


#include <stdio.h>
#include <string.h>
int main() {
char str[100];
int count[256] = {0};

printf("Enter a string: ");


scanf("%s", str);

for (int i = 0; str[i]; i++)


count[(unsigned char)str[i]]++;

for (int i = 0; i < 256; i++)


if (count[i] > 0)
printf("%c: %d\n", i, count[i]);

return 0;
}
Input: aabbc
Output:
a: 2
b: 2
c: 1

5. Print Duplicate Characters


#include <stdio.h>
#include <string.h>
int main() {
char str[100];
int count[256] = {0};

printf("Enter a string: ");


scanf("%s", str);

for (int i = 0; str[i]; i++)


count[(unsigned char)str[i]]++;

printf("Duplicate characters: ");


for (int i = 0; i < 256; i++)
if (count[i] > 1)
printf("%c ", i);

return 0;
}
Input: programming
Output: r g m

6. Remove Duplicate Characters


#include <stdio.h>
#include <string.h>
int main() {
char str[100], result[100] = "";
int seen[256] = {0}, j = 0;

printf("Enter a string: ");


scanf("%s", str);

for (int i = 0; str[i]; i++) {


if (!seen[(unsigned char)str[i]]) {
result[j++] = str[i];
seen[(unsigned char)str[i]] = 1;
}
}
result[j] = '\0';

printf("After removing duplicates: %s\n", result);


return 0;
}
Input: programming
Output: progamin

7. Remove Vowels
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int isVowel(char ch) {
ch = tolower(ch);
return (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u');
}
int main() {
char str[100], result[100];
int j = 0;

printf("Enter a string: ");


scanf("%s", str);

for (int i = 0; str[i]; i++) {


if (!isVowel(str[i]))
result[j++] = str[i];
}
result[j] = '\0';

printf("String without vowels: %s\n", result);


return 0;
}
Input: beautiful
Output: btfl

8. Rotate String N Times


#include <stdio.h>
#include <string.h>
void rotate(char str[], int n) {
int len = strlen(str);
n %= len;
char temp[100];
strcpy(temp, str + len - n);
str[len - n] = '\0';
strcat(temp, str);
strcpy(str, temp);
}
int main() {
char str[100];
int n;

printf("Enter string: ");


scanf("%s", str);
printf("Enter number of rotations: ");
scanf("%d", &n);

rotate(str, n);
printf("Rotated string: %s\n", str);
return 0;
}
Input: abcdef and 2
Output: efabcd

9. Check if Strings Are Rotations


#include <stdio.h>
#include <string.h>
int areRotations(char *s1, char *s2) {
if (strlen(s1) != strlen(s2)) return 0;

char temp[200];
strcpy(temp, s1);
strcat(temp, s1);

return strstr(temp, s2) != NULL;


}
int main() {
char s1[100], s2[100];

printf("Enter first string: ");


scanf("%s", s1);
printf("Enter second string: ");
scanf("%s", s2);

if (areRotations(s1, s2))
printf("Strings are rotations of each other.\n");
else
printf("Strings are not rotations.\n");

return 0;
}
Input: abcd and cdab
Output: Strings are rotations of each other.
10. Remove Characters from First String Found in
Second
#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100], result[100];
int remove[256] = {0}, j = 0;

printf("Enter first string: ");


scanf("%s", str1);
printf("Enter second string: ");
scanf("%s", str2);

for (int i = 0; str2[i]; i++)


remove[(unsigned char)str2[i]] = 1;

for (int i = 0; str1[i]; i++) {


if (!remove[(unsigned char)str1[i]])
result[j++] = str1[i];
}
result[j] = '\0';

printf("Resultant string: %s\n", result);


return 0;
}
Input: computer and cut
Output: ompier
QUESTIONS ON 2D ARRAYS

1. Print Contents of a 2D Array Row-Wise


#include <stdio.h>
int main() {
int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
printf("Row-wise:\n");
for (int i = 0; i < 2; i++)
for (int j = 0; j < 3; j++)
printf("%d ", a[i][j]);
return 0;
}
Output: 1 2 3 4 5 6

2. Print Contents Column-Wise


#include <stdio.h>
int main() {
int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
printf("Column-wise:\n");
for (int j = 0; j < 3; j++)
for (int i = 0; i < 2; i++)
printf("%d ", a[i][j]);
return 0;
}
Output: 1 4 2 5 3 6

3. Zig-Zag Order (Alternating Rows)


#include <stdio.h>
int main() {
int a[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
printf("Zig-Zag Order:\n");
for (int i = 0; i < 3; i++) {
if (i % 2 == 0)
for (int j = 0; j < 3; j++) printf("%d ", a[i][j]);
else
for (int j = 2; j >= 0; j--) printf("%d ", a[i][j]);
}
return 0;
}
Output: 1 2 3 6 5 4 7 8 9

4. Diagonal-wise (All Diagonals from Top-left to


Bottom-right)

#include <stdio.h>
int main() {
int a[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
printf("Diagonal-wise:\n");
for (int k = 0; k <= 2*2; k++) {
for (int i = 0; i < 3; i++) {
int j = k - i;
if (j >= 0 && j < 3)
printf("%d ", a[i][j]);
}
}
return 0;
}
Output: 1 2 4 3 5 7 6 8 9

5. Right-Diagonal (Main Diagonal: Top-left to Bottom-


right)
#include <stdio.h>
int main() {
int a[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
printf("Right Diagonal:\n");
for (int i = 0; i < 3; i++)
printf("%d ", a[i][i]);
return 0;
}
Output: 1 5 9

6. Left-Diagonal (Secondary Diagonal: Top-right to


Bottom-left)
#include <stdio.h>
int main() {
int a[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
printf("Left Diagonal:\n");
for (int i = 0; i < 3; i++)
printf("%d ", a[i][2 - i]);
return 0;
}
Output: 3 5 7

7. Upper Triangular (Including Diagonal)


#include <stdio.h>
int main() {
int a[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
printf("Upper Triangular:\n");
for (int i = 0; i < 3; i++)
for (int j = i; j < 3; j++)
printf("%d ", a[i][j]);
return 0;
}
Output: 1 2 3 5 6 9

8. Lower Triangular (Including Diagonal)


#include <stdio.h>
int main() {
int a[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
printf("Lower Triangular:\n");
for (int i = 0; i < 3; i++)
for (int j = 0; j <= i; j++)
printf("%d ", a[i][j]);
return 0;
}
Output: 1 4 5 7 8 9

9. Maximum Element and Position


#include <stdio.h>
int main() {
int a[3][3] = {{1, 29, 3}, {4, 5, 6}, {7, 8, 9}};
int max = a[0][0], r = 0, c = 0;

for (int i = 0; i < 3; i++)


for (int j = 0; j < 3; j++)
if (a[i][j] > max) {
max = a[i][j];
r = i;
c = j;
}

printf("Max Element: %d at (%d, %d)\n", max, r, c);


return 0;
}
Output: Max Element: 29 at (0, 1)

10. Minimum Element and Position


#include <stdio.h>
int main() {
int a[3][3] = {{4, 2, 3}, {1, 5, 6}, {7, 8, 9}};
int min = a[0][0], r = 0, c = 0;

for (int i = 0; i < 3; i++)


for (int j = 0; j < 3; j++)
if (a[i][j] < min) {
min = a[i][j];
r = i;
c = j;
}

printf("Min Element: %d at (%d, %d)\n", min, r, c);


return 0;
}
Output: Min Element: 1 at (1, 0)

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

#define SIZE 10

void inputMatrix(int mat[SIZE][SIZE], int r, int c) {


printf("Enter %dx%d matrix elements:\n", r, c);
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++)
scanf("%d", &mat[i][j]);
}
void maxEachRow(int mat[SIZE][SIZE], int r, int c) {
for (int i = 0; i < r; i++) {
int max = mat[i][0];
for (int j = 1; j < c; j++)
if (mat[i][j] > max) max = mat[i][j];
printf("Row %d Max: %d\n", i+1, max);
}
}

void minEachRow(int mat[SIZE][SIZE], int r, int c) {


for (int i = 0; i < r; i++) {
int min = mat[i][0];
for (int j = 1; j < c; j++)
if (mat[i][j] < min) min = mat[i][j];
printf("Row %d Min: %d\n", i+1, min);
}
}

void maxEachCol(int mat[SIZE][SIZE], int r, int c) {


for (int j = 0; j < c; j++) {
int max = mat[0][j];
for (int i = 1; i < r; i++)
if (mat[i][j] > max) max = mat[i][j];
printf("Col %d Max: %d\n", j+1, max);
}
}

void minEachCol(int mat[SIZE][SIZE], int r, int c) {


for (int j = 0; j < c; j++) {
int min = mat[0][j];
for (int i = 1; i < r; i++)
if (mat[i][j] < min) min = mat[i][j];
printf("Col %d Min: %d\n", j+1, min);
}
}

void triangleProduct(int mat[SIZE][SIZE], int n) {


int minUpper = __INT_MAX__, maxLower = -__INT_MAX__;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
if (i < j && mat[i][j] < minUpper)
minUpper = mat[i][j];
if (i > j && mat[i][j] > maxLower)
maxLower = mat[i][j];
}
printf("Product of min(upper) and max(lower): %d\n",
minUpper * maxLower);
}
void rowColSum(int mat[SIZE][SIZE], int r, int c) {
int minRowSum = __INT_MAX__, maxColSum = 0;

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


int sum = 0;
for (int j = 0; j < c; j++)
sum += mat[i][j];
if (sum < minRowSum) minRowSum = sum;
}

for (int j = 0; j < c; j++) {


int sum = 0;
for (int i = 0; i < r; i++)
sum += mat[i][j];
if (sum > maxColSum) maxColSum = sum;
}

printf("Min Row Sum: %d\nMax Column Sum: %d\n",


minRowSum, maxColSum);
}

void rowWithMaxOnes(int mat[SIZE][SIZE], int r, int c) {


int maxOnes = 0, rowIndex = -1;
for (int i = 0; i < r; i++) {
int count = 0;
for (int j = 0; j < c; j++)
if (mat[i][j] == 1) count++;
if (count > maxOnes) {
maxOnes = count;
rowIndex = i;
}
}
printf("Row with max 1s: %d\n", rowIndex);
}

void diagonalQuotRem(int mat[SIZE][SIZE], int n) {


int mainDiag = 0, secDiag = 0;
for (int i = 0; i < n; i++) {
mainDiag += mat[i][i];
secDiag += mat[i][n - i - 1];
}
printf("Quotient: %d\nRemainder: %d\n", mainDiag /
secDiag, mainDiag % secDiag);
}

void diagonalAbsDiff(int mat[SIZE][SIZE], int n) {


int mainDiag = 0, secDiag = 0;
for (int i = 0; i < n; i++) {
mainDiag += mat[i][i];
secDiag += mat[i][n - i - 1];
}
printf("Absolute Diagonal Difference: %d\n", abs(mainDiag
- secDiag));
}

void searchInSortedMatrix(int mat[SIZE][SIZE], int r, int c,


int key) {
int i = 0, j = c - 1;
while (i < r && j >= 0) {
if (mat[i][j] == key) {
printf("Element %d found at (%d, %d)\n", key, i, j);
return;
}
if (mat[i][j] > key) j--;
else i++;
}
printf("Element %d not found.\n", key);
}

int main() {
int mat[SIZE][SIZE], r, c, key;

printf("Enter rows and columns of matrix: ");


scanf("%d %d", &r, &c);

inputMatrix(mat, r, c);

maxEachRow(mat, r, c);
minEachRow(mat, r, c);
maxEachCol(mat, r, c);
minEachCol(mat, r, c);
if (r == c) triangleProduct(mat, r);
rowColSum(mat, r, c);
rowWithMaxOnes(mat, r, c);
if (r == c) diagonalQuotRem(mat, r);
if (r == c) diagonalAbsDiff(mat, r);

printf("Enter element to search: ");


scanf("%d", &key);
searchInSortedMatrix(mat, r, c, key);

return 0;
}

Example Input

Enter rows and columns of matrix: 3 3


Enter 3x3 matrix elements:
10 20 30
5 25 35
1 2 3
Enter element to search: 25

Example Output

Row 1 Max: 30
Row 2 Max: 35
Row 3 Max: 3
Row 1 Min: 10
Row 2 Min: 5
Row 3 Min: 1
Col 1 Max: 10
Col 2 Max: 25
Col 3 Max: 35
Col 1 Min: 1
Col 2 Min: 2
Col 3 Min: 3
Product of min(upper) and max(lower): 100
Min Row Sum: 6
Max Column Sum: 68
Row with max 1s: 2
Quotient: 1
Remainder: 33
Absolute Diagonal Difference: 33
Element 25 found at (1, 1)

1. Find the Kth Smallest Element in a Matrix


#include <stdio.h>
#include <stdlib.h>
#define MAX 100
void inputMatrix(int mat[MAX][MAX], int r, int c) {
for(int i = 0; i < r; i++)
for(int j = 0; j < c; j++)
scanf("%d", &mat[i][j]);
}
int compare(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
}
int kthSmallest(int mat[MAX][MAX], int r, int c, int k) {
int arr[MAX*MAX], idx = 0;
for(int i = 0; i < r; i++)
for(int j = 0; j < c; j++)
arr[idx++] = mat[i][j];
qsort(arr, idx, sizeof(int), compare);
return arr[k-1];
}
int main() {
int mat[MAX][MAX], r, c, k;
printf("Enter rows and columns: ");
scanf("%d %d", &r, &c);
printf("Enter matrix elements:\n");
inputMatrix(mat, r, c);
printf("Enter value of k: ");
scanf("%d", &k);
printf("Kth Smallest Element: %d\n", kthSmallest(mat, r, c, k));
return 0;
}
Example Input:
Enter rows and columns: 3 3
Enter matrix elements:10 20 305 25 351 2 3
Enter value of k: 4
Example Output:
Kth Smallest Element: 5

2. Find the Kth Largest Element in a Matrix


// Similar to the previous program, but sort in descending order

int compareDesc(const void *a, const void *b) {


return (*(int*)b - *(int*)a);
}
int kthLargest(int mat[MAX][MAX], int r, int c, int k) {
int arr[MAX*MAX], idx = 0;
for(int i = 0; i < r; i++)
for(int j = 0; j < c; j++)
arr[idx++] = mat[i][j];
qsort(arr, idx, sizeof(int), compareDesc);
return arr[k-1];
}
Example Input:
Enter value of k: 2
Example Output:
Kth Largest Element: 30

3. Check Equality of Two Matrices


int areEqual(int mat1[MAX][MAX], int mat2[MAX][MAX], int r, int
c) {
for(int i = 0; i < r; i++)
for(int j = 0; j < c; j++)
if(mat1[i][j] != mat2[i][j])
return 0;
return 1;
}
Example Input:
Matrix 1:1 2 34 5 67 8 9
Matrix 2:1 2 34 5 67 8 9
Example Output:
Matrices are equal.

4. Add Two Matrices


void addMatrices(int mat1[MAX][MAX], int mat2[MAX][MAX], int
res[MAX][MAX], int r, int c) {
for(int i = 0; i < r; i++)
for(int j = 0; j < c; j++)
res[i][j] = mat1[i][j] + mat2[i][j];
}
Example Output:
Resultant Matrix:2 4 68 10 1214 16 18

5. Subtract Two Matrices


void subtractMatrices(int mat1[MAX][MAX], int mat2[MAX][MAX],
int res[MAX][MAX], int r, int c) {
for(int i = 0; i < r; i++)
for(int j = 0; j < c; j++)
res[i][j] = mat1[i][j] - mat2[i][j];
}
Example Output:
Resultant Matrix:0 0 00 0 00 0 0

6. Multiply Two Matrices


void multiplyMatrices(int mat1[MAX][MAX], int mat2[MAX][MAX],
int res[MAX][MAX], int r1, int c1, int c2) {
for(int i = 0; i < r1; i++)
for(int j = 0; j < c2; j++) {
res[i][j] = 0;
for(int k = 0; k < c1; k++)
res[i][j] += mat1[i][k] * mat2[k][j];
}
}
Example Output:
Resultant Matrix:30 36 4266 81 96102 126 150
7. Sort Each Row of a Matrix
void sortRows(int mat[MAX][MAX], int r, int c) {
for(int i = 0; i < r; i++)
qsort(mat[i], c, sizeof(int), compare);
}
Example Output:
Sorted Matrix:1 2 34 5 67 8 9

8. Sum of 'Z' Sequence in a Matrix


int sumZSequence(int mat[MAX][MAX], int n) {
int sum = 0;
for(int i = 0; i < n; i++)
sum += mat[0][i]; // Top row
for(int i = 1; i < n-1; i++)
sum += mat[i][n - i - 1]; // Diagonal
for(int i = 0; i < n; i++)
sum += mat[n - 1][i]; // Bottom row
return sum;
}
Example Output:
Sum of 'Z' sequence: 45

9. Print Unique Rows in a Binary Matrix


#include <string.h>
void printUniqueRows(int mat[MAX][MAX], int r, int c) {
int unique[MAX][MAX], uniqueCount = 0;
for(int i = 0; i < r; i++) {
int isUnique = 1;
for(int j = 0; j < uniqueCount; j++) {
if(memcmp(mat[i], unique[j], c * sizeof(int)) == 0) {
isUnique = 0;
break;
}
}
if(isUnique) {
memcpy(unique[uniqueCount], mat[i], c * sizeof(int));
uniqueCount++;
}
}
printf("Unique Rows:\n");
for(int i = 0; i < uniqueCount; i++) {
for(int j = 0; j < c; j++)
printf("%d ", unique[i][j]);
printf("\n");
}
}
Example Output:
Unique Rows:1 0 00 1 0

10. Print Unique Columns in a Binary Matrix


void printUniqueColumns(int mat[MAX][MAX], int r, int c) {
int unique[MAX][MAX], uniqueCount = 0;
for(int j = 0; j < c; j++) {
int isUnique = 1;
for(int k = 0; k < uniqueCount; k++) {
int match = 1;
for(int i = 0; i < r; i++) {
if(mat[i][j] != unique[i][k]) {
match = 0;
break;
}
}
if(match) {
isUnique = 0;
break;
}
}
if(isUnique) {
for(int i = 0; i < r; i++)
unique[i][uniqueCount] = mat[i][j];
uniqueCount++;
}
}
printf("Unique Columns:\n");
for(int i = 0; i < r; i++) {
for(int j = 0; j < uniqueCount; j++)
printf("%d ", unique[i][j]);
printf("\n");
}
}
Example Output:
Unique Columns:1 00 10 0

QUESTIONS ON FILES, STRUCTURES & UNIONS:

1. Student Structure: Input and Display


1. Write a C program to create a struct, named Student, representing the student’s details as
follows: first_name, last_name, Age and standard.
Example
Read student data
john
carmack
15
10
Display the data in the following format
First Name: john
Last Name: carmack
Age: 15
Standard: 10

Program:
#include <stdio.h>
struct Student {
char first_name[50];
char last_name[50];
int age;
int standard;
};
int main() {
struct Student s;
printf("Read student data:\n");
scanf("%s", s.first_name);
scanf("%s", s.last_name);
scanf("%d", &[Link]);
scanf("%d", &[Link]);

printf("First Name: %s\n", s.first_name);


printf("Last Name: %s\n", s.last_name);
printf("Age: %d\n", [Link]);
printf("Standard: %d\n", [Link]);
return 0;
}
Sample Input:
john
Carmack
15
10
Sample Output:
First Name: john
Last Name: carmack
Age: 15
Standard: 10

2. Determine Quadrant of a Point


2. Declare a structure POINT. Input the coordinates of point variable and write a C program
to determine the quadrant in which it lies. The following table can be used to determine the
quadrant.
Quadrant
X
Y
1
Positive
Positive
2
Negative
Positive
3
Negative
Negative
4
Positive
Negative
Example
Input the values for X and Y coordinate: 7 9
The coordinate point (7,9) lies in the First quadrant.

Program:
#include <stdio.h>
struct Point {
int x;
int y;
};
int main() {
struct Point p;
printf("Input the values for X and Y coordinate: ");
scanf("%d %d", &p.x, &p.y);

if (p.x > 0 && p.y > 0)


printf("The coordinate point (%d,%d) lies in the First
quadrant.\n", p.x, p.y);
else if (p.x < 0 && p.y > 0)
printf("The coordinate point (%d,%d) lies in the Second
quadrant.\n", p.x, p.y);
else if (p.x < 0 && p.y < 0)
printf("The coordinate point (%d,%d) lies in the Third
quadrant.\n", p.x, p.y);
else if (p.x > 0 && p.y < 0)
printf("The coordinate point (%d,%d) lies in the Fourth
quadrant.\n", p.x, p.y);
else if (p.x == 0 && p.y == 0)
printf("The coordinate point (%d,%d) lies at the Origin.\n", p.x,
p.y);
else if (p.x == 0)
printf("The coordinate point (%d,%d) lies on the Y-axis.\n", p.x,
p.y);
else if (p.y == 0)
printf("The coordinate point (%d,%d) lies on the X-axis.\n",
p.x, p.y);

return 0;
}
Sample Input:
79
Sample Output:
The coordinate point (7,9) lies in the First quadrant.
3. Book Information Using Structures
3. Bob and Alice both are friends. Bob asked Alice how to store the information of the books using
Structures. Then Alice written a c program to store the information of books using book structure
by taking different attributes like book_name, author, book_id, price. Write a C program to read
and display the attributes of the books using structures.
Sample Input:
Enter number of books: 1
Enter the book name: c Programming
Enter the author name: balaguruswamy
Enter the book ID: 23413
Enter the book price: 500
Sample Output:
The details of the book are:
The book name is: c Programming
The author name is: balaguruswamy
The book ID is: 23413
The book price is: 500.00

Program:
#include <stdio.h>
struct Book {
char book_name[100];
char author[100];
int book_id;
float price;
};
int main() {
int n;
printf("Enter number of books: ");
scanf("%d", &n);
struct Book b[n];

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


printf("Enter the book name: ");
scanf(" %[^\n]", b[i].book_name);
printf("Enter the author name: ");
scanf(" %[^\n]", b[i].author);
printf("Enter the book ID: ");
scanf("%d", &b[i].book_id);
printf("Enter the book price: ");
scanf("%f", &b[i].price);
}

printf("The details of the book(s) are:\n");


for (int i = 0; i < n; i++) {
printf("The book name is: %s\n", b[i].book_name);
printf("The author name is: %s\n", b[i].author);
printf("The book ID is: %d\n", b[i].book_id);
printf("The book price is: %.2f\n", b[i].price);
}
return 0;
}
Sample Input:
Enter number of books: 1
Enter the book name: c Programming
Enter the author name: balaguruswamy
Enter the book ID: 23413
Enter the book price: 500
Sample Output:
The details of the book(s) are:The book name is: c Programming
The author name is: balaguruswamy The book ID is: 23413The
book price is: 500.00

4. Addition of Two Complex Numbers Using


Structures
4. Ramesh wants to do addition on complex numbers. He did it with regular practice but Charan
asked him to do with the help of structures by following below Criteria.
Write a C program that defines a structure named ‘Complex’ consisting of two floating point
members called “real and imaginary”. Let c1 and c2 are two Complex variables; compute the
sum of two variables.
Example:
c1= 2 8
c2= 6 4
Sum= 8.000000+12.000000i

Program:
#include <stdio.h>
struct Complex {
float real;
float imaginary;
};
int main() {
struct Complex c1, c2, sum;

printf("Enter real and imaginary parts of first complex number:


");
scanf("%f %f", &[Link], &[Link]);

printf("Enter real and imaginary parts of second complex


number: ");
scanf("%f %f", &[Link], &[Link]);

[Link] = [Link] + [Link];


[Link] = [Link] + [Link];

printf("Sum = %.6f + %.6fi\n", [Link], [Link]);

return 0;
}
Sample Input:
Enter real and imaginary parts of first complex number: 2 8
Enter real and imaginary parts of second complex number: 6 4
Sample Output:
Sum = 8.000000 + 12.000000i

5. Customer Payment Details with Nested Structures


5. Customer Payment Details is a structure with members as customers_name, address,
account_number, payment_status(paid(1)/ not_paid(0)), due_date, and amount. In this example,
payment_date is another structure with month, day and year as integer members. So, every
customer record can be considered as an array of structures.
Write a C program that displays the amount to be paid by each customer along with their names.
If payment_status is 1, display NIL for such customers.
Input Format:
First line of input contains ‘n’ number of customers, followed by 8 lines of input for each
customer. Each line represents (customers_name, address, account_number, amount
payment_status(paid(1)/ not_paid(0)), and due_date).
Output Format: First line of output is Amount to be paid by each customer as on date: followed
by n lines of output. Each line contains name of the customer followed by tab space, and
amount to be paid.
Hint: Use nested structure to represent date.
#include <stdio.h>
#include <string.h>
struct Date {
int day, month, year;
};
struct Customer {
char name[50];
char address[100];
int account_number;
float amount;
int payment_status;
struct Date due_date;
};
int main() {
int n;
printf("Enter number of customers: ");
scanf("%d", &n);
struct Customer c[n];

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


printf("\nEnter details for customer %d\n", i + 1);
printf("Name: ");
scanf(" %[^\n]", c[i].name);
printf("Address: ");
scanf(" %[^\n]", c[i].address);
printf("Account Number: ");
scanf("%d", &c[i].account_number);
printf("Amount: ");
scanf("%f", &c[i].amount);
printf("Payment Status (1=Paid, 0=Not Paid): ");
scanf("%d", &c[i].payment_status);
printf("Due Date (dd mm yyyy): ");
scanf("%d %d %d", &c[i].due_date.day, &c[i].due_date.month,
&c[i].due_date.year);
}

printf("\nAmount to be paid by each customer as on date:\n");


for (int i = 0; i < n; i++) {
printf("%s\t", c[i].name);
if (c[i].payment_status == 1)
printf("NIL\n");
else
printf("%.2f\n", c[i].amount);
}

return 0;
}
Sample Input:
1 Ravi Hyderabad 123451000010 5 2025
Sample Output:
Amount to be paid by each customer as on date:
Ravi 1000.00

6. Print Customers with Balance < 100


6. Write a ‘C’ program to accept customer details such as: Account_no, Name, Balance using
structure. Assume 3 customers in the bank. Write a function to print the account no. and name
of each customer whose balance < 100 Rs.

#include <stdio.h>
struct Customer {
int account_no;
char name[50];
float balance;
};
void low_balance(struct Customer c[], int n) {
printf("\nCustomers with balance less than 100:\n");
for (int i = 0; i < n; i++) {
if (c[i].balance < 100)
printf("Account No: %d, Name: %s\n", c[i].account_no,
c[i].name);
}
}
int main() {
struct Customer c[3];

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


printf("\nEnter details for customer %d\n", i + 1);
printf("Account Number: ");
scanf("%d", &c[i].account_no);
printf("Name: ");
scanf(" %[^\n]", c[i].name);
printf("Balance: ");
scanf("%f", &c[i].balance);
}

low_balance(c, 3);
return 0;
}

7. Employee with Highest Salary


7. Write a C program to accept details of ‘n’ employee(eno, ename, salary) and display the details
of employee having highest salary. Use array of structure.

#include <stdio.h>
struct Employee {
int eno;
char ename[50];
float salary;
};
int main() {
int n;
printf("Enter number of employees: ");
scanf("%d", &n);

struct Employee e[n], highest;


[Link] = 0;

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


printf("\nEnter details for employee %d\n", i + 1);
printf("Emp No: ");
scanf("%d", &e[i].eno);
printf("Name: ");
scanf(" %[^\n]", e[i].ename);
printf("Salary: ");
scanf("%f", &e[i].salary);

if (e[i].salary > [Link])


highest = e[i];
}

printf("\nEmployee with highest salary:\n");


printf("Emp No: %d, Name: %s, Salary: %.2f\n", [Link],
[Link], [Link]);
return 0;
}

8. Electricity Bill Calculation


8. Write a C program to print the bill details of ‘N’ number of customers with the following data:
meter number, customer name, no of units consumed, bill date, last date to deposit and city.
The bill is to be calculated according to the following conditions:
No. of units
Charges
For first 100 units
Rs.0.75 per unit
For the next 200 units
Rs.1.80 per unit
For the next 200 units
Rs.2.75 per unit
Sample Input
Enter no. of customers
1
Enter Meter Number AP01213
Enter Customer Name: Karthik
Enter No. of units consumed: 200
Enter Bill date:22/01/2021
Enter Last date: 12/2/2021
Enter City: Guntur
Sample Output
Meter Number AP01213
Customer Name: Karthik
No. of units consumed: 200
Bill date:22/01/2021
Last date: 12/2/2021
City: Guntur
Total Amount: 255.000000

#include <stdio.h>
struct Customer {
char meter_no[20];
char name[50];
int units;
char bill_date[20];
char last_date[20];
char city[50];
};
float calculate_bill(int units) {
float total = 0;
if (units <= 100)
total = units * 0.75;
else if (units <= 300)
total = 100 * 0.75 + (units - 100) * 1.80;
else
total = 100 * 0.75 + 200 * 1.80 + (units - 300) * 2.75;
return total;
}
int main() {
int n;
printf("Enter no. of customers: ");
scanf("%d", &n);
struct Customer c[n];

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


printf("\nEnter Meter Number: ");
scanf(" %[^\n]", c[i].meter_no);
printf("Enter Customer Name: ");
scanf(" %[^\n]", c[i].name);
printf("Enter No. of units consumed: ");
scanf("%d", &c[i].units);
printf("Enter Bill date (dd/mm/yyyy): ");
scanf(" %[^\n]", c[i].bill_date);
printf("Enter Last date to deposit: ");
scanf(" %[^\n]", c[i].last_date);
printf("Enter City: ");
scanf(" %[^\n]", c[i].city);
}

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


printf("\nMeter Number %s\n", c[i].meter_no);
printf("Customer Name: %s\n", c[i].name);
printf("No. of units consumed: %d\n", c[i].units);
printf("Bill date: %s\n", c[i].bill_date);
printf("Last date: %s\n", c[i].last_date);
printf("City: %s\n", c[i].city);
printf("Total Amount: %.6f\n", calculate_bill(c[i].units));
}
return 0;
}

9. File: Display Students in CSE


9. Write a C program that creates a student file containing {Roll No, Student Name, Address,
Stream}, where the data will be inserted and display the list of students who are in CSE
(Stream=CSE).
Input: A file name
Output: The attributes such as Roll_No, Student_Name, Stream, Address.
Sample Input
201fa4200
Raja
CSE
Guntur
201fa4201
Bala
IT
Tenali
Sample Output
201fa4200
Raja
CSE
Guntur

#include <stdio.h>
#include <string.h>
struct Student {
char roll_no[20];
char name[50];
char stream[10];
char address[50];
};
int main() {
FILE *fp = fopen("[Link]", "r");
struct Student s;

if (fp == NULL) {
printf("File not found.\n");
return 1;
}

printf("Students in CSE Stream:\n");


while (fscanf(fp, "%s %s %s %s", s.roll_no, [Link], [Link],
[Link]) != EOF) {
if (strcmp([Link], "CSE") == 0)
printf("%s %s %s %s\n", s.roll_no, [Link], [Link],
[Link]);
}

fclose(fp);
return 0;
}
You can manually create [Link] file with:
201fa4200 Raja CSE Guntur
201fa4201 Bala IT Tenali
10. Convert All Lowercase to Uppercase in File
10. Write a C program that reads content from an existing text file and write the same in a new file
by changing all lowercase alphabetic character to upper case. (Existing file may contain digit
and special characters).
Example:
Input: Enter the file name.
Output: New file with updated content.

#include <stdio.h>
#include <ctype.h>
int main() {
FILE *source, *destination;
char filename[100], ch;

printf("Enter the file name to read: ");


scanf("%s", filename);

source = fopen(filename, "r");


if (source == NULL) {
printf("Could not open file for reading.\n");
return 1;
}

destination = fopen("[Link]", "w");


if (destination == NULL) {
printf("Could not open file for writing.\n");
fclose(source);
return 1;
}
while ((ch = fgetc(source)) != EOF) {
fputc(toupper(ch), destination); // Convert each character to
uppercase
}

printf("Content written to [Link] with all lowercase


converted to uppercase.\n");

fclose(source);
fclose(destination);
return 0;
}
Sample Input:
Enter the file name to read: [Link]
Sample Output:
Content written to [Link] with all lowercase converted to
uppercase.

11. Count Occurrences of a String in a File


11. Write a C program to count the occurrences of the given string in a file.
Example:
Input: Enter the File name to read the string to be counted.
Output: Display the count of occurrences of the string.

#include <stdio.h>
#include <string.h>
int main() {
FILE *file;
char filename[100], word[100], line[256];
int count = 0;

printf("Enter the file name: ");


scanf("%s", filename);
printf("Enter the string to be counted: ");
scanf(" %[^\n]", word);

file = fopen(filename, "r");


if (file == NULL) {
printf("Could not open file for reading.\n");
return 1;
}

while (fgets(line, sizeof(line), file)) {


char *ptr = line;
while ((ptr = strstr(ptr, word)) != NULL) {
count++;
ptr++;
}
}

printf("The string '%s' occurred %d times in the file.\n", word,


count);

fclose(file);
return 0;
}
Sample Input:
Enter the file name: [Link]
Enter the string to be counted: C programming
Sample Output:
The string 'C programming' occurred 3 times in the file.

12. Transfer Data from One File to Another


12. Write a C Program to transfer the data from one location to another location without changing
the order of the content.
Example:
Read the file name from the user. If the source file exists, Transfer the data and display the
message as “Data is transferred successfully” otherwise display the message “No such file is
existing in the directory.”
#include <stdio.h>
int main() {
FILE *source, *destination;
char source_filename[100], destination_filename[100];
char ch;

printf("Enter the source file name: ");


scanf("%s", source_filename);

source = fopen(source_filename, "r");


if (source == NULL) {
printf("No such file is existing in the directory.\n");
return 1;
}

printf("Enter the destination file name: ");


scanf("%s", destination_filename);

destination = fopen(destination_filename, "w");


if (destination == NULL) {
printf("Could not open destination file for writing.\n");
fclose(source);
return 1;
}

while ((ch = fgetc(source)) != EOF) {


fputc(ch, destination); // Transfer content
}
printf("Data is transferred successfully.\n");

fclose(source);
fclose(destination);
return 0;
}
Sample Input:
Enter the source file name: [Link]
Enter the destination file name: [Link]
Sample Output:
Data is transferred successfully.

13. Separate Odd and Even Numbers into Files

13. Write a C program that reads numbers and write them into a text-file. Also find odd and even
numbers in that file and store it in 2 separate files named [Link] and [Link]. All the values
should be in ascending order.
Input: Enter the values.
Output: Creates a separate file for Even and Odd numbers.
Sample Input:
4 43 2 53 45
Sample Output:
[Link]: 2 4
[Link]: 43 45 53
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *odd_file, *even_file;
int numbers[100], n, i;

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


scanf("%d", &n);

printf("Enter the values: ");


for (i = 0; i < n; i++) {
scanf("%d", &numbers[i]);
}

// Sorting the numbers


for (i = 0; i < n-1; i++) {
for (int j = i+1; j < n; j++) {
if (numbers[i] > numbers[j]) {
int temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
}
}

odd_file = fopen("[Link]", "w");


even_file = fopen("[Link]", "w");
if (odd_file == NULL || even_file == NULL) {
printf("Error opening file.\n");
return 1;
}

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


if (numbers[i] % 2 == 0)
fprintf(even_file, "%d ", numbers[i]);
else
fprintf(odd_file, "%d ", numbers[i]);
}

printf("Even numbers in [Link] and Odd numbers in [Link].\


n");

fclose(odd_file);
fclose(even_file);
return 0;
}
Sample Input:
Enter the number of values: 5
Enter the values: 4 43 2 53 45
Sample Output:
Even numbers in [Link] and Odd numbers in [Link].
Content of [Link]:
24
Content of [Link]:
43 45 53

14. Replace Content in the Given Text File


14. Write a C program to replace the content in the given text file.
Input: Enter the file name, line number to be replaced and the new content
Output: New file with replaced lines.
Example:
Sample Input:
Enter the file name: [Link]
Enter the line no to replace: 3
Enter the content: Files stores data presently.
Sample Output:
Line no 3 is replaced with the given content.
The content of the file [Link] contains:
test line 1
test line 2
Files stores data presently
test line 4

#include <stdio.h>
int main() {
FILE *file;
char filename[100], new_content[200];
int line_num, current_line = 1;
char line[200];

printf("Enter the file name: ");


scanf("%s", filename);

printf("Enter the line number to replace: ");


scanf("%d", &line_num);

file = fopen(filename, "r+");


if (file == NULL) {
printf("Could not open file for reading and writing.\n");
return 1;
}

printf("Enter the new content for line %d: ", line_num);


scanf(" %[^\n]", new_content);

while (fgets(line, sizeof(line), file)) {


if (current_line == line_num) {
fseek(file, -strlen(line), SEEK_CUR); // Move pointer to start
of line
fprintf(file, "%s\n", new_content); // Replace the line with
new content
printf("Line no %d is replaced with the given content.\n",
line_num);
break;
}
current_line++;
}

fclose(file);
return 0;
}
Sample Input:
Enter the file name: [Link]
Enter the line number to replace: 3
Enter the new content for line 3: Files stores data presently.
Sample Output:
Line no 3 is replaced with the given content.
Content of [Link] after replacement:
test line 1
test line 2
Files stores data presently
test line 4

You might also like