소개
이 랩에서는 사용자로부터 'n'개의 정수를 입력받아 그 합을 출력하는 C++ 프로그램을 작성하는 방법을 배웁니다.
n 개의 숫자의 합을 구하는 코드 작성
WebIDE 에서 메뉴 바에서 Terminal > New Terminal 을 선택하여 새 터미널을 엽니다. 터미널에서 아래 명령을 입력하여 main.cpp라는 새 파일을 생성합니다.
touch ~/project/main.cpp
이제 main.cpp 파일을 열고 다음 코드를 붙여넣습니다.
#include <iostream>
using namespace std;
int main()
{
cout << "\n\nWelcome to the program to find the Sum of n numbers entered by the user :-)\n\n\n";
// Variable declaration
int n, i, temp;
// Initializing sum to zero
int sum = 0;
// Taking 'n' as input from the user
cout << "Enter the number of integers you want to add : ";
cin >> n;
cout << "\n\n";
// Taking n integers as input from user and adding them to find the final sum
for (i = 0; i < n; i++)
{
cout << "Enter number " << i + 1 << " : ";
cin >> temp;
// Add each number to the sum of all the previous numbers to find the final sum
sum += temp;
}
// Output the sum
cout << "\n\nSum of the " << n << " numbers entered by the user is : " << sum << endl;
cout << "\n\n\n";
return 0;
}
코드 컴파일 및 실행
터미널에 다음 명령을 입력하여 코드를 컴파일합니다.
g++ ~/project/main.cpp -o main
그런 다음 실행 파일을 실행하려면 다음 명령을 입력합니다.
./main
다음과 유사한 출력을 볼 수 있습니다.
Welcome to the program to find the Sum of n numbers entered by the user :-)
Enter the number of integers you want to add : 4
Enter number 1 : 2
Enter number 2 : 3
Enter number 3 : 5
Enter number 4 : 10
Sum of the 4 numbers entered by the user is : 20
요약
이 랩에서는 사용자로부터 'n'개의 정수를 입력받아 그 합을 출력하는 C++ 프로그램을 작성하는 방법을 배웠습니다. 랩을 성공적으로 완료했습니다. 축하합니다!



