Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

calculate and display the sum of first n positive integers where n is a number entered by the user from the key board

–1 vote
asked Mar 30, 2020 by Sanju Sana (120 points)

5 Answers

–2 votes
answered Mar 31, 2020 by sunny (140 points)

To calculate and display you can use loop. 

for e.g.
int n,sum = 0,c,value;
  printf("How many numbers you want to add?\n");
  scanf("%d", &n);
  printf("Enter %d integers\n", n);
  for (= 1; c <= n; c++)
  {
    scanf("%d", &value);
    sum = sum + value;
  }

commented Apr 18, 2020 by Daksh Prajapati (100 points)
if you are begginer than it is a good program.
0 votes
answered Apr 5, 2020 by Manav Changela (190 points)
I used a simple formula from Arithmetic  Progression

#include<stdio.h>

void main()

 {

  int n,sum;
  printf("ENTER VALUE OF n:");
  scanf("%d",&n);
  sum=0.5*n*(1+n);
  printf("\n sum=%d",sum);
  
}
0 votes
answered Apr 5, 2020 by Prabhat Nayak (220 points)
// for calculate sum of all positive integers upto n

#include<stdio.h>

void main()

 {

  int n,sum,i;

sum=o;

if(n<0)

 {

 printf("enteres number is  a negative number");

}

else if(n=0)

{

printf("sum is 0");

}

else

{

for(i=0;i<=n;i++)

 {

  sum=sum+i;

}

}

printf("sum of all integer upto %d is %d",n,sum);

}
0 votes
answered Apr 6, 2020 by bhoomi2000 (780 points)
0 votes
answered Apr 8, 2020 by Jag Man Gurung (220 points)
Here is a simple program to calculate the sum using recursion. And I have used a do while loop to check whether the user inputed number is positive or not.

#include <iostream>

int sum(int number)
{
    if(number > 0)
    {
        return number + sum(number - 1);
    }
}

int main()
{
    int n{0};
    do{
        std::cout << "Enter the number: ";
        std::cin >> n;
    }while(n <= 0);
    std::cout << sum(n);
    return 0;
}
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...