Click Show Code to view each solution. Use Copy to copy the code.
1. Write a program to print “Hello World”.
Copied!
#include <stdio.h>
int main() {
printf("Hello World\n");
return 0;
}
2. Write a program to add two numbers entered by the user.
Copied!
#include <stdio.h>
int main() {
int a, b, sum;
printf("Enter two integers: ");
scanf("%d %d", &a, &b);
sum = a + b;
printf("Sum = %d\n", sum);
return 0;
}
3. Write a program to find the largest of two numbers.
Copied!
#include <stdio.h>
int main() {
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
if (a > b)
printf("%d is larger\n", a);
else if (b > a)
printf("%d is larger\n", b);
else
printf("Both are equal\n");
return 0;
}
4. Write a program to check whether a number is even or odd.
Copied!
#include <stdio.h>
int main() {
int n;
printf("Enter an integer: ");
scanf("%d", &n);
if (n % 2 == 0)
printf("%d is Even\n", n);
else
printf("%d is Odd\n", n);
return 0;
}
5. Write a program to calculate the area of a circle (area = π * r * r).
Copied!
#include <stdio.h>
int main() {
float r, area;
const float PI = 3.1415926f;
printf("Enter radius: ");
scanf("%f", &r);
area = PI * r * r;
printf("Area = %.4f\n", area);
return 0;
}
6. Write a program to swap two numbers (use a temporary variable).
Copied!
#include <stdio.h>
int main() {
int a, b, temp;
printf("Enter two integers (a b): ");
scanf("%d %d", &a, &b);
printf("Before swap: a = %d, b = %d\n", a, b);
temp = a;
a = b;
b = temp;
printf("After swap: a = %d, b = %d\n", a, b);
return 0;
}
7. Write a program to find the sum of natural numbers from 1 to n.
Copied!
#include <stdio.h>
int main() {
int n, i, sum = 0;
printf("Enter n: ");
scanf("%d", &n);
for (i = 1; i <= n; ++i) {
sum += i;
}
printf("Sum of first %d natural numbers = %d\n", n, sum);
return 0;
}
8. Write a program to print the multiplication table of a given number.
Copied!
#include <stdio.h>
int main() {
int n, i;
printf("Enter a number: ");
scanf("%d", &n);
for (i = 1; i <= 10; ++i) {
printf("%d x %d = %d\n", n, i, n * i);
}
return 0;
}
9. Write a program to check whether a number is positive, negative or zero.
Copied!
#include <stdio.h>
int main() {
int n;
printf("Enter a number: ");
scanf("%d", &n);
if (n > 0)
printf("Positive\n");
else if (n < 0)
printf("Negative\n");
else
printf("Zero\n");
return 0;
}
10. Write a program to find the factorial of a number.
Copied!
#include <stdio.h>
int main() {
int n, i;
unsigned long long fact = 1ULL;
printf("Enter a non-negative integer: ");
scanf("%d", &n);
if (n < 0) {
printf("Factorial is not defined for negative numbers.\n");
} else {
for (i = 1; i <= n; ++i)
fact *= i;
printf("Factorial of %d = %llu\n", n, fact);
}
return 0;
}
Tip: In Blogspot switch to HTML editor, paste this block, then switch back to Compose to see it.