c# – Read by CSharp console

Question:

I am starting in the world of programming and I have just solved the following exercise.

Ingresar un número y mostrar la suma de los números que lo anteceden.
Al ingresar el 5 me da como resultado el 10

.

As I do so that by console when entering for example 5 , it shows me 1+2+3+4 = 10 , I leave the code that I make.

int num, suma = 0;

Console.Write("Ingresa un número:");
num = Convert.ToInt32(Console.ReadLine());

for (int i = 0; i < num; i++)

   suma = suma + i;

   Console.Write("La suma de los números que anteceden a el número: " + num + " es " + suma + ".");
   Console.ReadKey();

Answer:

You can do with a for loop, concatenating the value that the loop carries in each turn, the program would be as follows:

        Console.Write("Ingresa un número: ");
        int num = Convert.ToInt32(Console.ReadLine());
        int suma = 1;

        Console.Write("La suma de los números anteriores a " + num + " es: 1");
        for (int i = 2; i < num; i++)
        {
            suma += i; //Para poder mostrar los números desde el uno, ya que i en un inicio va a valer 0
            Console.Write(" + " + i);
        }
        Console.Write(" = " + suma);

        Console.ReadKey();

The suma variable is initialized to 1 for the following reasons:

1) We already know that before any number there will always be the number one, so it is worth putting it in the for loop later.

2) In order to concatenate the "+" signs in each turn, they have to be written at the beginning of each Console.Write() within the for loop, so it is necessary to have a number already written beforehand. Let me explain: Before starting the for loop, write the phrase "The sum of the numbers before" + num + "is: 1" since, having that one there, we can concatenate, within the for, at the beginning of each write a plus sign, since we know that before there will always be a number. This helps us so that, at the end of the for loop turns, a plus sign does not appear. If we leave the plus sign at the end of writing the for loop, it would look like this (in the case that num = 5): 1 + 2 + 3 + 4 + = 10

I hope it helps you, any questions we are here to serve.

Scroll to Top