C++ : Making a do while loop repeat - c++

I'm very sorry for the super newbie question, but I cannot for the life of me understand how to make a do while loop repeat. I changed a while loop into a do while loop and now I don't know how to get it to ask "would you like to repeat Y or N?" any explanation?
I've read various posts that accomplish a do while loop repeat, but they don't make sense to me.
Am I essentially going to wrap this code into another do while loop? Do I move the boolean expression to before the while?
#include <iostream>
using namespace std;
int main(void)
{
int x;
int count = 0;
int N;
double sum = 0;
double average;
char ans;
{
cout << "Enter number of values, N, to be read in <Enter>:" << endl;
cin >> N;
do
{
cout << "\n Enter a grade <Enter>: ";
cin >> x;
sum = sum + x;
count++; //
} while (count < N);
if (N == 0)
cout << "You have entered 0 numbers. No average will be computed. Bye! \n";
else {
average = average = sum / N;
cout << "The average of these " << N << " grades is " << average << endl;
}
cout << "Would you like to enter more values to calculate your grade average?\n";
system("pause");
return 0;
}
}

can do this:
char repeat='y';
cout << "Enter number of values, N, to be read in <Enter>:" << endl;
cin >> N;
do
{
for(int i=0;i<n;i++){
cout << "\n Enter a grade <Enter>: ";
cin >> x;
sum = sum + x;
count++; //
}
if (N == 0)
cout << "You have entered 0 numbers. No average will be computed. Bye! \n";
else {
average = average = sum / N;
cout << "The average of these " << N << " grades is " << average << endl;
}
cout << "Would you like to enter more values to calculate your grade average?\n";
cin>>repeat;
}while(repeat=='y');

May be this is what you need, with char YorN you are considering if to continue or break the inner do-while.
#include <iostream>
using namespace std;
int main(void)
{
int x;
int count = 0;
int N;
double sum = 0;
double average;
char ans;
char YorN;
do{
cout << "Enter number of values, N, to be read in <Enter>:" << endl;
cin >> N;
do
{
cout << "\n Enter a grade <Enter>: ";
cin >> x;
sum = sum + x;
count++; //
} while (count < N);
if (N == 0)
cout << "You have entered 0 numbers. No average will be computed. Bye! \n";
else {
average = average = sum / N;
cout << "The average of these " << N << " grades is " << average << endl;
}
cout << "Would you like to enter more values to calculate your grade average?\n";
cin>>YorN;
} while (YorN=='Y');
return 0;
}

Although there are a ton of ways to do it better, this code allows me to explain what is happening. Do-While loops are definitely pretty tricky. However, just remember that a do-while loop is designed to run at least once.
In the case of our code, we set up if statements to test against running code where it is not appropriate.
Take a look at how the very first if statement is N > 0, the if-statement does execute, please do not forget that. Once more for emphasis, the if statement DOES execute, it just results in false.
With that being said, you use a do-while loop when you want your code block to execute AT LEAST once. Notice how our while statement has two things we're testing for, one, is the answer 'Y' from the user to continue, and if it is, is the newly inputted N value greater than 0?
You might be wondering if the inner most if statement ever executes at least once, well the answer is it depends on the previous if statement result if(N > 0) and if(count == N && N != 0) both execute once every single time the while loop stays true. However that nested if depends on it's parent result.
I hope this cleared some things up for you on do-while loops.
#include <iostream>
using namespace std;
int main(void)
{
int x;
int count = 0;
int N;
double sum = 0;
double average;
char ans = 'Y';
cout << "Enter number of values, N, to be read in <Enter>:" << endl;
cin >> N;
do
{
if(N > 0){ //THIS IF STATEMENT WILL ALWAYS RUN AT LEAST ONCE
cout << "\n Enter a grade <Enter>: ";
cin >> x;
sum = sum + x;
count++;
}
if(count == N && N != 0) {//THIS IF STATEMENT WILL ALSO ALWAYS RUN AT LEAST ONCE
average = average = sum / N;
cout << "The average of these " << N << " grades is " << average << endl;
cout << "Would you like to enter more values to calculate your grade average?\n";
cin>>ans;
if(ans == 'Y') {//This one depends on it's parents result.
x = 0;
N = 0;
sum = 0;
count = 0;
cout << "Enter number of values, N, to be read in <Enter>:" << endl;
cin >> N;
}
}
} while (ans == 'Y' && N != 0);
if (N == 0)
cout << "You have entered 0 numbers. No average will be computed. Bye! \n";
system("pause");
return 0;
}

Related

Printing on same line and add count in one line one time in c++

how to show output ( Number of grades above the Average + Grades above or equal the Average ) in same line i don't wont new line for each number + how to print these one time not many times , i mean because i use for loop it print Number of grades above the Average every number in one line i want just the count in one line how to do this
#include <iostream>
using namespace std;
int main()
{
int G,N;
float num[100], sum=0.0, average;
cout << "Enter the numbers of Student : ";
cin >> N;
while (N > 500 || N <= 1)
{
cout << "Error ! number of student should in range of (1 to 500)." << endl;
cout << "Enter the number again: ";
cin >> N;
}
for(G = 0; G < N; ++G)
{
cout << G + 1 << ". Enter " << G + 1 << " Mark : ";
cin >> num[G];
sum += num[G];
}
// find average
average = sum / N;
cout <<endl<< "Grades Average = " << average <<endl<<endl;
// find Grades above or equal the Average
cout<<"Grades above or equal the Average : "<< endl;
for (G = 0; G < N; ++G){
if (num[G] >= average){
cout << num[G] << endl;
}
}
// find Number of grades above the Average
cout<<endl;
for (G = 0; G < N; ++G){
if (num[G] >= average){
cout << "Number of grades above the Average : " << G + 1 << endl;
}
}
return 0;
}
There are a number of issues with your code:
num[] can hold 100 values max, but you are allowing the user to enter up to 500 values into it, thus you have the potential for a buffer overflow.
you say the valid number of students is 1 to 500, but you are preventing the user from entering 1.
lack of adequate error handling when reading the user's input.
you are outputting "Number of grades above the Average : " inside the loop for every matching grade, which you say you don't want. You should instead output it once before entering the loop, then use the loop to count the matching grades without outputting each one, then output the final count after the loop is finished.
Try this:
#include <iostream>
#include <limits>
using namespace std;
const int maxStudents = 500;
int main()
{
int G, N, nAverages = 0;
float num[maxStudents], sum = 0.0, average;
cout << "Enter the number of Students : ";
do
{
if (cin >> N)
{
if (N >= 1 && N <= maxStudents)
break;
cout << "Error ! Number of students should be in range of (1 to " << maxStudents << ")." << endl;
}
else
{
cout << "Error ! Invalid input." << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
cout << "Enter the number again: ";
}
while (true);
for(G = 0; G < N; ++G)
{
cout << G + 1 << ". Enter Mark : ";
while (!(cin >> num[G]))
{
cout << "Error ! Invalid input." << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Enter the mark again: ";
}
sum += num[G];
}
// find average
average = sum / N;
cout << endl << "Grades Average = " << average << endl << endl;
// find Grades above or equal the Average
cout << "Grades above or equal the Average : " << endl;
for (G = 0; G < N; ++G){
if (num[G] >= average){
cout << G + 1 << ": " << num[G] << endl;
++nAverages;
}
}
// Number of grades above the Average
cout << endl << "Number of grades above the Average : " << nAverages << endl;
return 0;
}

how to count the number of "numbers in for"

everyone, I build a programme to know even and odd number from given numbers.
The even and odd number works just fine, and i want to know the total count of numbers ranging from the start number to the end number but it always says 11 at the output for both.
How do I solve this? and is there any function to count letters/numbers because it will be very helpful.
I did search it up but I can't find any Thank you
#include<stdio.h>
#include <iostream>
using namespace std;
int main(){
int number;
int firstNum,secondNum;
int countOdd,countEven;
cout << "Enter the first number: ";
cin >> firstNum;
cout << "Enter the second number: ";
cin >> secondNum;
if (firstNum>secondNum )
cout << "Sorry the first number must be less than second number";
else
cout << "Odd numbers in given range are: ";
for(number = firstNum;number <= secondNum; number++)
if(number % 2 !=0)
cout << number<< " ";
countOdd = number;
cout << "\nTotal count of odd number is :" << countOdd << endl;
printf("\nEven numbers in given range are: ");
for(number = firstNum;number <= secondNum; number++)
if(number % 2 ==0)
cout << number << " ";
countEven = number;
cout << "\nTotal count of even number is :" << countEven << endl;
return 0;
}
Code to count odd and even numbers:
using namespace std;
// Return the number of odd numbers
// in the range [L, R]
int countOdd(int L, int R){
int N = (R - L) / 2;
// if either R or L is odd
if (R % 2 != 0 || L % 2 != 0)
N += 1;
return N;
}
// Driver code
int main()
{
int L = 3, R = 7;
int odds = countOdd(L, R);
int evens = (R - L + 1) - odds;
cout << "Count of odd numbers is " << odds << endl;
cout << "Count of even numbers is " << evens << endl;
return 0;
}
You are overwriting your counts with every iteration of the for loop. countOdd = number; should be moved inside the if statement and read more like this:
if (number % 2 != 0) {
cout << number << " ";
countOdd++;
}
That way you will actually be counting the numbers as you find them.
This goes the same for the code in the counting of even numbers.
if (number % 2 == 0) {
cout << number << " ";
countEven++;
}
And don't forget to initialize the counters variables before using them:
countOdd = countEven = 0;

Why doesn't this code work correctly? (C++)

If I input this code:
#include<iostream>
using namespace std;
int main ()
{
int input, qty, min, max;
bool validity = 1;
cout << "How many integers would you like to enter? \n";
cin >> qty;
if (qty <= 0)
cout << "Please enter a positive number\n";
else
{
cout << "Please enter " << qty << " integers:" << endl;
for (int x=0; x < qty; x++)
{
cin >> input;
if (input > max)
max = input;
if (input < min)
min = input;
}
}
if (validity)
{
cout << "Minimum: " << min << endl;
cout << "Maximum: " << max << endl;
}
return 0;
}
It works as expected.
But if I have this:
#include<iostream>
using namespace std;
int main ()
{
int input, qty, min, max;
bool validity = 1;
cout << "How many integers would you like to enter? \n";
cin >> qty;
if (qty <= 0)
cout << "Please enter a positive number\n";
else
{
cout << "Please enter " << qty << " integers:" << endl;
for (int x=0; x < qty; x++)
{
cin >> input;
if (input > max)
max = input;
if (input < min)
min = input;
}
}
if (max > 2147483646)
{
cout << "Please enter a valid value for integers." << endl;
validity = 0;
}
if (min < -2147483647)
{
cout << "Please enter a valid value for integers." << endl;
validity = 0;
}
if (validity)
{
cout << "Minimum: " << min << endl;
cout << "Maximum: " << max << endl;
}
return 0;
}
It gives me erroneous values.
What am I doing wrong? Any help is greatly appreciated. (I'm a noob btw). Adding a little text here so that I can post this question.............................
max and min are uninitialized. In C++, this means the values can be anything at all, unless in say Java where primitives are auto-initialized to 0.
One way to fix is to set a first flag, and set max and min the the first value entered.
bool first = true;
for (int x=0; x < qty; x++)
{
cin >> input;
if( first )
{
max = input;
min = input;
first = false;
}
if (input > max)
max = input;
if (input < min)
min = input;
}
Here's what I mean by uninitialized. When starting up, min and max can be anything. Anything at all. Try it by printing out the value of min and max before your loop. It should (could) be different every time you run the program. Basically the value depends on what data was in that memory location the last time it was used.
So the if( input > max) is checking to see if input is greater than some random number between -2billion and 2 billion. (not useful). The first flag I put in there initializes min/max in the first iteration of the for loop, or the first value entered by the user, which is guaranteed to be both the min and the max of the entered value since it's the only entered value.

C++ While loop and Array

I have made a application where you enter in all the marks and it gives you the average and also makes it repeat itself but the problem is that
1) when ever the 'Finding average' line is executed, it gives me the
wrong value and also I use array to do so.
2)When ever I try to
iterate the application, the destructor is called and messes up my
application
and here is my code
#include <iostream>
#include <string>
using namespace std;
class Grade{
private:
int* ptr;
int number;
public:
Grade(const int hNumber){
number = hNumber;
ptr = new int[this->number];
}
Grade(const Grade& cpy){
ptr = new int[cpy.number];
}
void get_marks(){
for(int i = 0; i < number; ++i){
cout << "Enter Mark " << i << ": ";
cin >> ptr[i];
}
}
const int& operator [](const int access) const{
return ptr[access];
}
~Grade(){
cout << "Deleting memory" << endl;
delete [] ptr;
}
};
int main(){
//local variables
int sum = 0;
string name,subject;
int repeat;
char again = 'y';
//user interface
cout << "Welcome to Grade Marker" << endl;
cout << "Enter your name: ";
getline(cin,name);
while(again == 'y'){
cout << "Enter the subject name: ";
getline(cin,subject);
cout << "How many marks are being entered: ";
cin >> repeat;
//creating instance of grade
Grade grd(repeat);
grd.get_marks();;
//display info
cout << "The average mark is: ";
for (int i = 0; i < repeat; i++){
sum = ((sum + grd[i]) / repeat);
}
cout << sum << endl;
//looping the application
cout << "Would you like to enter another subject[y/n]: ";
cin >> again;
}
//good bye message
if (again == 'n' || again == 'no'){
cout << "Goodbye" << endl;
}
system("pause");
return 0;
}
and just to make it simple, the code section which I think gives me error are
cout << "Would you like to enter another subject[y/n]: ";
cin >> again;
}
//good bye message
if (again == 'n' || again == 'no'){
cout << "Goodbye" << endl;
}
and
//display info
cout << "The average mark is: ";
for (int i = 0; i < repeat; i++){
sum = ((sum + grd[i]) / repeat);
}
cout << sum << endl;
and thank you for your time
You are doing integer division, and in addition you do not reinitialize sum to 0 for each iteration. You can move sum declaration inside of the loop and just write:
float sum = 0;
for (int i = 0; i < repeat; i++){
sum += grd[i];
}
cout << "The average mark is: ";
cout << sum / repeat << endl;
std::cin.ignore() will help you here.
Adding...
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
...to the very end of your while-loop will clear out the input buffer up to the newline... You'll find that this will end the seemingly infinite loop.
See How do I flush the cin buffer? for more info.
Your while loop is calling the destructor because of scope. You are declaring the Grade grd every iteration you run the while loop. That means that your grd from the previous iteration is being redeclared again and again, hence the destructor being called. But that's normal. Did you want to save the Grade instances? In that case you'll need to make an array of Grade objects

