전공/C
과제 5 - Control Flow 2 (1 ~ 5)
yha97
2021. 6. 21. 15:39
c에서 가장 많이 사용되는 반복문인 for, while문을 활용하여 해결하는 과제이다.
어디서 먼저 시작되는지, 어디서 끝나야 하는지를 확실하게 파악했기 때문에 큰 어려움은 없었다.
알파벳 소문자를 for문, while문을 통해 해결하는 문제다.
c의 경우 for(int i=0; i<n; i++)가 불가능하다. 사전에 i를 선언하고 for문을 진행해야 하는 번거로움이 있어서 조금은 귀찮았다.
#include <stdio.h>
int main(){
char al = 'a'; // default alphabet
int i=0; // counter
printf("Alphabets from a - z are:\n");
for(i=0; i<26; i++){
printf("%c\n", al+i); // printing with sum i to default alphabet
}
return 0;
}
#include <stdio.h>
int main(){
char al = 'a'; // default alphabet
printf("Alphabets from a - z are:\n");
while(al != ('z'+1)){
printf("%c\n", al); // print if alphabet is not same with 'z'+1
al++;
}
return 0;
}
맨 처음 시작하는 알파벳으로 'a'를 설정, 이후 'z'까지 1씩 증가시키면서 출력하였다.
짝수를 하나 입력받고 for문, while문을 통해 1부터 해당하는 수까지의 모든 짝수를 출력하는 프로그램이다.
#include <stdio.h>
int main(){
int n, i=0;
printf("Print all even number till: ");
scanf("%d", &n); // inputs number
printf("All even numbers from 1 to %d are:\n", n);
i=1;
while(i <= n){
if(i % 2 == 0)
printf("%d\n", i); // print if counter's remain of 2 is same with 2(even num)
i++; // ascending i
}
return 0;
}
#include <stdio.h>
int main(){
int n, i=0;
printf("Print all even number till: ");
scanf("%d", &n); // inputs number
printf("All even numbers from 1 to %d are:\n", n);
for(i=1; i<(n+1); i++){ // from 1 to n
if(i%2 == 0)
printf("%d\n", i); // print if counter is even number
}
return 0;
}
처음 수를 0으로 할 경우 0이 출력될 수 있기 때문에 i를 1로 설정해야 하는 점을 주의해야 한다.
상한선을 입력받고 그 수까지의 모든 짝수의 합을 구하는 프로그램이다.
int형 정수 s = 0으로 초기화 한 후 for문 안에 if문을 넣어 덧셈을 진행함으로써 해결 가능하다.
#include <stdio.h>
int main(){
int n, i = 0;
int sum = 0;
printf("Enter upper limit: ");
scanf("%d", &n); // Input a number
for(i=1; i<(n+1); i++){
if(i % 2 == 0) // if counter is even number, it is summed to variable sum
sum += i;
}
// print result
printf("Sum of all even number between 1 to %d = %d", n, sum);
return 0;
}