Looping Confusion - c++

My code seems to ask twice instead of once if I want to run the code again. I just want it to run normally like my other cases which only ask once after I have viewed the activity and these two activities are the only ones with problems. What seems to be the problem here:
case 5:
cout<<"Here are the list of activities in Activity 5:" << endl;
cout<<"[5.1]Determining a Number within the Array" << endl;
cout<<"[5.2]Determining the Highest and Lowest integer" << endl;
cout<<"[5.3]Reversed Array" << endl;
cin >> choice;
system("CLS");
if(choice == 5.1){
counter +=1;
int nos[10];
int det;
cout <<"Note: Do not input any decimal numbers." << endl;
for(int array = 1; array < 11; array++){
cout << "Input integers 1-10 only. [" << array << "]";
cin >> nos[det];
}
cout << "Type in 1 integer value only.[" << det << "]";
cin >> det;
if(det >= nos[1] || det <= nos[10]){
cout << "The value is within the scope of the array.";
}
else{
cout << "The value is not within the scope of the array.";
}
system ("PAUSE");
system ("CLS");
cout << "Do you want to run the program again? (y/n)" << endl;
cin >> choose;
}
else if(choice == 5.2){
counter +=1;
cout <<"Note: Do not input any decimal numbers." << endl;
cout <<"Enter your integers." << endl;
int nos[10];
int put;
for(int rep = 1; rep < 11; rep++){
cout <<"[" << rep << "]";
cin >> nos[rep];
}
int highnos = nos[1];
int lownos = nos[1];
for(int rep = 1; rep < 11; rep++){
if(nos[rep] > highnos){
highnos = nos[rep];
}
}
cout << "Your highest integer is:" << highnos << endl;
for(int rep = 1; rep > 11; rep++){
if(nos[rep] < lownos){
lownos = nos[rep];
}
}
cout <<"Your lowest integer is:"<< lownos << endl;
system ("PAUSE");
system ("CLS");
cout << "Do you want to run the program again? (y/n)" << endl;
cin >> choose;
}
P.S. my activities also has errors but dont mind it :D

First of all, you haven't initialized anything so everything is taking garbage values.
initialize det first and if you want to input the whole array then run a loop. cin>>nos[det] only inputs one value at a garbage index according to your code.
This code is a mess. Kindly fix initializations and inputs, then share the output you're getting vs the output you want.

Related

How do I change a char's values?

