C Programming: For Loop

更新於 2023/08/27閱讀時間約 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;
}


avatar-img
3會員
5內容數
留言0
查看全部
avatar-img
發表第一個留言支持創作者!
你可能也想看
Google News 追蹤
Thumbnail
*合作聲明與警語: 本文係由國泰世華銀行邀稿。 證券服務係由國泰世華銀行辦理共同行銷證券經紀開戶業務,定期定額(股)服務由國泰綜合證券提供。   剛出社會的時候,很常在各種 Podcast 或 YouTube 甚至是在朋友間聊天,都會聽到各種市場動態、理財話題,像是:聯準會降息或是近期哪些科
Thumbnail
*合作聲明與警語: 本文係由國泰世華銀行邀稿。 證券服務係由國泰世華銀行辦理共同行銷證券經紀開戶業務,定期定額(股)服務由國泰綜合證券提供。   剛出社會的時候,很常在各種 Podcast 或 YouTube 甚至是在朋友間聊天,都會聽到各種市場動態、理財話題,像是:聯準會降息或是近期哪些科