Assignment 5 Answers
Assignment 5 Answers
1. Write suitable function and corresponding program to test them for the following:
(a) Compute xnx^n, where x is any valid number and n is an integer value.
#include <stdio.h>
int main() {
double x;
int n;
printf("Enter base x and exponent n: ");
scanf("%lf %d", &x, &n);
printf("%.2lf ^ %d = %.2lf\n", x, n, power(x, n));
return 0;
}
#include <stdio.h>
int main() {
int x, y;
printf("Enter two integers: ");
scanf("%d %d", &x, &y);
swap(&x, &y);
printf("After swapping: x = %d, y = %d\n", x, y);
return 0;
}
(c) Compute the GCD of two integers and return the result to the calling function.
#include <stdio.h>
int main() {
int x, y;
printf("Enter two numbers: ");
scanf("%d %d", &x, &y);
printf("GCD is %d\n", gcd(x, y));
return 0;
}
#include <stdio.h>
int main() {
int arr[100], n;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter elements:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Sum = %d\n", sumArray(arr, n));
return 0;
}
int main() {
char str[100];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
removeSpaces(str);
printf("String without spaces: %s\n", str);
return 0;
}
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
reverse(str);
printf("Reversed string: %s\n", str);
return 0;
}
3. Write a C function subs(s1, s2) which returns 1 if s2 is a substring of s1 otherwise
0.
#include <stdio.h>
#include <string.h>
int main() {
char s1[100], s2[100];
printf("Enter string 1: ");
fgets(s1, sizeof(s1), stdin);
printf("Enter string 2: ");
fgets(s2, sizeof(s2), stdin);
printf("Result: %d\n", subs(s1, s2));
return 0;
}
4. Write a C function that takes input a two dimensional array of integers and find
the largest integer among them and return it to calling function.
#include <stdio.h>
int main() {
int arr[10][10], rows, cols;
printf("Enter number of rows and columns: ");
scanf("%d %d", &rows, &cols);
printf("Enter elements:\n");
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
scanf("%d", &arr[i][j]);
printf("Largest element = %d\n", findMax(arr, rows, cols));
return 0;
}
5. Write a C function that finds the largest number from each row and column
individually.
#include <stdio.h>
int main() {
int arr[10][10], rowMax[10], colMax[10];
int rows, cols, i, j;
#include <stdio.h>
int reverseInteger(int n) {
int reversed = 0;
while (n != 0) {
reversed = reversed * 10 + n % 10;
n /= 10;
}
return reversed;
}
int main() {
int n;
printf("Enter an integer: ");
scanf("%d", &n);
printf("Reversed integer = %d\n", reverseInteger(n));
return 0;
}