Adding n numbers:

Without using an array

We add the numbers as and when the user enters them. For this logic, we will need a while or a for loop.

The code for adding n numbers using for loop is:

#include <stdio.h>

int  main()

{

   int  count;

   int  num;

   int  sum = 0;

   int  i = 1;

   printf("Enter the number of numbers you wish to add: ");

   scanf("%d", & amp; count);

   for  (i = 1; i & lt; = count; i++)

   {

      printf("Enter the number: ");

      scanf("%d", & amp; num);

      sum = sum + num;

   }

   printf("Sum: %d\n", sum);

   return  0;

}

The input and output for the above code is:

Enter the number of numbers you wish to add:  2

Enter the number:  2

Enter the number:  2

Sum: 4

  • We have created the variable count to store the number of numbers that the user wants to add.
  • We have created the variable sum to store the sum of the numbers.
  • We have created the variable i as a counter variable.
  • We have created the variable num to store the number entered by the user in each iteration.
  • In each iteration of the for loop, we are simply adding the number entered by the user.
  • At the end of the for loop we get our total sum.

Using an array

We can store the user input in an array and add the value present at each location in the array.

The code for adding n numbers using an array is:

 
#include <stdio.h>

int  main()

{

   int  count;

   int  sum = 0;

   int  i = 1;

   printf("Enter the number of numbers you wish to add: ");

   scanf("%d", & amp; count);

   int  arr[count];

   for  (i = 1; i & lt; = count; i++) // for loop for storing user input in the array

   {

      printf("Enter a number: ");

      scanf("%d", & amp; arr[i]);

   }

   for  (i = 1; i & lt; = count; i++) //for loop for calculating the sum

   {

      sum = sum + arr[i];

   }

   printf("Sum: %d\n", sum);

   return  0;

}

The output for the above code is:

 
Enter the number of numbers you wish to add:  4

Enter a number:  1

Enter a number:  2

Enter a number:  3

Enter a number:  4

Sum: 10
  • We have created the variable count to store the number of numbers that the user wants to add.
  • We have created the variable sum to store the sum of the numbers.
  • We have created the variable i as a counter variable.
  • We have created the array arr to store the numbers entered by the user.
  • In each iteration of the for loop, we are simply adding the number present at each index in the array.
  • At the end of the for loop we get our total sum.

Report Error/ Suggestion

Related Posts:

[yuzo_views]











CopyRight © 2019

CopyRight © 2019