

Question 1: Write a C program to find the sum of the first n natural numbers.
Solution:
#include <stdio.h> int main()
int n, sum=0, i;
printf("Enter the value of n: "); scanf("%d", &n); for(i=1; i<=n; i++)
{ sum = sum + i;
printf("Sum of first %d natural numbers is %d", n, sum); return 0;
Question 2: Write a C program to find the largest element in an array.
Solution:
#include <stdio.h>
int main() { int n, i; int arr[100];
int max;
printf("Enter the size of array: ");
scanf("%d", &n);
printf("Enter the elements of the array:\n");
for(i=0; i<n; i++)
{ scanf("%d", &arr[i]);
} max = arr[0];
for(i=1; i<n; i++)
{ if(arr[i] > max) { max = arr[i];
} } printf("Largest element in the array is %d", max);
return 0;
Question 3: Write a C program to swap two numbers without using a temporary variable.
Solution:
#include <stdio.h> int main()
int a, b;
printf("Enter the values of a and b: "); scanf("%d %d", &a, &b);
printf("Before swapping, a = %d and b = %d\n", a, b); a = a + b; b = a - b; a = a - b;
printf("After swapping, a = %d and b = %d", a, b); return 0;
Question 4: Write a C program to check whether a given number is prime or not.
Solution:
#include <stdio.h> int main()
{ int n, i, flag=0;
printf("Enter a positive integer: "); scanf("%d", &n); for(i=2; i<=n/2; i++) { if(n%i == 0) { flag = 1; break;
if(n == 1) { printf("1 is neither prime nor composite");
else { if(flag == 0) printf("%d is a prime number", n); else printf("%d is not a prime number", n);
return 0;
Question 5: Write a C program to count the number of words in a given string.
Solution:
#include <stdio.h>
#include <string.h> int main() { char str[100]; int i, count=1;
printf("Enter a string: "); gets(str); for(i=0; i<strlen(str); i++) { if(str[i] == ' ') { count++; } }
printf("Number of words in the string is %d", count); return 0;