更新於 2023/08/27閱讀時間約 4 分鐘

C Programming: For Loop

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;
}


分享至
成為作者繼續創作的動力吧!
從 Google News 追蹤更多 vocus 的最新精選內容從 Google News 追蹤更多 vocus 的最新精選內容

你可能也想看

發表回應

成為會員 後即可發表留言
© 2024 vocus All rights reserved.