How can I solve this exercise? C ++ Cycle for

0

Start programming with for cycle, would you help me try to solve this exercise? Thanks ... Create a program that allows you to enter an entire number from 1 to 12 and show me the multiplication table of that number.

#include<stdio.h>
#include<stdlib.h>
#include<conio.h>

int main () {

    int n,contador=0,multiplicacion=0;

    printf("Ingrese un numero: ");

    scanf("%d",&n);

    if(n>0 && n<=12)

    for(contador=0;contador<=10;contador++){

    multiplicacion=multiplicacion*n;

    contador++;
    }

    printf("la tabla de multiplicar es: %d ",multiplicacion);
}
    
asked by Gustavo Torres 27.06.2017 в 22:30
source

1 answer

0

You want me to show you the table ... however you are not saving the temporary data:

for(contador=0;contador<=10;contador++){
  multiplicacion=multiplicacion*n; // <<---
  contador++;
}

The commented line crushes the value stored in multiplicacion in each iteration.

If your idea is to show each result you have to print the result in each iteration

for(int contador=0;contador<=10;contador++){
  int multiplicacion=contador*n;
  std::cout << multiplicacion << '\n'; // Estamos en C++
  contador++;
}

If we try the code we see that it does strange things (if for example we try to print the table of the 1 ...

0
2
4
6
8
10

What is happening? Well, look at the last line of for :

for(int contador=0;contador<=10;contador++){
  int multiplicacion=contador*n;
  std::cout << multiplicacion << '\n';
  contador++; // <<---
}

You are incrementing the counter twice in each iteration: in the declaration of for and in that last line. The solution is as simple as eliminating that second increase:

for(int contador=0;contador<=10;contador++){
  int multiplicacion=contador*n;
  std::cout << multiplicacion << '\n';
}

By the way, cout is in the library iostream . The example with more C ++ code than C would look like this:

#include <iostream>

int main ()
{
  int n;

  std::cout << "Ingrese un numero: ";
  std::cin >> n;

  std::cout << "la tabla de multiplicar es: \n";
  if(n>0 && n<=12)
  {
    for(int contador=0;contador<=10;contador++){
      int multiplicacion=contador*n;
      std::cout << n << 'x' << contador << '=' << multiplicacion << '\n';
    }
  }
}
    
answered by 27.06.2017 / 22:43
source