gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
provide me a c++ code that finds the sum of the first n numbers
- User
provide me a c++ code that finds the sum of the first n numbers
- Assistant
Certainly! Here's a C++ code that calculates the sum of the first n numbers:
#include <iostream> int main() { int n; int sum = 0; std::cout << "Enter the value of n: "; std::cin >> n; // Calculating the sum of the first n numbers for (int i = 1; i <= n; i++) { sum += i; } std::cout << "The sum of the first " << n << " numbers is " << sum << std::endl; return 0; }In this code, the user is prompted to enter the value of n. The code then calculates the sum of the numbers from 1 to n using a for loop and stores the sum in the variable "sum". Finally, it displays the sum on the console.