2023-08-27|閱讀時間 ‧ 約 5 分鐘

C Programming: If Else, For Loop


Exercise 1: Write a program that prompts the user to enter two integers, and then outputs all even numbers between those two integers (inclusive). If the first integer is greater than the second integer, swap the two integers.

Here are two sample inputs and outputs:

Sample 1:

Enter two integers: 3 8
4 6 8

Sample 2:

Enter two integers: 10 5
6 8 10


Exercise 2: Write a program that prompts the user to enter an integer, and then outputs the sum of all the odd numbers between 1 and that integer (inclusive). If the input is not a positive integer, output an error message.

Here are two sample inputs and outputs:

Sample 1:

Enter an integer: 10
25

Sample 2:

Enter an integer: -5
Error: Input must be a positive integer.


Exercise 3: Write a program that prompts the user to enter an integer, and then outputs the sum of all the prime numbers between 1 and that integer (inclusive). If the input is not a positive integer, output an error message.

Here are two sample inputs and outputs:

Sample 1:

Enter an integer: 10
17

Sample 2:

Enter an integer: -5
Error: Input must be a positive integer.






Code Example of Exercise 1:


#include <stdio.h>

int main() {
int num1, num2,i;

printf("Enter two integers: ");
scanf("%d %d", &num1,&num2);

if(num1 > num2){
int temp = num1;
num1 = num2;
num2 = temp;
}

for(i = num1;i <= num2;i++){
if(i % 2==0){
printf("%d ", i);
}
}

return0;
}



Code Example of Exercise 2:

#include <stdio.h>

int main() {
int num, i,sum = 0;

printf("Enter an integer: ");
scanf("%d",&num);

if(num <= 0){
printf("Error: Input must be a positive integer.\n");
return0;
}

for(i = 1;i <= num;i++){
if(i % 2==1){
sum += i;
}
}

printf("%d\n",sum);

return0;
}


Code Example of Exercise 3:


#include <stdio.h>

int main() {
int num, i,j,is_prime,sum = 0;

printf("Enter an integer: ");
scanf("%d",&num);

if(num <= 0){
printf("Error: Input must be a positive integer.\n");
return0;
}

for(i = 2;i <= num;i++){
is_prime = 1;
for(j = 2;j <= i / 2;j++){
if(i % j == 0){
is_prime = 0;
break;
}
}
if(is_prime == 1){
sum += i;
}
}

printf("%d\n",sum);

return0;
}



分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.