Problem 42

author
By Supreme2023-03-15
Problem Statement :
Write a program that defines a function to add first n numbers
Code:

#include <stdio.h>

int sum(int n);

int main() {

//42. Write a program that defines a function to add first n numbers.

printf("\t\tSum Of N Numbers");
printf("\n================================================\n\n");

int n;

printf("Enter The Value Of N : ");
scanf("%d",&n);

int result = sum(n);

printf("\n------------------------------------------------\n\n");
printf("The sum of the first %d numbers is: %d\n", n, result);
printf("\n------------------------------------------------\n\n");
return 0;
}

int sum(int n) {
int sum = 0,i;
for (i = 1; i <= n; i++) {
sum += i;
}
return sum;
}

Description :
  • This program defines a function sum that calculates the sum of the first n numbers. It then uses this function to calculate the sum of the first n numbers entered by the user.
  • The program starts by including the standard input/output library header stdio.h.
  • The program defines a function sum that takes an integer argument n and returns an integer result.
  • Inside the sum function, a local integer variable sum is declared and initialized to zero.
  • A for loop is used to iterate from 1 to n, adding each number to the sum variable.
  • After the loop, the sum variable is returned.
  • The program defines the main function.
  • Inside the main function, an integer variable n is declared to hold the number of terms to sum.
  • The user is prompted to enter the value of n.
  • The sum function is called with the value of n as an argument, and the result is stored in the result variable.
  • The program prints out the sum of the first n numbers using the printf function.
Output Image:
Output-image

© Copyright 2022. All right reserved, GTU Coder.