multiplication of random numbers different from zero - c++

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;
}

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;
}

Related

How to find Maximum number and negative numbers from a .txt file and also how to output Total result to another .txt file

I want to find Maximum numbers from my "numbers.txt" file and amount of negative numbers. And i want to output the Total result to another .txt file and console and the rest to the console only.
Im very new and just cant figure out how to do it.
This is what i have now
a "numbers.txt" file with
-4
53
-5
-3
2
and
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int n = 0;
int sum = 0, total = 0;
fstream file("numbers.txt");
while (file >> n)
{
sum += n;
total++;
}
int average = (float)sum / total;
int AmountOfNumbersAdded = total;
int Highest;
int Negative;
cout << "Total result: " << sum << endl;
cout << "Numbers added: " << AmountOfNumbersAdded << endl;
cout << "Average number: " << average << endl;
cout << "Maxiumum number: " << endl;
cout << "Negative numbers: " << endl;
return 0;
}
i tried to do
float Highest = INT_MIN;
if (Highest < num[i]) {
Highest = num[i];
but it just wouldn't work.
You don't need to store the numbers to find the maximum or the amount of negative numbers, but you need to track them inside the loop, like you're already doing with the sum and the total amount of numbers.
int Highest = INT_MIN;
int Negative = 0;
while (file >> n)
{
sum += n;
total += 1;
if (n < 0)
{
Negative += 1;
}
if (n > Highest)
{
Highest = n;
}
}
float average = (float)sum / total;
Here's what you're looking for.
#include <iostream>
#include <fstream>
int main()
{
int n = 0;
int sum = 0, total = 0;
int highest = 0;
int negatives = 0;
std::fstream file("numbers.txt");
while (file >> n)
{
if (n > highest) highest = n;
if (n < 0) ++negatives;
sum += n;
++total;
}
int average = (float)sum / total;
int AmountOfNumbersAdded = total;
std::cout << "Total result: " << sum << "\n";
std::cout << "Numbers added: " << AmountOfNumbersAdded << "\n";
std::cout << "Average number: " << average << "\n";
std::cout << "Maxiumum number: " << highest << "\n";
std::cout << "Negative numbers: " << negatives << "\n";
file.close();
return 0;
}
As you're new, few advices for you:
Never use using namespace std.
Prefer using "\n" instead of std::endl.
Don't forget to close any files/database after opening them like you did in your code.
Always try to avoid macros.

How to display whole numbers without decimals

I created a program to display an average from an array of numbers the user have decided to input. The program asks the user the amount of numbers he / she will input, then they input all positive numbers. The output for the average is always a decimal, how can I only display the whole number without any decimal points. Ex. 12.34 = 12 / 8.98 = 8
#include <iostream>
#include <iomanip>
using namespace std;
void sortingTheScores(double *, int);
void showsTheScoresNumber(double *, int);
double averageForAllScores(double, int);
int main()
{
double *scores;
double total = 0.0;
double average;
int numberOfTestScores;
cout << "How many test scores do you have? ";
cin >> numberOfTestScores;
scores = new double[numberOfTestScores];
if (scores == NULL)
return 0;
for (int count = 0; count < numberOfTestScores; )
{
cout << "Test Score #" << (count + 1) << ": ";
cin >> scores[count];
while (scores[count] <= 0)
{
cout << "Value must be one or greater: " ;
cin >> scores[count];
}
count = count +1;
}
for (int count = 0; count < numberOfTestScores; count++)
{
total += scores[count];
}
sortingTheScores(scores, numberOfTestScores);
cout << "The numbers in set are: \n";
showsTheScoresNumber(scores, numberOfTestScores);
averageForAllScores(total, numberOfTestScores);
cout << fixed << showpoint << setprecision(2);
cout << "Average Score: " << averageForAllScores(total,numberOfTestScores);
return 0;
}
void sortingTheScores (double *array, int size)
{
int sorting;
int theIndex;
double theNumbers;
for (sorting = 0; sorting < (size - 1); sorting++)
{
theIndex = sorting;
theNumbers = array[sorting];
for (int index = sorting + 1; index < size; index++)
{
if (array[index] < theNumbers)
{
theNumbers = array[index];
theIndex = index;
}
}
array[theIndex] = array[sorting];
array[sorting] = theNumbers;
}
}
void showsTheScoresNumber (double *array, int size)
{
for (int count = 0; count < size; count++)
cout << array[count] << " ";
cout << endl;
}
double averageForAllScores(double total, int numberOfTestScores)
{ double average;
average = total / numberOfTestScores;
return average;
}
You can use I/O manipulators here:
#include <iostream>
#include <iomanip>
int main()
{
std::cout << std::setprecision(0) << 1.231321 << '\n';
}
Output:
1
You can do it without using iomanip library:
std::cout.precision(0);
std::cout << 1.231321 << std::endl;
Then you'll simply get:
1
Just you need to use std::cout.precision() which is equivalent to std::setprecision() from iomanip library.
Edit:
The aforementioned solution is okay for smaller floating point values, but if you try something like 1334.231321, the std::cout will result displaying some scientific notation, something like:
1e+03
which is actually odd to read and understand. To solve it, you need std::fixed flag, you may write something like:
std::cout.precision(0), std::cout << std::fixed;
std::cout << 1334.231321 << std::endl;
Then it'll show:
1334
For numbers in a +/-2^31 range you can do:
cout << int(12.34) << " " << int(8.98) << endl;
which produces output
12 8
You may also want to consider rounding to the nearest integers. To do so
add a line
#include <cmath>
then do
cout << int(rint(12.34)) << " " << int(rint(8.98)) << endl;
this gives
12 9

error expected primary-expression before ';'token c++

am new in coding and am using c++ to create a program to find sum median maximum and minimum but i get the error expected primary-expression before ';' token in every place that has cout
#include <iostream>
using namespace std;
int main()
{
int array[10],maximum,minimum,sum=0,median;
cout<<"input ten integers,"<<;
for(int i=0; i<10; i++){
cin>> array[i];
sum=sum+array[i];
}
for(int i=0; i<10; i++){
if(maximum>array[i])
{
maximum=array[i];
}
else if( minimum<array[i])
{
maximum= array[i];
}
}
median=(array[4]+array[5])/2;
cout<<"maximum value is"<<maximum<<;
cout<<"minimum value is"<<minimum<<;
cout<<"sum is"<<sum<<;
cout<<"median is"<median<<;
Remove the << before the ; on every line that has it or replace <<; with <<'\n'; for a new line.
#include <iostream>
using namespace std;
int main()
{
int array[10], maximum = 0, minimum = 0, sum = 0, median = 0;
cout << "input ten integers: ";
for (int i = 0; i < 10; i++) {
cin >> array[i];
sum = sum + array[i];
}
for (int i = 0; i < 10; i++) {
if (maximum > array[i])
{
maximum = array[i];
}
else if (minimum < array[i])
{
maximum = array[i];
}
}
median = (array[4] + array[5]) / 2;
cout << "maximum value is " << maximum << '\n';
cout << "minimum value is " << minimum << '\n';
cout << "sum is " << sum << '\n';
cout << "median is " << median << '\n';
return 0;
}
Use the below dummy code to fix this issue for the new line:
dummy code
#include <iostream>
int main() {
int a = 5;
int b = 10;
std::cout << (a < b) << std::endl; // 1
std::cout << (a > b) << std::endl; // 0
return 0;
}
output
1
0

using functions to write the code in C++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Hi i'm trying to Write a program in C++ to, generate and print 20 random numbers, between 0 to 999, and do the following operations without using inbuilt functions, find and print the: min value, max value, average, median, standard deviation, variance. Do a binary search on the 15th element. Please help me with the code.
So far i've done this much
#include
#include
#include
using namespace std;
void minimum(int[], int);
void maximum (int[], int);
void average(int[], int);
void median(int[], int);
void mean(int[], int);
void sort(int[], int);
int ra()
{
int r = rand() % 1000;
return r;
}
int main ()
{
srand(time(NULL));
ra();
int array[20];
int num=20;
for (unsigned int i = 0; i < num; i++)
{
array[i] = ra();
cout << "Index: " << i << ", random number: " << array[i] << endl;
}
minimum();
new_array[20];
num=20;
for (unsigned int i = 0; i < num; i++)
{
new_array[i] = new_array();
cout << "Index: " << i << ", random number: " << minimum << endl;
}
return 0;
}
void minimum(int new_array[], int num)
{
for (unsigned int i = 0; i < num; i++)
if (new_array[i] minimum)
minimum = new_array[i];
cout << "Maximum value: " << minimum << endl;
}
void maximum (int new_array[], int num)
{
for (unsigned int i = 0; i < num; i++)
if (new_array[i] > maximum)
maximum = new_array[i];
cout << "Maximum value: " << maximum << endl;
return 0;
}
void median(int new_array[], int num)
{
//CALCULATE THE MEDIAN (middle number)
if(num % 2 != 0){// is the # of elements odd?
int temp = ((num+1)/2)-1;
cout << "The median is " << new_array[temp] << endl;
}
else{// then it's even! :)
cout << "The median is "<< new_array[(num/2)-1]<<new_array[num/2]< endl;
}
mean(new_array, num);
}
void sort(int new_array[], int num)
{
//ARRANGE VALUES
for(int x=0; x<num; x++){
for(int y=0; y<num-1; y++){
if(new_array[y]>new_array[y+1]){
int temp = new_array[y+1];
new_array[y+1] = new_array[y];
new_array[y] = temp;
}
}
}
cout << "List: ";
for(int i =0; i<num; i++){
cout << new_array[i] << " ";
}
cout << "\n";
median(new_array, num);
}
void average_(int new_array[], int nums)
{
float sum;
for (unsigned int i = 0; i < 20; ++i)
{
sum+=num;
}
cout << "Average value: " << average_/num << endl;
}
Please tell the necessary corrections
You have a ways to go, your code does not do any of the things you want yet. However, you mentioned that you are a beginner so I fixed your code and set up a basic structure of how to get going. I left comments on what I changed and what you need to do. That being said, I don't know what you mean by "Do a binary search on the 15th element"
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
int ra()
{
// You wanted a number between 0 and 999 inclusive so do not add 1
// Instead do a modulus of 1000
int r = rand() % 1000;
return r;
}
int main ()
{
// Do this to get different random numbers each time you run your program
srand(time(NULL));
// You have to call ra as a function. Do this by writing: ra()
// Here I am storing 20 random numbers in an array
int nums[20];
for (unsigned int i = 0; i < 20; ++i)
{
nums[i] = ra();
cout << "Index: " << i << ", random number: " << nums[i] << endl;
}
// Iterate to find the minimum number
int minimum = nums[0];
for (unsigned int i = 1; i < 20; ++i)
if (nums[i] < minimum)
minimum = nums[i];
cout << "Minimum value: " << minimum << endl;
// TODO: Find the maximum in basically the same way
// TODO: Find the average by summing all numbers then dividing by 20
// TODO: Find the median by sorting nums and taking the average of the two center elements
// TODO: etc.
return 0;
}
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int r;
int ra;
int i=0;
int ra(){
r = (rand() % 999) + 1;
return r;
}
int main ()
{
int random_;
srand((int)time(0));
while (i++ < 20)
{
random_ = r;
cout<< random_<<endl;
}
return 0;
}

Print an array in C++

I'm trying to do some of my C++ homework, but I seem to have run into an issue. I need to make it so that the user inputs 8 numbers, and those said 8 get stored in an array. Then, if one of the numbers is greater than 21, to output said number. The code is below, and it's kind of sloppy. Yes, first year C++ learner here :p
#include <iostream>
using namespace std;
int main() {
const int NUM_ELEMENTS = 8; // Number of elements
int userVals[NUM_ELEMENTS]; // User numbers
int i = 0; // Loop index
int sumVal = 0; // For computing sum
int prntSel = 0; // For printing greater than 21
// Prompt user to populate array
cout << "Enter " << NUM_ELEMENTS << " integer values..." << endl;
for (i = 0; i < NUM_ELEMENTS; ++i) {
cin >> userVals[i];
}
for (int i = NUM_ELEMENTS - 1; i > 21; i--)
cout << "Value: " << sumVal << endl;
// Determine sum
sumVal = 0;
for (i = 0; i < NUM_ELEMENTS; ++i) {
sumVal = sumVal + userVals[i];
}
cout << "Sum: " << sumVal << endl;
return 0;
}
Don't reinvent the wheel, use standard algorithms:
std::copy_if(std::begin(userVals), std::end(userVals),
std::ostream_iterator<int>(std::cout, "\n"),
[] (auto x) { return x > 21; });
I improved the rest of your program as well:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <numeric>
#include <vector>
auto constexpr count = 8;
int main() {
std::vector<int> numbers(count);
std::cout << "Enter " << count << " integer values...\n";
std::copy_n(std::istream_iterator<int>(std::cin), numbers.size(), numbers.begin());
std::copy_if(numbers.begin(), numbers.end(),
std::ostream_iterator<int>(std::cout, "\n"),
[] (auto x) { return x > 21; });
auto sum = std::accumulate(numbers.begin(), numbers.end(), 0);
std::cout << "Sum: " << sum << '\n';
return 0;
}
See it live on Coliru!
Ok, I'm going to explain this to you and keep it simple. This loop
`for (int i = NUM_ELEMENTS - 1; i > 21; i--)`
will never execute because in your first iteration you are checking if (NUM_ELEMENTS-1=7)>21. You are then decrementing i so this will take the series (6,5,4,...) and nothing would ever happen here.
If you have to sum the numbers greater than 21, which I presume is what you need then you will have to remove the above loop and modify your second loop to:
for (i = 0; i < NUM_ELEMENTS; i++) {
if(userVals[i]>21)
sumVal = sumVal + userVals[i];
}
This way, you add the numbers in the array that are only greater than 21. The index of userVals is determined by the i variable which also acts as a counter.
You're on the right track. There's just a few things wrong with your approach.
#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
const int NUM_ELEMENTS = 8;
int userVals[NUM_ELEMENTS];
int i = 0;
int sumVal = 0;
int prntSel = 0;
int size = sizeof(userVals) / sizeof(int); // Get size of your array
// 32/4 = 8 (ints are 4 bytes)
cout << "Enter " << NUM_ELEMENTS << " integer values..." << endl;
for (i = 0; i < NUM_ELEMENTS; ++i) {
cin >> userVals[i];
}
for(int i = 0; i < size; i++) {
if(userVals[i] > 21) { // Is number > 21?
cout << userVals[i] << endl; // If so, print said number
exit(0); // And exit
}
else
sumVal += userVals[i]; // Else sum your values
}
cout << "Sum: " << sumVal << endl;
return 0;
}
#include <iostream>
using namespace std;
int main() {
const int NUM_ELEMENTS = 8; // Number of elements
int userVals[NUM_ELEMENTS]; // User numbers
int i = 0; // Loop index
int sumVal = 0; // For computing sum
int prntSel = 0; // For printing greater than 21
// Prompt user to populate array
cout << "Enter " << NUM_ELEMENTS << " integer values..." << endl;
for (i = 0; i < NUM_ELEMENTS; ++i) {
cin >> userVals[i];
}
// for (int i = NUM_ELEMENTS - 1; i > 21; i--)
// cout << "Value: " << sumVal << endl;
for( i = 0; i < NUM_ELEMENTS; ++i )
{
if( userVals[ i ] > 21 )
{
cout << "Value: " << i << " is " << userVals[ i ] << endl;
}
}
for (i = 0; i < NUM_ELEMENTS; ++i) {
sumVal = sumVal + userVals[i];
}
cout << "Sum: " << sumVal << endl;
return 0;
}
Try
for (int i = NUM_ELEMENTS - 1; i > 21; i--)
cout << "Value: " << sumVal << endl;
to
for (i = 0; i < NUM_ELEMENTS; ++i) {
if(userVals[i] > 21)
cout << "Value: " << userVals[i] << endl;
}
This line isnt needed as well, as you arent using it.
int prntSel = 0; // For printing greater than 21
for (int i = NUM_ELEMENTS - 1; i > 21; i--)
cout << "Value: " << sumVal << endl;
Here you are printing the value of sumVal, not the value of the array in the position i. The line should be:
cout << "Value: " << usersVals[i] << endl;
Also that that your for is not doing what you think it does. for doesn't use the condition you gave to decide if will execute the current iteration or not, it uses the condition to decide if the loop should continue or not. So when you put i > 21, means that it will continue running while i is bigger than 21. To achieve your goal, you should make a test (if statement) inside the loop.
The final result it would be:
for (i = 0; i < NUM_ELEMENTS; ++i) {
if (usersVals[i] > 21) {
cout << "Value: " << usersVals[i] << endl;
}
}