I've recently started working through the "c++ primer 5th Edition". I'm currently on the following exercise:
Exercise 1.11:
Write a program that prompts the user for two integers.
Print each number in the range specified by those two integers.
I have written the following code as a solution :
#include <iostream>
int main(){
int num1 = 0, num2 = 0;
std::cout << std::endl << "Please enter two numbers to find a range between" << std::endl;
std::cin >> num1 >> num2;
if (num1 < num2)
while (num1 <= num2){
std::cout << std::endl << num1;
++num1;
}
if (num2 < num1)
while (num2 <= num1){
std::cout << std::endl << num2;
++num2;
}
if (num1 == num2)
std::cout << std::endl << num1;
std::cout << std::endl;
However when I input the numbers, the output is not quite correct;
Sample input:
Please enter two numbers to find a range betweem
>> 1 5
Sample output:
1
2
3
4
5
5
6
What I don't understand, is that if the first number i input is larger than the first (e.g. num1 > num2), then the program produces the desired result, eg:
Please enter two numbers to find a range between
>> 5 1
1
2
3
4
5
What is particularly confusing is that, when I swap the order of the conditional statements, the first example will work correctly and the second will produce incorrect output.
Just to be clear, I'm aware of a cleaner, correct solution to this exercise. I would just like to know the reason that my program functions this way.
I'd very much appreciate an explanation!
Its so simple.
Just add 'else' for the bottom two if loops
Basically you need to go through only 1 'if' loop, but your program goes through each 'if' loop
Actually you are increamenting your num1 in the first condition when all iterations of while loop completed your second if condition gets true because its the loop exit condition of first if(i.e. num1 <= num2), so your second if triggered and print the last 5 6 .
While in second case your first if not triggered and you reach the second if and hence your flow works properly
As Technoid said, add else statements. Your code should now become:
#include <iostream>
int main(){
int num1 = 0, num2 = 0;
std::cout << std::endl << "Please enter two numbers to find a range between" << std::endl;
std::cin >> num1 >> num2;
if (num1 < num2)
while (num1 <= num2){
std::cout << std::endl << num1;
++num1;
}
else if (num2 < num1)
while (num2 <= num1){
std::cout << std::endl << num2;
++num2;
}
else if (num1 == num2)
std::cout << std::endl << num1;
/* Alternatively for (num1 ==num2) use:
else
std::cout << std::endl << num1;
*/
std::cout << std::endl;
}
Related
I am currently stuck in my homework and the problem is that I need to create a program that will ask for 5 integer numbers from which I should determine the highest and lowest value. I am quite confused as of now, and my initial code is this:
#include<iostream>
using namespace std;
int main(){
int num1,num2,num3,num4,num5,min=0,max=0;
cout << " Enter 1st number : ";
cin >> num1;
cout << " Enter 2nd number : ";
cin >> num2;
cout << " Enter 3rd number : ";
cin >> num3;
cout << " Enter 4th number : ";
cin >> num4;
cout << " Enter 5th number : ";
cin >> num5;
do{
if(num1<num2 && num1<num3 && num1<num4 && num1<num5 ){
max = num1;}
if(num2<num1 && num2<num3 && num2<num4 && num2<num5 ){
max = num2;}
if(num3<num1 && num3<num2 && num3<num4 && num3<num5 ){
max = num3;}
if(num4<num1 && num4<num3 && num4<num2 && num4<num5 ){
max = num4;}
if(num5<num1 && num5<num3 && num5<num4 && num5<num2 ){
max = num2;}
}while(max>0);
cout << " The highest number is : " <<max;
return 0;
}
Any help would be appreciated. Thanks in advance!
You should store your numbers into a std::vector<int> or std::array and then use the std::minmax_element algorithm to obtain the largest and smallest number.
If you are allowed to use std::max and std::min, you can use:
max = std::max({num1, num2, num3, num4, num5});
min = std::min({num1, num2, num3, num4, num5});
to simplify the code in the loop.
This would be my solution without using arrays.
I'd suggest you to try it yourself before. You don't learn when you just copy code.
#include <iostream>
int main() {
int i=0, num, min=INT_MAX, max=INT_MIN;
do {
std::cout << "Enter number: ";
std::cin >> num;
if (num < min) {
min = num;
}
if (num > max) {
max = num;
}
i++;
} while (i < 5);
std::cout << "The max number is: " << max << std::endl;
std::cout << "The min number is: " << min << std::endl;
return 0;
}
If you don't need to remember, you can loop for e.g. 5 times, then have a comparison before asking the next number.
so generally (idea, write it yourself and learn):
for (5 times)
ask user input, save as input
if largest number is null, then equal to input
else if largest number is smaller, then set input equal to largest number
Continue for loop times.
Rather than compare all the numbers each time. Simply compare your current smallest against the numbers in sequence.
int data[5];
// read numbers into data.
int min = data[0]; // Guess that number 0 is the smallst number.
// Now check if the guess is correct and update if you are wrong.
for(int loop = 0; loop < 5; ++loop)
{
// check if data[loop] is smaller than your current guess.
// if it is smaller than update your guess.
// when you have checked all the values exit the loop.
}
std::cout << "Smallest: " << min << "\n";
There is no need to use a loop to do this you can do that without it else if it's necessary to use a loop you must use an array or some other data structure
I have to write a program in C++ and am unsure on how to return to the top after an error. For example, I have the user input 2 integers, if the 2nd integer is smaller than the first i have an error stating pls enter in a number larger than the first, but from here I do not know what code to enter to have the question be asked again / send to the beginning / top of the code?
if (num1 > num2)
cout << "You second number must be larger than your first number." << endl;
Problem
I do not know what code to enter to have the question be asked again / send to the beginning / top of the code?
Well almost always when you have that situation, you will use a while loop. This loops over the block if the condition is true.
#include <iostream>
#include <string>
int main()
{
int num1;
int num2;
do {
std::cout << "What is first num? ";
std::cin >> num1;
std::cout << "What is second num? ";
std::cin >> num2;
} while (num1 < num2);
}
Basically, what happens is first you have to declare the integers num1 and num2. Then you have a do while loop! Well this executes the code in the do block before checking for the condition! First we ask for the two user inputs, then we check for the condition. Let's look at the condition carefully:
while(num1<num2)
This means if the first number the user entered is less than the second number, loop through the while block. The while block does the same thing until num1 becomes greater than num2!
Here is a compiled version (GCC).
Additional Exercises
icodecool
Tutorial
CS_PDF
References
cpprefrence
MSDN
Flow Control Tutorial
Glossary:
do-while loop:
Executes a statement repeatedly until the value of the expression becomes false. The test takes place after each iteration.
Syntax
attr(optional) do statement while ( expression ) ;
attr(C++11) - any number of attributes
expression - any expression which is contextually convertible to bool. This expression is evaluated after each iteration, and if it yields false, the loop is exited.
statement - any statement, typically a compound statement, which is the body of the loop
Try:
cout << "Enter number 2: ";
cin >> num2;
while (num1 > num2) {
cout << "You second number must be larger than your first number." << endl;
cout << "Enter number 2: ";
cin >> num2;
}
int num1 = 0, num2 = 0;
do
{
cout << "num1: ";
cin >> num1;
cout << "num2: ";
cin >> num2;
if(num2 < num1)
cout << "error num2 is smaler than num1" << endl;
}while(num2 < num1);
I just can't seem to get this program to work properly. I can get it to accept two integers and print them to the screen. But I can't get the program to terminate when the '|' is used. Once that its entered it loops infinitely. Here is the code that I have so far:
#include "../../std_lib_facilities.h"
int main()
{
int num1 = 0;
int num2 = 0;
char counter = '\0';
cout << "Please enter two integers and press enter. \n";
bool test = true;
while (counter != '|')
{
cin >> num1 >> num2;
cout << "Your numbers are: " << num1 << " " << num2 << endl;
if (cin.fail())
{
cout << "Goodbye!\n";
test = false;
}
else (counter != '|');
cout << "Enter more numbers or press '|' to exit.\n";
}
system("pause");
}
You are using the wrong condition in your while loop. You are never changing counter so the loop will never end. However you do change test to false in the while loop if the input fails. You can change the condition of the while loop to use test instead like
while(test)
{
//...
}
Since counter is no longer being used you can get rid of it completely.
Please note that unless you change to taking in string and parsing the input any input that will cause cin to fail will end the loop not just a |.
I got an assignment where we make a cmd prompt show up and display a flashcard game for multiplication. After inputting a correct answer a prompt shows up and asks the user to go "Again? Y/N." after the second input answer the prompt to ask the user doesn't show up and it's stuck on a "congratulations" message. This happens when I write in code to randomly generate two numbers for the game twice. one outside the while loop, and one inside while loop. If I leave one out the 2nd code for the random numbers it will run fine but will only display the same numbers over again. what I'm asking is how do I fix it so that it won't get stuck after the second answer input?
sample code below:
#include <iostream>
using namespace std;
int main()
{
int num1, num2, ans, guess, count = 0;
char choice;
num1 = rand() % 12 + 1;
num2 = rand() % 12 + 1;
//first number generator.
ans = num1 * num2;
do
{
{
cout << num1 << " X " << num2 << " = ";
cin >> guess;
cout << "Wow~! Congratulations~! ";
count++;
num1 = rand() % 12 + 1;
num2 = rand() % 12 + 1;
//second number generator.
} while (guess != ans);
cout << "\nAgain? Y/N: ";
cin >> choice;
} while ((choice == 'y') || (choice == 'Y'));
//after two turns the loop stops. Can't make a choice.
cout << " Thanks for playing! Number of tries:" << count << endl;
return 0;
}
I'd guess the problem is because your loops aren't quite what you think they are.
do
{
The code above has started a do loop.
{
I suspect you intended to start another (nested) do loop here--but you left off the do, so it's just a block that gets entered, executed, and exited. Useless and pointless in this case.
cout << num1 << " X " << num2 << " = ";
cin >> guess;
cout << "Wow~! Congratulations~! ";
count++;
num1 = rand() % 12 + 1;
num2 = rand() % 12 + 1;
//second number generator.
} while (guess != ans);
You've formatted this as if the while were closing the nested do loop--but since you didn't actually create a nested do loop, this is just a while loop with an empty body. Its meaning would be more apparent with a little re-formatting:
// second number generator
}
while (guess != ans)
/* do nothing */
;
The problem can be found here:
do
{
{
cout << num1 << " X " << num2 << " = ";
cin >> guess;
As you can see, the second scope has no do statement. As a result it is only a codeblock.
You can solve it by writing a do statement for the second code block.
Because the do is not present in the second bracket ({), the while is interpreted as a while loop:
while (guess != ans);
or
while (guess != ans) {
}
this thus keeps looping until guess is not equal to ans. But since in the loop does not modify any of the two variables, the loop will keep iterating.
Other errors: note that the program is still incorrect, since it will claim you have answered the question, regardless of the answer. You can fix it by implementing this as follows:
int main()
{
int num1, num2, ans, guess, count = 0;
char choice;
do {
num1 = rand() % 12 + 1;
num2 = rand() % 12 + 1;
ans = num1 * num2;
do {
cout << num1 << " X " << num2 << " = ";
cin >> guess;
if(guess == ans) {
cout << "Wow~! Congratulations~! ";
} else {
cout << "No, wrong!\n";
}
count++;
} while (guess != ans);
cout << "\nAgain? Y/N: ";
cin >> choice;
} while ((choice == 'y') || (choice == 'Y'));
//after two turns the loop stops. Can't make a choice.
cout << " Thanks for playing! Number of tries:" << count << endl;
return 0;
}
I'm a beginner learning code, and I was copying what a YouTube video for programming teaching said. But when I wrote the code, it resulted in some errors.
Here's the code:
#include <iostream>
using namespace std;
int main()
{
int num1 , num2;
cout<< " Enter number 1 and number 2 \n";
cin>> num1 >> num2;
if (num1 == num2);
cout<< "The both numbers are equal \n";
else if (num1> num2)
cout<< "Number 1 is greater than number 2 \n";
else (num1< num2)
cout<< "Number 2 is greater than number 1 \n";
return 0;
}
Note that ; means the expression ends, so you should change
if (num1 == num2);
to
if (num1 == num2)
And else doesn't need condition, so change
else (num1< num2)
to
else
; is not placed after `if` condition
Moreover, else does not get a condition... it always checks the negation of its corresponding if.
In fact if the condition of if does not hold the code in the block of else is executed.... by changing
else (num1< num2)
cout<< "Number 2 is greater than number 1 \n";
to
else
cout<< "Number 2 is greater than number 1 \n";
your problem will get solved.
You dont need ; after if condition check
If you want to do a condition check, you should use else if, in that case else is not enough:
#include <iostream>
using namespace std;
int main()
{
int num1 , num2;
cout<< " Enter number 1 and number 2 \n";
cin>> num1 >> num2;
if (num1 == num2)
cout<< "The both numbers are equal \n";
else if (num1> num2)
cout<< "Number 1 is greater than number 2 \n";
else if (num1< num2)
cout<< "Number 2 is greater than number 1 \n";
return 0;
}