Spring 2025FinalStructured programming
Solutions
Reference answers and worked solutions.
1. Largest and smallest using pointers
Steps:
- Read n and input n integers into an array.
- Sort the array using bubble sort with pointer-based comparisons/swaps.
- After sorting, let p point to the first element; smallest = _p, largest = _(p + n - 1).
- Print the largest and smallest values.
#include <stdio.h>
int main()
{
int n, temp;
printf("Enter array length ->");
scanf("%d", &n);
int arr[n];
printf("Enter %d numbers->", n);
for (int i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
int largest, smallest;
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - 1 - i; j++)
{
int *p = &arr[j];
if (*p > *(p + 1))
{
temp = *p;
*p = *(p + 1);
*(p + 1) = temp;
}
}
}
int *p=arr;
largest = *(p+n-1);
smallest = *p;
printf("Largest is %d and smallest is %d", largest, smallest);
return 0;
}2. Armstrong numbers 1–500
Steps:
- Loop j from 1 to 500.
- For each number, count digits, extract digits, and sum digit^count.
- If the sum equals the original number, print it.
#include <stdio.h>
#include <math.h>
int main()
{
for (int j = 1; j <= 500; j++)
{
int actual=j;
int test = actual, temp = actual;
int count = 0;
while (test != 0)
{
test = test / 10;
count++;
}
int arr[count], i = 0;
while (temp != 0)
{
arr[i] = temp % 10;
temp = temp / 10;
i++;
}
int total = 0;
for (int i = 0; i < count; i++)
{
total = total + (int)pow(arr[i], count);
}
if (total == actual)
{
printf("%d ",actual);
}
}
return 0;
}3. Sum of positives and negatives from file
Steps:
- Open "numbers.txt" for reading.
- Read integers until EOF.
- If x > 0 add to positive sum, else add to negative sum.
- Close the file and print both sums.
#include <stdio.h>
int main(){
FILE *file;
int x,sumN=0,sumP=0;
file=fopen("numbers.txt","r");
while (fscanf(file,"%d",&x)==1) // used 1 bcz EOF value in c is -1, which will be a problem
{
if(x>0)
{
sumP+=x;
}
else
{
sumN+=x;
}
}
fclose(file);
printf("Result is %d for positive and %d for negative",sumP,sumN);
return 0;
}4. Factorial of 1 to n (for loop)
Steps:
- Read x (how many factorials to print).
- For each i from 1 to x, set factorial = 1 and multiply 1 to i in an inner loop.
- Print each factorial value as it is computed.
#include <stdio.h>
int main(){
int x;
printf("Enter how many factorial number you want->");
scanf("%d",&x);
for (int i = 1; i <= x; i++)
{
int factorial=1;
for (int j = 1; j <= i; j++)
{
factorial=factorial*j;
}
printf("%d ",factorial);
}
return 0;
}5. Prime check for N test cases (simple trial division)
Steps:
- Read t (number of test cases).
- For each num, count divisors by testing j from 1 to num.
- If
num <= 1, print specific message; else print Prime ifcount == 2, otherwise Not a prime.
#include <stdio.h>
int main()
{
int x, num;
printf("How many times you want to run the test->");
scanf("%d", &x);
for (int i = 0; i < x; i++)
{
int count = 0;
printf("Enter Number->");
scanf("%d", &num);
for (int j = 1; j <= num; j++)
{
if (num % j == 0)
{
count++;
}
}
if (num == 1 || num <= 0)
{
printf("Enter any number other than 1 ,negative integer or 0\n");
}
else if (count == 2)
{
printf("Prime\n");
}
else
{
printf("Not a prime\n");
}
}
return 0;
}6. Swap without third variable
Steps:
- Read a and b.
- Swap without a third variable: a = a + b; b = a - b; a = a - b.
- Print the swapped values.
#include <stdio.h>
int main()
{
int a, b;
printf("Enter 2 numbers ->");
scanf("%d %d", &a, &b);
a = a + b;
b = a - b;
a = a - b;
printf("%d %d", a, b);
return 0;
}7. Sum of primes 1–50
Steps:
- Iterate i from 1 to 50.
- For each i, count divisors using a simple loop; prime iff count == 2.
- Add primes to a running sum and print the total.
#include <stdio.h>
int main(){
int result=0,count;
for (int i = 1; i <= 50; i++)
{
count=0;
for (int j = 1; j <= i; j++)
{
if(i%j==0)
{
count++;
}
}
if(count==2)
{
result+=i;
}
}
printf("Sum of all prime(1-50) is %d",result);
return 0;
}8. Write 1–10 to file and sum
Steps:
- Open "output.txt" in write mode and write 1 to 10.
- Close, reopen in read mode, and read integers until EOF accumulating the sum.
- Print the sum.
#include <stdio.h>
int main(){
FILE *file;
file=fopen("output.txt","w");
for (int i = 1; i <= 10; i++)
{
fprintf(file,"%d ",i);
}
fclose(file);
int sum=0,n;
file=fopen("output.txt","r");
while(fscanf(file,"%d",&n)!=EOF)
{
sum+=n;
}
printf("Sum is %d",sum);
return 0;
}9. Palindrome string (no string.h)
Steps:
- Read a line using fgets into a char array.
- Compute length until the newline character.
- Compare str[i] with str[length - 1] while moving inward; decide palindrome and print.
#include <stdio.h>
int main()
{
char str[100];
printf("Enter String->");
fgets(str, sizeof(str), stdin);
fflush(stdin);
int length = 0, j = 0;
while (str[length] != '\n')
{
length++;
}
printf("%d\n", length);
int count = 1;
for (int i = 0; i < length; i++)
{
if (str[i] != str[length - 1])
{
count = -1;
break;
}
length--;
}
if (count == 1)
{
printf("Palindrome");
}
else
{
printf("Not a plaindrome");
}
return 0;
}10. Merge two arrays
Steps:
- Read m and n, then fill two arrays of those sizes.
- Create an array of size m + n; copy first array then second into it.
- Print the merged array values in order.
#include <stdio.h>
int main(){
int x=0,m,n;
printf("Enter size of 2 arrays->");
scanf("%d %d",&m,&n);
int arr1[m], arr2[n], arr[m+n];
printf("Enter inputs for first array->");
for (int i = 0; i < m; i++)
{
scanf("%d",&arr1[i]);
}
printf("Enter inputs for second array->");
for (int i = 0; i < n; i++)
{
scanf("%d",&arr2[i]);
}
for (int i = 0; i < m; i++)
{
arr[x]=arr1[i];
x++;
}
for (int i = 0; i < n; i++)
{
arr[x]=arr2[i];
x++;
}
printf("Merged array of array 1 and 2 is->");
for (int i = 0; i < x; i++)
{
printf("%d",arr[i]);
}
return 0;
}11. Hollow square pattern
Steps:
- Read n (side length). Validate n > 1; otherwise print "Too small box." and exit.
- Print the top border: '* ' repeated n times, then newline.
- For each of the n-2 middle rows: print '* ', then (n-2) double-spaces, then '* ', then newline.
- Print the bottom border the same as the top.
#include <stdio.h>
int main()
{
int n;
printf("Enter side length of the square->");
scanf("%d", &n);
if(n==1 || n<=0)
{
printf("Too small box.");
return 1;
}
for (int i = 0; i < n; i++)
{
printf("* ");
}
printf("\n");
for (int i = 0; i < n - 2; i++)
{
printf("* ");
for (int j = 0; j < n - 2; j++)
{
printf(" ");
}
printf("* ");
printf("\n");
}
for (int i = 0; i < n; i++)
{
printf("* ");
}
printf("\n");
return 0;
}12. First 20 terms of AP (a=5, d=3)
Steps:
- Use term(i) = a + (i - 1)*d for i = 1 to 20.
- Print each term space-separated.
#include <stdio.h>
int main(){
int a=5,d=3;
for (int i = 1; i <=20; i++)
{
int c=a+((i-1)*d);
printf("%d ",c);
}
return 0;
}13. Perfect numbers 1–500
Steps:
- For each n in 1 to 500, sum all divisors 1 to n, then subtract n to get proper-divisor sum.
- If that sum equals n, print n.
#include <stdio.h>
int main()
{
for (int i = 1; i <= 500; i++)
{
int result = 0;
for (int j = 1; j <= i; j++)
{
if (i % j == 0)
{
result = result + j;
}
}
result = result - i;
if (result == i)
{
printf("%d ", i);
}
}
return 0;
}14. Count vowels in a string
Steps:
- Read a line of input.
- Normalize to lowercase (or check both cases).
- Count occurrences of a, e, i, o, u.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main()
{
char str[100];
int vcount = 0;
printf("Enter string->");
fgets(str, sizeof(str), stdin);
str[strcspn(str, "\n")] = '\0';
int count = strlen(str);
for (int i = 0; i < count; i++)
{
char c = str[i];
str[i] = tolower(c);
}
for (int i = 0; i < count; i++)
{
char c = str[i];
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
{
vcount++;
}
}
printf("Vowels present at %s is %d", str, vcount);
return 0;
}15. Stats from mixed-number file
Steps:
- Open file (numbers.txt).
- Read doubles until EOF; track count, sum, min, max.
- Compute average = sum/count and print with two decimals.
#include <stdio.h>
int main()
{
FILE *file;
file = fopen("numbers.txt", "r");
double sum = 0, min = 100000, max = -min, average, n;
int count = 0;
while (fscanf(file, "%lf", &n) == 1)
{
count++;
sum = sum + n;
if (min > n)
{
min = n;
}
else if (max < n)
{
max = n;
}
}
printf("Max-> %lf\n", max);
printf("Min-> %lf\n", min);
printf("Sum-> %lf\n", sum);
printf("Average-> %.2lf\n", sum / count);
printf("Count-> %d\n", count);
return 0;
}16. Even/odd sum using ?:
Steps:
- Read two integers a and b.
- Compute s = a + b.
- Use conditional operator to print Even or Odd.
#include <stdio.h>
int main()
{
int a, b;
printf("Enter 2 integer number->");
scanf("%d %d", &a, &b);
int c = a + b;
printf((c % 2 == 0) ? "Even\n" : "odd\n");
return 0;
}17. Count positive/negative/zero in array
Steps:
- Read n and the array.
- Traverse once and count positives, negatives, zeros.
- Print the three counts.
#include <stdio.h>
int main()
{
int n;
printf("Enter array size->");
scanf("%d", &n);
int arr[n];
for (int i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
int positive = 0, negative = 0, zero = 0;
for (int i = 0; i < n; i++)
{
if (arr[i] > 0)
{
positive++;
}
else if (arr[i] < 0)
{
negative++;
}
else
{
zero++;
}
}
printf("Positive-> %d\nNegative-%d\nZero->%d\n", positive, negative, zero);
return 0;
}18. Sum of digits (iterative)
Steps:
- Use recursion: sum(n) returns n % 10 + sum(n / 10) with base case n == 0.
- Read n and print sum(n).
#include <stdio.h>
int sum(int n)
{
if (n == 0)
{
return 0;
}
else
{
return n % 10 + sum(n / 10);
}
}
int main()
{
int n;
printf("Enter number->");
scanf("%d", &n);
printf("Sum of all digits are->%d", sum(n));
return 0;
}19. Highest mark and average from file
Steps:
- Open marks file; each line has Name and Mark.
- Track best (max) mark with name and running sum/count.
- After reading, print top student and average.
#include <stdio.h>
#include <string.h>
int main()
{
FILE *file;
file = fopen("numbers.txt", "r");
int max = -1, mark, sum = 0, count = 0;
char name[100], topname[100];
while (fscanf(file, "%s %d", name, &mark) == 2)
{
if (mark > max)
{
max = mark;
strcpy(topname, name);
}
sum += mark;
count++;
}
float average = (float)sum / (float)count;
printf("Highest mark obtained by %s is %d\n And average of mark is %.3f", topname, max, average);
fclose(file);
return 0;
}20. Reverse array in place
Steps:
- Read n and array a.
- Use two-pointer swap from ends moving inward.
- Print reversed array.
#include <stdio.h>
int main(){
int n;
printf("Enter array size->");
scanf("%d",&n);
int arr[n];
printf("Enter values->");
for (int i = 0; i < n; i++)
{
scanf("%d",&arr[i]);
}
int j=n-1;
for (int i = 0; i <= n/2; i++)
{
int temp;
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
j--;
}
for (int i = 0; i < n; i++)
{
printf("%d ",arr[i]);
}
return 0;
}21. Rotate array right by one
Steps:
- Read n and array a.
- Store last element; shift right; place last at index 0.
- Print rotated array.
#include <stdio.h>
int main()
{
int n;
printf("Enter array size->");
scanf("%d", &n);
int arr[n];
int temp;
printf("Enter elements->");
for (int i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
temp = arr[n - 1];
for (int i = n - 1; i > 0; i--)
{
arr[i] = arr[i - 1];
}
arr[0] = temp;
for (int i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
return 0;
}22. Multiplication table
Steps:
- Read n.
- For i=1 to 10, print n x i = n*i.
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
for (int i = 1; i <= 10; i++) {
printf("%d x %d = %d\n", n, i, n * i);
}
return 0;
}23. GCD (iterative Euclid)
Steps:
- Implement Euclid's algorithm recursively.
- Read a and b; print gcd(a, b).
#include <stdio.h>
int gcd(int a, int b)
{
if (b == 0)
{
return a;
}
else
{
return gcd(b, a % b);
}
}
int main()
{
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
printf("GCD of %d and %d is %d\n", a, b, gcd(a, b));
return 0;
}24. Sign of product without multiplying (avoid overflow)
Steps:
- Read three integers a, b, c.
- If any number is zero, print "Zero".
- Otherwise, compute product = a _ b _ c and print "Positive" if product > 0, else "Negative".
#include <stdio.h>
int main()
{
int a, b, c, product;
printf("Enter 3 integers->");
scanf("%d%d%d", &a, &b, &c);
if (a == 0 || b == 0 || c == 0)
{
printf("Zero");
}
else
{
product = a * b * c;
printf(product>0 ? "Positive":"Negative");
}
return 0;
}25. Divisibility using ?:
Steps:
- Read a and b.
- If b != 0 and a % b == 0, print Divisible; else Not Divisible.
- Use conditional operator.
#include <stdio.h>
int main() {
int a, b;
scanf("%d %d", &a, &b);
printf((b != 0 && a % b == 0) ? "Divisible\n" : "Not Divisible\n");
return 0;
}26. Binary of integer (iterative, no arrays/strings)
Steps:
- Read unsigned integer n.
- Find the highest power of 2 not exceeding n, then print bits from high to low.
- If n is 0, print 0.
#include <stdio.h>
int main() {
unsigned int n;
scanf("%u", &n);
if (n == 0) {
putchar('0');
putchar('\n');
return 0;
}
unsigned int p = 1;
while (p <= n / 2) {
p *= 2;
}
while (p > 0) {
if (n >= p) {
putchar('1');
n -= p;
} else {
putchar('0');
}
p /= 2;
}
putchar('\n');
return 0;
}27. Count uppercase and lowercase
Steps:
- Read a line character-by-character.
- If 'A'..'Z' increment upper; if 'a'..'z' increment lower.
- Print counts.
#include <stdio.h>
int main() {
int c, up = 0, low = 0;
while ((c = getchar()) != EOF && c != '\n') {
if (c >= 'A' && c <= 'Z') {
up++;
} else if (c >= 'a' && c <= 'z') {
low++;
}
}
printf("Upper=%d Lower=%d\n", up, low);
return 0;
}28. Reverse integer (iterative)
Steps:
- Read an integer n.
- Print digits in reverse using a recursive helper that prints last digit then recurses on n/10.
- Print a newline at the end.
#include <stdio.h>
void reverse(int num)
{
if (num == 0)
return;
printf("%d", num % 10);
reverse(num / 10);
}
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d", &number);
printf("Reversed number: ");
reverse(number);
printf("\n");
return 0;
}29. Diamond pattern
Steps:
- Read n for half-height.
- Print increasing width odd stars with leading spaces, then decreasing.
- Use loops; no arrays needed.
#include <stdio.h>
int main(void) {
int n;
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
int sp = n - i;
int st = 2 * i - 1;
while (sp--) putchar(' ');
while (st--) putchar('*');
putchar('\n');
}
for (int i = n - 1; i >= 1; i--) {
int sp = n - i;
int st = 2 * i - 1;
while (sp--) putchar(' ');
while (st--) putchar('*');
putchar('\n');
}
return 0;
}30. Remove duplicates from array
Steps:
- Read n and array a.
- For each i, scan j>i and remove duplicates by shifting left and reducing size.
- Print remaining elements.
#include <stdio.h>
int main(void) {
int n;
scanf("%d", &n);
int a[n];
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
int m = n;
for (int i = 0; i < m; i++) {
for (int j = i + 1; j < m;) {
if (a[j] == a[i]) {
for (int k = j; k < m - 1; k++) {
a[k] = a[k + 1];
}
m--;
} else {
j++;
}
}
}
for (int i = 0; i < m; i++) {
printf("%d ", a[i]);
}
printf("\n");
return 0;
}