39.6k views
5 votes
Write code for a function that uses a loop to compute the sum of all integers from 1 to n. Do a time analysis, counting each basic operation (such as assignment and ++) as one operation.

User Excellor
by
3.5k points

1 Answer

5 votes

Answer:

#include<bits/stdc++.h>

using namespace std;

int sumOfinteger(int );

// Returns sum of all digits in numbers from 1 to n

int sumOfintegersFrom1ToN(int n) {

int result = 0; // initialize result

// One by one compute sum of digits in every number from

// 1 to n

for (int x = 1; x <= n; x++)

result += sumOfinteger(x);

return result;

}

// A utility function to compute sum of digits in a

// given number x

int sumOfinteger(int x) {

int sum = 0;

while (x != 0) {

sum += x %10;

x = x /10; }

return sum; }

// Driver Program

int main() {

int n ;

cout<<"enter a number between 1 and n : ";

cin>>n;

cout << "Sum of digits in numbers from 1 to " << n << " is " << sumOfDigitsFrom1ToN(n);

return 0; }

User Marty Wallace
by
3.5k points