I want help in some basic problems of c++

the problem is to find the sum of n integers input by the user
I donot know how to iterate the number in that n integer
help me in this question

use the for loop
include

int main() {
int n;
std::cin >> n;
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
std::cout << sum << std::endl;
return 0;
}

thanks alot for the earlier help
can you help me in solving (sum of digits) question.
difficulty of 455.

yes sure but actually write code in c and python i hope this works for you

type or paste code here
#include <iostream>
using namespace std;

int main() {
    int num, sum = 0;
    cout << "Enter a number: ";
    cin >> num;
    while (num!= 0) {
        sum += num % 10;
        num /= 10;
    }
    cout << "Sum of digits: " << sum << endl;
    return 0;
}
1 Like

thanks.

1 Like

no problem if you find this helpful do like my message.

2 Likes

To sum N numbers input by a user, you have these two options:

#include <bits/stdc++.h>
using namespace std;

int main(){
    long long total_sum = 0;
    long long N, auxiliar;

    cin >> N;
    for (long long i=0; i<N; i++){
        cin >> auxiliar;
        total_sum += auxiliar;
    }

    // ... rest of the code
}

Another fancy (slower and requires more memory, yet useful in some cases) option is:

#include <bits/stdc++.h>
using namespace std;

int main(){
    long long N;

    cin >> N;
    vector<long long> nums(N);
    for (long long i=0; i<N; i++){
        cin >> nums[i];
    }

    long long total_sum = accumulate(nums.begin(), nums.end(), (long long)0);

    // ... rest of the code
}

Now, if what you want is the sum of the first N integers, don’t loop, just use a formula.

#include <bits/stdc++.h>
using namespace std;

int main(){
    long long N;

    cin >> N;

    long long sum_first_N_integers = N * (N+1) / 2;

    // ... rest of the code
}
2 Likes