I've created a program and it runs, however there are two problems. 1) Char doesn't change values as it should. 2) One of my total variables is stuck on one.
I've tested the code multiple times, and the char deptID is stuck on 'B'. I've tried going through the workflow and it's stuck on the value. Just to make sure, I wrote a cout line to check it throughout the workflow. Regardless of what I input, it's stuck on 'B'.
2) The variable TechTotal is seemingly stuck on 1. I've tested it using different values as well. I also went ahead and used a cout line to determine the value throughout the workflow to no success. I've made sure the variables are correct in calculating the variable. Both are correct.
Here's my main code:
int main(int argc, char** argv) {
welcomeScreen();
long int empID;
int TechAccAvg, TechTixAvg;
int BusTotal, TechTotal, BusAccAvg, BusTixAvg;
char deptID;
for (int i=0; i < 2; i++)
{
cout << "What department are you apart of?\n";
cin >> deptID;
if (deptID = 'B')
{
auto Averages = gatherData(deptID);
BusTixAvg = std::get<0>(Averages);
BusAccAvg = std::get<1>(Averages);
cout << BusTixAvg << endl;
cout << BusAccAvg << endl;
BusTotal = BusTixAvg + BusAccAvg;
cout << "Bus Total: " << BusTotal << endl;
}
else if (deptID = 'T')
{
auto TechAverages = gatherData(deptID);
TechTixAvg = std::get<0>(TechAverages);
TechAccAvg = std::get<1>(TechAverages);
cout << TechTixAvg << endl;
cout << TechAccAvg << endl;
TechTotal = TechTixAvg + TechAccAvg;
cout << "Tech Total: " << TechTotal << endl;
}
}
cout << "Tech: " << TechTotal << endl;
cout << "Business: " << BusTotal << endl;
summaryReport(TechTotal, BusTotal);
goodByeScreen();
return 0;
}```
` std::tuple<int, int> gatherData (char dept)
{
tuple <double, double> Averages;
int employeeNum=0, TotalTix=0, TotalAcc=0, trafficTickets=0, accidents=0;
long int empID=0;
double TixAverage=0, AccAverage=0;
char deptID;
cout << dept << endl;
cout << "How many employees do you have?\n";
cin >> employeeNum;
for(int j = 0; j < employeeNum; j++)
{
cout << "Please enter your employees ID number\n";
cin >> empID;
cout << "How many tickets did they have this year?\n";
cin >> trafficTickets;
TotalTix += trafficTickets;
cout << "How many accidents did they have this year?\n";
cin >> accidents;
TotalAcc += accidents;
}
TixAverage = TotalTix / employeeNum;
AccAverage = TotalAcc / employeeNum;
cout << "Department: " << dept << endl;
cout << "Total employees: " << employeeNum << endl;
cout << "Total tickets: " << TotalTix << endl;
cout << "Total Accidents: " << TotalAcc << endl;
Averages = make_tuple (TotalTix, TotalAcc);
return Averages;
}```
This is used to create the tuple that is used in determining Totals for both 'B' and 'T' depts.
Fixing both the char dept and the TechTotal would fix the entire program, I think. Those are the only things holding the program back. I've been stuck on this problem for a few hours now and I'm kind of lost as to why it's not changing those values. Any help would be appreciated, thank you in advance!
Solution
Replace else if (deptID = 'T') with else if (deptID == 'T') and if (deptID = 'B') with if (deptID == 'B').
Explanation
The single equal sign = means assignment. Therefore, everytime the program runs, deptID will be assigned to B and the statement will return true, satisfying the if statement.
However, you want to compare two values to see if they are equal. Therefore, you must use == (equality).
Because the statements in the else if will never execute, TechTotal will remain uninitialised, and the value in that memory address just so happens to be 1.

Why aren't my two cin statements running towards the end of the program?

I am a first year cs major. Today in our lab we had to debug some code and make it work. Below is the result.
#include <iostream>
using namespace std;
int main() {
int x = 3, y;
char myanswer;
int val= 1;
int num;
y = x;
cout << "y is set to: " << y << endl;
bool again = true;
int ans;
while (again) {
cout << "Please input a number: ";
cin >> y;
if (x > y)
cout << "X is greater than Y\n";
else {
cout << "X is less than Y" << endl;
cout << "would you like to input another number?" << endl;
cin >> ans;
if (ans != 1)
break;
}
cout << "would you like to input another number ?" << endl;
cin >> ans;
if (ans != 1)
again = false;
}
for (x = 0; x < 10; x++)
cout << x << endl;
cout << "What number would you like to find the factorial for? " << endl;
cin >> num;
cout << num;
for (int x = num; x > 0; x--) {
val *= x;
}
cout << "Are you enjoying cs161? (y or n) " << endl;
cin >> myanswer;
if (myanswer == 'y')
cout << "Yay!" << endl;
else
cout << "I hope you will soon!" << endl;
return 0;
}
After the cout regarding factorials, the cin's don't work and the user ceases to be able to enter input. So far my lab ta's and friends haven't been able to find the issue. The code has been compiled and exected on both my school's engineering servers and my local computer. On both the error persists.
almost certainly this caused an overflow
for (int x = num; x > 0; x--) {
val *= x;
}
what did you enter for num?
When you have a statement as:
cout << "would you like to input another number?" << endl;
The first instinct for the user would be to type y or n as an answer. You can help the user by providing a hint.
cout << "would you like to input another number (1 for yes, 0 for no)?" << endl;
If you do that, it would be better to be consistent throughout your program. The next prompt that seeks a y/n response must use the same mechanism.
cout << "Are you enjoying cs161? (1 for yes, 0 for no) " << endl;
Of course, always validate input operations before proceeding to use the data.
if ( !(cin >> ans) )
{
// Input failed. Add code to deal with the error.
}

How do you make a counter to count the number of even and odd numbers entered by user?

I have this code so far that is supposed to keep asking the user for a number until they type 0. Then the program will tell the user how many odds and evens they typed. I cannot get the latter function to work correctly. Any tips? I am a beginner, so please no advanced ways to solve this :D
#include <iostream>
using namespace std;
int main ()
{
int n;
int myCounter1, myCounter2;
cout << "Odds and Evens\n\n" << endl;
do
{
cout << "Please enter an integer: ";
cin >> n;
myCounter1 = 0;
myCounter2 = 0;
if (n%2 == 0)
{
myCounter1++;
}
else
{
myCounter2++;
}
}
while (n!=0);
cout << "You entered " << myCounter1 << " even numbers, and " << myCounter2 << "odd numbers " << endl;
return 0;
}
A couple things:
Code indentation (or lack thereof) makes this really hard to read. Indentation is not only cosmetic, but can help in understanding code.
You are setting the counter variables to zero each time the loop runs. Declare them outside of the loop so they retain their values.
The else clause of the if statement has erroneous syntax. Use a simple else instead, as there are only two cases for the parity of n.
When the user types 0 to exit the loop, it too is counted as an even integer. Add a condition in the if statement to account for this.
Applying these changes yields this code:
int n;
int myCounter1 = 0, myCounter2 = 0;
cout << "Odds and Evens\n\n" << endl;
do {
cout << "Please enter an integer: ";
cin >> n;
if (n%2 == 0 && n != 0)
{
myCounter1++;
}
else
{
myCounter2++;
}
} while (n!=0);
cout << "You entered " << myCounter1 << " even numbers, and " << myCounter2 << "odd numbers " << endl;
This
else n == 0
{
myCounter2++;
}
should be
else
{
myCounter2++;
}
Honestly, I don't even know why it didn't grab your attention, since it can't compile.
Also, you shouldn't set the counters to zero in the loop. So
int myCounter1, myCounter2;
cout << "Odds and Evens\n\n" << endl;
do
{
cout << "Please enter an integer: ";
cin >> n;
myCounter1 = 0;
myCounter2 = 0;
should be
int myCounter1=0, myCounter2=0;
cout << "Odds and Evens\n\n" << endl;
do
{
cout << "Please enter an integer: ";
cin >> n;
And, finally, since you probably shouldn't count the 0 as one of the integers entered...
cout << "You entered " << myCounter1-1 << " even numbers, and " << myCounter2 << " odd numbers " << endl;
You have 2 bugs and 1 syntax error.
line:else n == 0 should be simply else
The 2 bugs are related to your counters:
1) You have to exclude the 0 input from the counters.
2) Every time you are reading a number your are setting them (the counters) to zero, which means that you will always ending with zero and one.
Here it is for anyone interested:
include
using namespace std;
int main ()
{
int n;
int myCounter1 = 0;
int myCounter2 = 0;
cout << "Odds and Evens\n\n" << endl;
do
{
cout << "Please enter an integer: ";
cin >> n;
if (n%2 == 0)
{
myCounter1++;
}
else
{
myCounter2++;
}
}
while (n!=0);
cout << "You entered " << myCounter2 << " odd numbers, and " << myCounter1-1 << " even numbers " << endl;
return 0;
}

C++ Input and Output problems

My problem is that when i compile and run the program, the hours doesnt have "hours" listing 1,2,3 as the loop continues and also the loop calculation is the same for each line.
this is what the program looks like
http://postimg.org/image/htk194eah/
the calculation is wrong and the hours is suppose to say 1,2...5
I would like it to look something like this
http://postimg.org/image/pnkvab1j1/
this is what i have so far:
int main()
{
// Variables
int speed;
int time;
int distance;
// Obtain the speed
cout << "Please input the speed of the vehicle " ;
cin >> speed;
while(speed < 0) // while statement
{
cout << "Please refrain from using a negative number ";
cin >> speed;
}
cout << "Please enter the time, represented in hours, travelled" <<endl;
cin >> time;
// Obtain the time
while(speed < 1)
{
cout<< "Please use a number greater than 1 " <<endl;
cin >> time;
}
// Calculation
distance = speed * time;
cout << endl;
cout << "Hour(s) " << "\t" << "Distance Travelled" << endl;
cout << "____________________________________________" << endl;
// "for" Loop statement
for(int count =1; count <= time; count++)
{
cout << " " << "\t\t" << speed*time << endl;
}
system ("PAUSE");
return 0;
}
When you print in your for loop, speed = 20 and time = 5 always, so it always prints 100 (in the example you give).
You want to be printing speed*count (in this case).
Again you print "" for the hours, which is an empty string, you want to be printing count.
cout << count << "\t\t" << speed*count << endl;
Here is the correct program. Your program was very good. But you have a very small mistake.
#include<iostream.h>
main()
{
// Variables
int speed;
int time;
int distance;
// Obtain the speed
cout << "Please input the speed of the vehicle " ;
cin >> speed;
while(speed < 0) // while statement
{
cout << "Please refrain from using a negative number ";
cin >> speed;
}
cout << "Please enter the time, represented in hours, travelled ";
cin >> time;
// Obtain the time
while(speed < 1)
{
cout<< "Please use a number greater than 1 ";
cin >> time;
}
// Calculation
cout << endl;
cout << "Hour(s) " << "\t" << "Distance Travelled" << endl;
cout << "____________________________________________" << endl;
// "for" Loop statement
for(int count =1; count <= time; count++)
{
cout << count << "\t\t" << speed * count << endl;
}
system ("PAUSE");
return 0;
}

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