In C++, I need to create a program that loops and stops when a certain number is entered, Then displays the max and min

*edit: Fixed the code after realizing I was being a dumbass
Fixed code that works:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
int one, two, three = 0, highnum, lownum;
cout << "Enter your first integer: ";
cin >> one;
cout << "\nEnter your second integer: ";
cin >> two;
if (one > two)
{
highnum = one;
lownum = two;
}
while (one != -99 && two != -99 && three != -99)
{
cout << "\nEnter integers until you want to stop (-99 to stop): ";
cin >> three;
if (three > one && three > two || three < one && three < two )
{
if (three > one && three > two && three > lownum)
{
highnum = three;
}
else if ( three < one && three < two && three < lownum)
{
lownum = three;
}
}
else if (one > three && one > two || one < three && one < two)
{
if (one > three && one > two)
{
highnum = one;
}
else if (one < three && one < two)
{
lownum = one;
}
}
else if ( two > three && two > one || two < one && two < three)
{
if ( two > three && two > one)
{
highnum = two;
}
else if (two < one && two < three)
{
lownum = two;
}
}
}
cout << "Your lowest number is: "<< lownum << endl << "Your highest number is: " << highnum << endl << endl;
return 0;
}
I am not sure if arrays are the way to go for this type of problem, as we have yet to learn them in our lecture, but I am having some trouble finding the logic behind this looping structure and how to store an infinite number of variables until -99 is entered. Any help is appreciated
The assignment text:
Write a program with a loop that lets the user enter a series of integers. The user should enter -99 to signal the end of the series. After all the numbers have been entered, the program should display the largest and smallest numbers entered.
So far I have taken two different approaches using different combinations of while and for loops, but so far, no dice. Anyone have any suggestions?
Here are the two different versions of the code
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main()
/*
int one, two, three=0;
cout << "Enter your first integer: ";
cin >> one;
cout << "Enter you second integer: ";
cin >> two;
while ( one != -99 && two != -99 && three != -99 )
{
cout << "Enter another integer. To stop the program enter -99: ";
cin >> three;
}
if (one < two && three)
cout << one << endl;
else if (two < one && three)
cout << two << endl;
else if (three < one && two)
cout << three << endl;
return 0;
*/
And here is my second attempt:
int number, number2, number3, counter = 1;
double mul = 1;
cout << "Enter your first number that is not -99";
cin >> number;
while (number !=-99)
{
cout << "Please enter your second number " <<endl<<endl;
cin >> number2;
}
for (number != -99; number != -99; counter ++)
{
cout <<"Please enter another number. ";
cin >> number3;
}
if (number < number2 && number3)
{
cout << "The low number is " << number << endl;
if (number2 < number3)
cout << "The high number is " << number3 << endl;
}
else if (number2 < number && number3)
{
cout<< "The low number is " << number2 << endl;
if (number < number3)
cout << "The high number is " << number3 << endl;
}
else if (number3 < number && number2)
{
cout << "The low numer is " << number3 << endl;
if (number < number2)
cout << "The high number is " << number2 << endl;
}
Your code and your question title is a little bit controversy.
Based on what I understand about your question, you enter a series of numbers, and when -99 is entered the program will output min, max; but your code is keep entering 2 numbers, compare them and produce output until -99 is entered.
Here is just my raw code, it's not tested yet.
int main() {
int max, min, number;
cout << "Enter your number (not -99): ";
cin >> number;
max = number;
min = number;
while(1) {
cout << "Enter your number (-99 to stop): ";
cin >> number;
if (number == -99) { break; }
if (max < number) { max = number; }
if (min > number) {min = number; }
}
cout << "max: " << max << endl;
cout << "min: " << min << endl;
return 0;
}
The following code should work granted a user doesn't enter numbers greater than or less than 1000000.
int max,min,input;
max = -1000000;
min = 1000000;
cout << "Enter number: ";
cin >> input;
while(input!=-99){
if(input<min) min = input;
if(input>max) max = input;
cout << "Enter number: ";
cin >> input;
}
cout << "Max: " << max << endl;
cout << "Min: " << min << endl;
/I encountered this question tonight and came up with this solution/
#include <iostream>
using namespace std;
int main()
{
int inputNum, lownum, highnum;
cout << "Enter as many numbers as you'd like and then I'll show you which\n";
cout << "was highest and which was lowest.\n";
cout << "Enter -99 to end program.\n\n=>";
cin >> inputNum;
//If user enters -99 right away
if (inputNum == -99)
{
cout << "Ok, we'll thanks for playing anyway\n";
cin.ignore(); //This & next line pause program after ending.
cin.get();
return 0;
}
//assign first input number to both high & low values
highnum = inputNum;
lownum = inputNum;
while (inputNum != -99)
{
cout << "Input number\n=>";
cin >> inputNum;
if (inputNum == -99)
{
break;
}
if (inputNum > highnum)
highnum = inputNum;
if (inputNum < lownum)
lownum = inputNum;
}
cout << "Low number was " << lownum << endl;
cout << "High number was " << highnum << endl;
cin.ignore(); //This & next line pause program after ending.
cin.get();
return 0;
}