Search code examples
c++productdraw

multiplication of random numbers different from zero


I have a code that generates 10 random numbers and I need to calculate the sum and product of the non-zero numbers and display which numbers have been multiplied. I already have most of the code but I have no idea how to multiply numbers that are nonzero and then display them. Can someone help me?

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <windows.h>

using namespace std;

int main()
{
    cout << "draws 10 numbers:" << endl;
    Sleep(1000);
    cout << endl;

    srand(time(0));
    int sum=0;
    int product=1;

    for(int i=0, value=0; i<10; i++, sum+=value, product*=value) 
    {
        value = rand()%10+0;
        Sleep(1000);
        cout << value << endl;
    }

    Sleep(1000);
    cout << "the sum is " << sum <<endl;
    cout << "the product is " << product <<endl;
    return 0;
  }

Solution

  • To start, it is easier to read and understand if we move the addition and multiplication out of the for loop header.

    int sum = 0;
    int value = 1;
    
    for(int i = 0; i < 10; i++) 
    {
      int value = rand() % 10;
      sum += value;
      product *= value;
      std::cout << value << std::::endl;
    }
    

    Next, we only want to do the multiplication if the value is not equal 0.

    int sum = 0;
    int value = 1;
    
    for(int i = 0; i < 10; i++) 
    {
      int value = rand() % 10;
      sum += value;
    
      if(value != 0)
      {
        product *= value;
      }
    
      std::cout << value << std::::endl;
    }
    

    So the whole program looks like this.

    #include <iostream>
    #include <cstdlib>
    #include <ctime>
    
    int main()
    {
      std::cout << "draws 10 numbers:" << std::endl;
    
      srand(time(0));
      int sum = 0;
      int product = 1;
      int multiplied = 0;
    
      for(int i = 0; i < 10; i++)
      {
        int value = rand() % 10;
        sum += value;
    
        if(value != 0)
        {
          product *= value;
          multiplied += 1;
        }
    
        std::cout << value << " ";
      }
    
      std::cout << std::endl;
      std::cout << "the sum is " << sum << std::endl;
      std::cout << "the product is " << product << std::endl;
      std::cout << "numbers multiplied is " << multiplied << std::endl;
      return EXIT_SUCCESS;
    }