Program output becomes unstable when all negative inputs are introduced? - c++

As the title suggests, my program which is designed to find the largest element within a user defined integer array becomes unstable when all negative numbers are used for the user input. Additionally the output becomes unstable when all zero's are used for the user input (excluding the input for total # of elements).
The program works just fine when all positive numbers are used. This is quite perplexing to me and I'm sure there's a valid explanation but I was under the impression that in C++, the int & float data types were automatically signed and would be able to handle negative numbers for it's data range. So why would the program not return a valid output if all negative numbers are used for the user array input(s)?
Bad Output:
Please enter a total number of elements you'll be using: 5
Please enter each variable one by one.
Enter number 1: -10
Enter number 2: -5
Enter number 3: -20
Enter number 4: -2
Enter number 5: -7
The largest element within specified realNum[5] array is element number: 6 with a value of: 5.88501e-039
Good Output:
Please enter a total number of elements you'll be using: 5
Please enter each variable one by one.
Enter number 1: 10
Enter number 2: 5
Enter number 3: 20
Enter number 4: 2
Enter number 5: 7
The largest element within specififed realNum[5] array is element number: 3 with a value of: 20
Program:
//10.2 Largest Element Finder of an Array
//Mandatory header
#include <iostream>
//Use namespace std ;
using namespace std ;
//Mandatory main method
int main ()
{
//Declare and initlize variables
int i, total, realNum = 0, temp = 1 ;
//Ask user to input a number of total elements
cout << endl << endl
<< "Please enter a total number of elements you'll be using: " ;
//Wait for user input
cin >> total ;
//Declare array set
float setNum [total] ;
//Ask user to input each varaible
cout << endl
<< "Please enter each variable one by one." << endl << endl ;
for ( i = 0 ; i < total ; i ++ )
{
cout << endl << "Enter number " << (i + 1) << ": " ;
cin >> setNum [i] ;
}
//Find the largest element within the array
for ( i = 0 ; i < total ; i ++ )
{
if ( setNum [i] <= setNum [temp] ) //Discard current i if less than the next element - Means temp is HIGHER and should be saved
{
if ( setNum [temp] >= setNum[realNum] )
realNum = temp ; //Temp can now be changed for iteration purposes as realNum is saving the highest element's positon
}
else if ( setNum [i] >= setNum [temp] ) //Discard current i if more than the next element and use the remainder to compete against the realNum
{
if ( setNum [i] >= setNum [realNum] )
realNum = i ;
}
i ++ ;
temp += 2 ;
}
//Display calculations
cout << endl << endl
<< "The largest element within specififed realNum[" << total << "] array is element number: " << (realNum + 1) << " with a value of: " << setNum[realNum] << endl ;
//Mandatory return statement
return 0 ;
}

Related

enter Odd, Even, zero and negative numbers and count using for and while loop in C++ without using arrray

