📌  相关文章
📜  国际空间研究组织 | ISRO CS 2008 |问题 19(1)

📅  最后修改于: 2023-12-03 15:23:02.527000             🧑  作者: Mango

ISRO CS 2008 Question 19

This is a question from the ISRO CS 2008 exam, which tests a programmer's knowledge of C programming language.

Problem Description

The problem asks the programmer to write a C program that takes a number (n) as input and prints out the result of the following series:

1 + (1 + 2) + (1 + 2 + 3) + ... + (1 + 2 + ... + n)
Example

For example, if n = 3, the program should output:

1
4
10
Solution

We can solve this problem by using a loop to iterate through all of the numbers from 1 to n. We will keep track of the sum of the first i numbers (i.e. 1 + 2 + ... + i) using a variable called current_sum.

At the end of each iteration, we add the current sum to the total sum and print it out. Here is the C code to implement this algorithm using a for loop:

#include<stdio.h>

int main()
{
    int n, i, current_sum, total_sum;
    total_sum = 0; // initialize total_sum to zero

    printf("Enter a number: ");
    scanf("%d", &n);

    for(i=1; i<=n; i++)
    {
        // calculate the sum of the first i numbers
        current_sum = (i*(i+1))/2;

        // add current sum to the total sum
        total_sum += current_sum;

        // print the total sum
        printf("%d\n", total_sum);
    }

    return 0;
}
Explanation

In this code, we first declare the necessary variables: n for the input number, i for the loop counter, current_sum for the sum of the first i numbers, and total_sum for the total sum so far.

We then use the scanf() function to read in the input number n.

Next, we use a for loop to iterate from i=1 to i=n. Inside the loop, we use the formula (i*(i+1))/2 to calculate the sum of the first i numbers, which is equal to 1 + 2 + ... + i.

We add the current sum to the total sum using the += operator, and then print out the total sum using the printf() function.

Finally, the program returns 0 to indicate that it has executed successfully.

Conclusion

In conclusion, this C program solves the ISRO CS 2008 Question 19 by taking a number as input and printing out the sum of the series 1 + (1 + 2) + (1 + 2 + 3) + ... + (1 + 2 + ... + n) up to the given number. The program uses a for loop and the formula for the sum of the first n natural numbers to accomplish this task.