C#/C#200제

[C#] 7일차 - 43. 반복문(1에서100까지 더하기, 홀수의합, 역수의합)

반나무 2021. 1. 22. 13:16

"Hello World"라는 문장을 10번 출력하는 프로그램을 3가지 방법으로 작성

 

while

int i = 0; // 초기값
while(i < 10) //반복하는 조건
{
	Console.WriteLine("{0} : Hello world",i);
    i++; //반복할 때마다 변하는 값
}

do while

int i = 0; // 초기값
do
{
	Console.WriteLine("{0} : Hello World", i);
    i++; // 반복할 때마다 변하는 값
} while (i < 10); // 반복하는 조건

for

for(int i=0; i<10; i++)
{
	Console.WriteLine("{0} : Hello world",i);
}

 

(1) 1부터 100까지 더하는 프로그램

(2) 1부터 100까지의 홀수를 더하는 프로그램

(3) 역수의 합을 구하는 프로그램

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace A043_Loop
{
    class Program
    {
        static void Main(string[] args)
        {
            // (1) 1 부터 100까지 더하는 프로그램
            int sum = 0;
            for(int i=1; i<=100; i++)
            {
                sum += i;
            }
            Console.WriteLine("1부터 100까지 더하면 : {0}", sum);

            // (2) 1부터 100까지 홀수의 합 을 구하는 프로그램
            int sum2 = 0;
            for(int x=1; x<=100; x++)
            {
                if (x % 2 == 1)
                    sum2 += x;
            }
            Console.WriteLine("1부터 100까지 홀수의 합을 구하면 : {0}", sum2);

            // (3) 역수의 합을 구하는 프로그램
            double sum3 = 0;
            for(int x=1; x<=100; x++)
            {
                sum3 += 1.0/x;
            }
            Console.WriteLine("1부터 100까지 역수의 합을 구하면 : {0}", sum3);

        }
    }
}

반응형