I've met some problem during programming. I want to write a program to differentiate even numbers, odd numbers, zero values and negative numbers by using while and for loop.
1st question :
However, when I try to run my program, the last number I've entered will not be counted. I know it occur because of my o++ put at the top of the if condition, how should I solve my problem?
2nd question :
For the for loop parts, actually it may ignored those negative values. How should I solve it to let the negative numbers also count in loop ? May I changed the num>0 to num < 100000 to let the for loop works?
#include<iostream>
using namespace std;
#include<iostream>
using namespace std;
int main ()
{
int num ,numbers = 1 ;
char answer = 'Y' ;
int o=0, e=0, z=0 ,n=0 ;
// o for odd numbers, e for even numbers, z for zero values, n for negative numbers
cout << "Enter number" << numbers << ": " << endl ;
cin >> num ;
for ( num = num ; num >0; num++)
while (answer == 'y' || answer == 'Y')
{
if (num % 2 == 0 && num > 0)
{
e++ ;
cout<< "The number of even numbers is :" << e << endl;
numbers ++ ;
cout<<"Please enter number" << numbers << endl ;
cin >> num ;
cout<<"If you wish to continue, Please enter y or Y to continue this program : "<< endl ;
cin>> answer ;
}
else if (num % 2 == 1 && num > 0)
{
o++;
cout<< "The number of odd numbers is :" << o << endl;
numbers ++ ;
cout<<"Please enter number" << numbers << endl ;
cin >> num;
cout<<"If you wish to continue, Please enter y or Y to continue this program : "<< endl ;
cin>> answer ;
}
else if (num == 0)
{
z ++;
cout<< "The total of 0 is :" << z << endl;
numbers ++ ;
cout<<"Please enter number" << numbers << endl ;
cin >> num;
cout<<"If you wish to continue, Please enter y or Y to continue this program : "<< endl ;
cin>> answer ;
}
}
cout << "The total even numbers is :" << e << endl;
cout << "The total odd numbers is :" << o << endl ;
cout << "The total negative numbers is :" << n << endl ;
cout << "The total zero number is:" << z << endl;
return 0;
}
This line, in main() is really puzzling:
// ...
for ( num = num ; num >0; num++)
while (answer == 'y' || answer == 'Y')
The for(;;) statement is your main loop. The while statement will be executed as long as num is positive.
Let's look at this for() statement in detail:
for (num = num; // num = num ??? this statement does nothing.
num > 0; // the while statement (and the contents of the whule() loop block)
// will only execute if num is > 0.
++num) // if num was > 0 then this loop will run until num overflows...
Removing the for(;;) statement will make your program run a lot better.
Your o++ has nothing do with it.
(Perhaps you have been so convinced about that being the problem that you didn't think of looking elsewhere. It happens to everyone.)
The problem is that your sequence is this:
Check the most recently entered number and print the result
Ask the user for a number, but don't do anything with it
Ask the user whether they want to continue
If they want to continue, repeat from item 1
If they don't, stop counting
And since you stop counting if the user doesn't want to continue, the last number seems to have disappeared.
Fixing it left as an exercise.
(Think more carefully about which order you need to do things in.)
Handling negative numbers requires you to write some code to do that - you handle two cases of positive numbers, and one for zero, but you must have forgotten about the negatives.
Fixing this also left as an exercise.

C++ need help fixing to get desired output

I am working on a programming challenge from "Starting Out With C++: Early Objects, 10th Edition". I have the code about halfway done, but the output isn't coming out how it is supposed to be, and I am wondering how to fix it. I have it attached here and the desired output.
#include <iostream>
using namespace std;
int main()
{
float starting_num_of_organisms,
average_daily_population_increase,
size_of_daily_population;
int num_of_days_to_multiply;
cout << "Enter Starting Population: ";
while (!(cin >> starting_num_of_organisms) || starting_num_of_organisms < 2) {
cout << "Invalid. Population must be 2 or greater.";
cout << "Enter starting population: ";
cin.clear();
cin.ignore(123, '\n');
}
cout << "Enter positive daily growth % (.1 must be entered as 10): ";
while (!(cin >> average_daily_population_increase) || average_daily_population_increase < 0) {
cout << "Invalid. Daily Population Growth \n"
<< " must be greater than 0. \n"
<< "Enter Daily Population Growth (%): ";
cin.clear();
cin.ignore(123, '\n');
}
average_daily_population_increase *= .01;
cout << "Enter number of days to calculate: ";
while (!(cin >> num_of_days_to_multiply) || num_of_days_to_multiply < 1) {
cout << "Invalid. Number of days must not be less\n"
<< "than 1. Enter number of days to calculate: ";
cin.clear();
cin.ignore(123, '\n');
}
for (int i = 0; i < num_of_days_to_multiply; i++) {
cout << "Population size for day " << (i + 1);
cout << ": " << starting_num_of_organisms
<< endl;
starting_num_of_organisms += (starting_num_of_organisms * average_daily_population_increase);
}
return 0;
}
Here is the current output:
Enter Starting Population: 896.896
Enter positive daily growth % (.1 must be entered as 10): 2.785
Enter number of days to calculate: 8
Population size for day 1: 896.896
Population size for day 2: 921.875
Population size for day 3: 947.549
Population size for day 4: 973.938
Population size for day 5: 1001.06
Population size for day 6: 1028.94
Population size for day 7: 1057.6
Population size for day 8: 1087.05
The desired output is something like this below. The numbers are just for reference, and do not have to be specific to those numbers.
Enter starting population (greater than 2): 896.896
Enter positive daily growth % (.1 must be entered as 10): 2.785
Enter number of days to calculate (greater than 1): 8
----------------------------------
Start Population: 896.90
Daily Percent Growth: 2.79%
Number of Days: 8
Day Start End
Popl. Popl.
----------------------------
1 896.90 921.87
2 921.87 947.55
3 947.55 973.94
4 973.94 1001.06
5 1001.06 1028.94
6 1028.94 1057.60
7 1057.60 1087.05
8 1087.05 1117.33
It appears as though your code does the correct calculations. Just format the output and it will look like the desired output.
printf("%-10s%10s%10s\n", "day", "start", "end");
for(int i = 0; i < 30; i++)
printf("=");
printf("\n");
for (int i = 0; i < num_of_days_to_multiply; i++)
{
printf("%-10u%10.2lf", i + 1, starting_num_of_organisms);
starting_num_of_organisms +=
(starting_num_of_organisms *
average_daily_population_increase);
printf("%10.2lf\n", starting_num_of_organisms);
}
Note I used printf from the C libs (<stdio.h>), but the same can be achieved with cout, just much more verbose.
Output:
Enter Starting Population: 896.896
Enter positive daily growth % (.1 must be entered as 10): 2.785
Enter number of days to calculate: 8
day start end
==============================
1 896.90 921.87
2 921.87 947.55
3 947.55 973.94
4 973.94 1001.06
5 1001.06 1028.94
6 1028.94 1057.60
7 1057.60 1087.05
8 1087.05 1117.33

Program breaks when character is entered instead of integer

I'm new to C++ and am finding it difficult to find information on the cin feature. This is my first program ever so it's very simple. It determines if the entered number is a prime number or composite whilst filtering out bad values such as negative numbers and decimals. The program also will time-out after 10 failed entries.
The last feature I want to add to this program is the ability to filter out character inputs but I'm having no luck with trying different solutions. I tried converting the character to a float/double/int but to no avail. I just need help with cin, if the user inputs the letter 'K' or any other invalid character i'd like the program to recognize this and then produce the "invalid value" cout message + new entry try x number of times.
Currently when a character is entered the program crashes and goes through all 10 try attempts at once leaving the output results in the terminal very sloppy.
#include <iostream>
#include <cmath>
using namespace std ;
int main (void)
{
//Declare variables
int y, c, i1 ;
double i ;
//Ask for user input
cout << endl << endl << "Please enter a number: " ;
cin >> i ;
//Eliminate bad user input values
i1 = i ;
//Detect when a decimal number is entered for the first attempt
for ( c = 1 ; int(i1) != i ; c ++ )
{
cout << endl << "This value is invalid. Please retry: " ;
cin >> i ;
i1 = i ;
//Terminate program after so many failed attempts
if ( 8 < c )
{
cout << endl << "This value is invalid. Try again next time! \n\n" ;
return 0 ;
}
//Detect if a '0' is entered on the latter attempts
for ( c ; i < 1 ; c ++ )
{
cout << endl << "This value is invalid. Please retry: " ;
cin >> i ;
i1 = i ;
//Terminate program after so many failed attempts
if ( 8 < c )
{
cout << endl << "This value is invalid. Try again next time! \n\n" ;
return 0 ;
}
}
}
//Detect when '0' is entered on the first attempt
for ( c = 1 ; i < 1 ; c ++ )
{
cout << endl << "This value is invalid. Please retry: " ;
cin >> i ;
i1 = i ;
//Terminate program after so many failed attempts
if ( 8 < c )
{
cout << endl << "This value is invalid. Try again next time! \n\n" ;
return 0 ;
}
//Detect if a decimal number is entered on the latter attempts
for ( c ; int(i1) != i ; c ++ )
{
cout << endl << "This value is invalid. Please retry: " ;
cin >> i ;
i1 = i ;
//Terminate program after so many failed attempts
if ( 8 < c )
{
cout << endl << "This value is invalid. Try again next time! \n\n" ;
return 0 ;
}
}
}
//Find prime numbers
for ( y = 1 ; y <= i ; y ++ )
{
//Give instant result if user input is no. 1
if ( i == 1 )
{
cout << endl << "The number: " << i << " is a composite number.\n\n" ;
break ;
}
//Eliminate no. 1 from prime number search
if ( y == 1 )
continue ;
//Search for a whole number division using modulus
if ( fmod(i, y) == 0 )
{
if ( i == y )
cout << endl << "The number: " << i << " is a prime number.\n\n" ;
else if ( i != y )
{
cout << endl << "The number: " << i << " is a composite number.\n\n" ;
break ;
}
}
}
return 0 ;
}

Calculating the minimum and maximum values from a user-generated list

I am writing code for an assignment that wants me to make a program that asks the user for the amount of integers they'd like to input then it accepts each input while testing if the value is the max value or the minimum.
The program runs fine but for some reason will stop and show me the min and max number when I have entered in 1 integer less than the original input.
Examples of the problem I am having:
If I input 5 for the first value, it asks me to enter 5 integers.
After entering 4 numbers, 1 2 3 and 4.
It tells me the max is 4 and min is 1.
It prevents me from entering in the 5th integer.
Additionally,
If I input 5 for the first value, it asks me to enter 5 integers.
If I enter a negative number, like -1, the input allowed to me is further
shortened.
If I enter -1, 2, 3 then the output is min: 2 and max: 3
I have two main questions:
What adjustments do I need to make to my code so that I can properly
enter in the number of integers initially asked for?
What adjustments need to be made in order for me to be able to enter
negative integers so they are outputted correctly?
The code:
#include <iostream>
using namespace std;
int main()
{
int input;
int tmp;
int counter = 1;
int max_num = 0;
int min_num;
// prompt user for integer amount
cout << "How many integers would you like to enter? " << endl;
cin >> input;
cout << "Please enter " << input << " integers." << endl;
tmp = input;
// loop for requested amount with a test for each input
while (counter <= tmp) {
cin >> input;
// if smaller than previous number it is the minimum
if (input < min_num || min_num == -1) {
min_num = input;
counter++;
}
// if larger than previous number it becomes max number else
if (input > max_num) {
max_num = input;
counter++;
} else { // continue loop if number isn't bigger than max or smaller than min
counter++;
}
}
// display the max and min
cout << "min: " << min_num << endl;
cout << "max: " << max_num << endl;
return 0;
}

Switch statement

Using switch statement create a code that output remainders( 0, 1, 2, 3 and others) when divided by 8. User inputs 20 integer from 0 till 99. Each remainder should show its total count.
Eg :This is how the output should be.
Total number with remainder 0 is 4.
Total number with remainder 1 is 6.
Total number with remainder 2 is 5.
Total number with remainder 3 is 3.
Total number of other remainder is 2.
/
#include <iostream>
using namespace std;
int main()
{
int i, x[20];
cout << "Enter 20 integer numbers from 0 to 99: " <<endl;
for (i=1;i<=20;i++)
{
cout << "Input " << i <<":";
cin >> x[i]; // above this code, its working.
}
int remainder ; // From here im not sure how i should do it
switch (remainder)
{
case x[i] % 8 == 0 :
cout << "Total number with remainder zero is " << endl ;
break;
case x[i] % 8 == 1 :
cout << "Total number with remainder one is " << endl ;
break;
case x[i] % 8 == 2 :
cout << "Total number with remainder two is " << endl ;
break;
case x[i] % 8 == 3 :
cout << "Total number with remainder three is " << endl ;
break;
default :
cout << "Total of others is " << endl ;
}
return 0 ;
}
I have the general idea of the switch statements. I'm new to c++ and also to this website. Between the errors are at case part. It says i cant use x[i]. So should i just use x or other integer? Im not sure how to count the total number for each case. should i be using count++ ?
Switch statements are supposed to have a condition to test and then execute commands based on the results. The problem here is that you are testing a variable that does not have a value. The parentheses contain the data being tested. The cases are to execute given commands based on the resulting value. The thing you are testing here is x[i] % 8. This should go between in the parentheses. The case should just have the value attached to it.
switch (x[i] % 8) {
case 0: //...
case 1: //...
case 2: //...
case 3: //...
default: //...
}
case will test whether the result of the action taken in the parentheses equal its assigned value (e.g. 0, 1, 2, 3, or default) and execute the assigned command.