C Programming: For Loop

2023/08/26閱讀時間約 4 分鐘

Exercise 1: Print Numbers from 1 to N

Description: Write a program that takes a positive integer N as input and prints all the numbers from 1 to N.

Input Example:

Enter a positive integer N: 5

Output Example:

Numbers from 1 to 5:
1
2
3
4
5


Exercise 2: Calculate Factorial

Description: Write a program that takes a positive integer N as input and calculates the factorial of N.

Input Example:

Enter a positive integer N: 4

Output Example:

Factorial of 4 is 24

Exercise 3: Print Multiplication Table

Description: Write a program that takes a positive integer N as input and prints the multiplication table for N.

Input Example:

Enter a positive integer N: 7

Output Example:

Multiplication table for 7:
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
...
7 x 10 = 70






Exercise 1 Complete Code:

#include <stdio.h>

int main() {
int N;

printf("Enter a positive integer N: ");
scanf("%d", &N);

printf("Numbers from 1 to %d:\n", N);
for (int i = 1; i <= N; ++i) {
printf("%d\n", i);
}

return 0;
}


Exercise 2 Complete Code:

#include <stdio.h>

int main() {
int N;
unsigned long long factorial = 1;

printf("Enter a positive integer N: ");
scanf("%d", &N);

for (int i = 1; i <= N; ++i) {
factorial *= i;
}

printf("Factorial of %d is %llu\n", N, factorial);

return 0;
}


Exercise 3 Complete Code:

#include <stdio.h>

int main() {
int N;

printf("Enter a positive integer N: ");
scanf("%d", &N);

printf("Multiplication table for %d:\n", N);
for (int i = 1; i <= 10; ++i) {
printf("%d x %d = %d\n", N, i, N * i);
}

return 0;
}


邵
I am focused on practicing programming and enjoy sharing fundamental C language exercises with everyone :)
留言0
查看全部
發表第一個留言支持創作者!
從 Google News 追蹤更多 vocus 的最新精選內容