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 the 5
, it shows me , I 1+2+3+4 = 10
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();
You can do with a for cycle, concatenating in each return the value that the cycle carries, the program would be as follows:
The variable
suma
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 unnecessary to put it in the for loop later on.
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 before. Let me explain: Before starting the for cycle, write the sentence "The sum of the numbers before " + num + " is: 1" since, by having that one there, we can concatenate, within the for, at the beginning of each writing a plus sign, since we know that before there will always be a number. This helps us so that, at the end of the loops of the for loop, a plus sign does not appear. If we leave the plus sign at the end of the for loop script, it would look like this (if num = 5):1 + 2 + 3 + 4 + = 10
I hope it works for you, any questions we are here to serve.
Try storing all the values in a variable with its symbol and at the end you print it as you wish... like this:
I hope it works for you and you mark it, ReNiceCode...
Hi, change your code to this: