WSQ07 ‘Sum of Numbers’

Ever wondered what is the result of the addition of all the intergers from a certain range? Of course not, but let’s calculate it!

okami doge
Sorry, been playing Okami lately. 

What I mean by ‘Sum of Numbers’, it is for example: from a range of 5 to 10 one has to sum 5 + 6+ 7 + 8 + 9 + 10. This has to be done in order to get the final result of 45.  Sounds easy right? But what if the range was bigger? For example from 1 to 100. One is not going to grab a calculator and start “1+2+3+4+5+6+7+8+9+(…)+100”. Of course not! This is why I was in charge of programming a code were the computer automatically does this.

 

 

I will be using the classic variables “x” and “y” to define the range. This time “x” is the number we begin, and “y” is the number the addition countdown stops. However, I had to make a prediction were the user actually submits “x” higher than “y”. This would me impossible since the program is unable to count backwards. So I used a conditional “If” to let the user know what the mistake is. In the end, this is my code.

WSQ07 code

Looks cool right? It looks better when one uses it.

wsq07run

This blog corresponds to the song “After Midnight” by Blin182. I am not that old, yet I know that band brings nostalgia to most of the 90’s kids. This song was recommended by an old friend of mine, and I have must say thanks to her for introducing me this awesome song.

After Midnight

 

Suma de números#WSQ007

En este ejercicio te pide que hagas la suma del rango que te solicite el usuario, te dará dos números, y el programa deberá hacer la suma desde el número más pequeño al más grande.

Para mí la manera más fácil fue hacerlo con un acumulador y un for.

Primero le solicito al usuario los dos números, serán variables x & para mí. Esos datos que reciba los tengo que convertir en número entero.

for a in range (x,(y+1)):

El for, es un Para “a” en el rango de x & y hará lo que le diga.
a= cada número entre ese rango. En este caso le tengo que aumentar +1″ a porque ese número ya no lo abarcará, por ejemplo si me da los números 2 y 6, mostrará hasta el número 5, la suma será la misma, pero como yo quiero ver en pantalla los números que se sumaron por eso le aumento el 1.

Lo demás serán puros detalles, imprimir un “+” entre cada número, el “=end” para imprimirlo en una sola linea,  y finalmente imprimir un “=” cuando a sea igual a y

El resultado será “acum”, tiene que valer cero al principio y cada vuelta tomará un nuevo valor, el cual será el de: él mismo + a.

Y  correrlo.

for

CÓDIGO

acum=0

for a in range (11):
if a!=10:
print(a,end=”+”)
else:
print(a, end=”=”)
acum+=a

print (acum)

 

Sum of numbers

The next task we were asked to perform was a program capable of adding the numbers inside a user specified range. The user provides the first value of the range and the last value of the range. We were asked to preferably use loops to solve this task.

This program was a bigger challenge for me. It helped me to really understand the way a counter works. It is kind of strange and hard to undestand how a variable is initializaed under the value of another one, and then inside the loop you initialize it to the value of itself plus one.

First I thought I had to use a for loop to run this program. But it was getting to hard for me and I could not do it. My fellow classmate and friend Alberto Rodriguez gave me a general idea of how it should work, using a do while loop.

So how this basically works is that the sum varable is initialized to the value of the first number of the range, before the for loop starts working. Inside the for loop, you intialize the sum funtcion again to the value of itself (which is now the value of the first number of the range) plus one. Then you make the actual operation, which is to add the value of the first number of the range plus the variable sum.

The program will keep on doing the operation while the value of sum is less than the last value of the range.

#include <iostream>

using namespace std;

int x, y, sum;

int main (){

cout << “Provide the first number of the range: ” << endl;
cin >> x;

cout << “Provide the last number of the range: ” << endl;
cin >> y;

sum = x;

do{

Continue reading “Sum of numbers”

Sum of numbers

Hello,

Welcome back!

This time I will show you a great code using LOOP. In the last WSQ I explained what is a loop and now we are goint to use it again.

Instructions:

Write a program that asks for a range of integers and then prints the sum of the numbers in that range (inclusive).

You can use a formula to calculate this of course but what we want you to do here is practice using a loop to do repetitive work.

And here’s the code:

2016-02-06

The same as the last one but in this code we are introducing a new tool what I call “counter” and “accumulator”. But, what is the function of each one?

Counter: we can use it by our benefit abd it depends in what kind code we are trying to make. Most of cases it helps us to count how many times the cycle is repeated and to use it in the condition.

Accumulator: it is not difficult to think what an accumulator is. This variable accumulate all the values that are generated by the cycle. Most of the time the value changes.

As you can see I defined the counter as “num”. Remember to declare the value of the counter as cero and add “+ 1” and with every cycle the counter is goin to plus one round.

It is not difficult just need to practice and think logically.

Code’s link: here

I remember how to do it because I used in my last course and to see if it is the same I visit this web and be sure.

See you in my next post!

Top image by: https://www.flickr.com/photos/joeyz51/9323915464/sizes/l/

Sum of numbers WSQ07

For this one I actually get a lot of trouble to find out how to make it, because I already know the functions of if and do/while. But for some type of reason I didn’t manage to get it done right. So I ask some of my student partners to if they can explain me how this is suppose to be done. At the end I finally get it right.

Another problem that I faced was the one that it was presented that the sum starter with 0, but I actually need to started in 1 to get it as the example that the teacher give us, that was 1 as the lower and 10 as the upper, and getting 55 as result, but when I started the sum in 0, the program actually give me as result 54, so I change it to 1 so this number was the correct one.

Here are the pictures:

Click to view slideshow.

Here is the code in GitHub:

https://gist.github.com/batmantec/bcec98aea205edcb679c

For NARNIA!

Hoy estuve de melosa con mi novio (el cual va en sistemas) y surgió la conversación de patos…

Y pregunté ¿Oye, cómo le haría para imprimir 42 patos?

Así que me dijo “sepa, ya pon la película de Shrek”

pero.. .me puse a investigar sobre los For (: (mi novio es Arturo Fornés Arvayo, va en su clase de POO – Saludos, Ken 🙂 )

Y pues, a repasar los condicionales :3 <3 porque amo la programación y todas esas madres del nintendo.

Y así fue como imprimí 42 patos :DDD

ashamed

(luego le agrego más teoría del for, solo que ARTURO (A01227071) TC201 me está apurando :/, una que le quiere echar ganas al blog)

CÓDIGO

print(“Esto va por ti Arturo :*”)

for i in range (43):
if i==0:
print(i,” te quiero “)
elif i==1:
print(i, “pato”)
else:
print(i, “patos”)

 

 

Sum of Numbers

En esta practica lo que hice fue crear un código en el cual le pida al usuario dos números con los cuales se vaya sumando, el primero que fuera el número con el que iniciara la sumatoria y el segundo el último (hasta el cual se sumara el primer número).

Sum_Of_Numbers

Lo que necesitamos para la realización de este código es un loop para que se vaya sumando automáticamente hasta llegar al numero que sera el último a sumar y así mismo dentro de éste debemos insertar un contador que se vaya sumando de uno en uno hasta llegar al ultimo número y así mismo que se vaya sumando al numero principal y se vaya guardando la sumatoria.

El código que yo realice se encuentra en la siguiente liga de Dropbox, así como los demás que he realizado durante mi proceso de este curso.

https://www.dropbox.com/home/C%2B%2B%20TC101