I'm a novice to c++ programming and currently taking a class as an introduction to programming. I am currently working on a homework project where I input 10 integers and determine whether the numbers are in ascending order or not.
The issue I'm having is that the program always thinks there is a ascension, no matter the input provided. I figured the problem lies in the IsInOrder() function's for loop, however I can't figure out why exactly it isn't working or how to fix it.
Another potential problem is how to determine ascension for all values, for instance if my code worked I think it would count [1, 2, 3, 4, 5, 1, 2, 3, 4, 5] as an ascension, even though it's not.
I've tried searching online and have found a few similar assignment questions, but with no answer to these problems.
Here's the code I have so far:
#include <iostream>
using namespace std;
bool IsInOrder (int numHold[]);
//This portion takes the numeral inputs and outputs the answer
int main()
{
int numHold[10];
bool status;
cout << "Welcome to the Ascension detector 5000" << endl;
cout << "This program will detect whether the numbers you input are in ascending
order" << endl;
cout << "Isn't that neat?" << endl <<endl;
for (int i=0; i < 10;i++)
{
cout << "Please enter a number: ";
cin >> numHold[i];
}
cout << endl;
for(int i=0;i < 10;i++)
{
cout << numHold[i] << endl;
}
status = IsInOrder(numHold);
if (status == true)
{
cout << "The numbers are in ascending order" << endl;
}
else
{
cout << "The numbers are not in ascending order" << endl;
}
system("PAUSE");
return 0;
}
//This function determines whether the inputs are in ascending order
bool IsInOrder (int numHold[])
{
for (int i = 0; i < 10; i++)
{
if (numHold[i] < numHold [i++])
{
return false;
}
else
{
return true;
}
}
}
Appreciate any help in advance and sorry if the code isn't well formatted, the code wasn't copy/pasting well in to the code sample.
in IsInOrder Function, run for loop till i<9 and remove else part and put return true outside the for loop.
Why return true outside the for loop?
Because return true only when you checked all the element, not every time. Take a look at your code you'll get it.
Your IsInOrder routine doesn't check all the values in the array, it returns immediately after encountering two different numbers.
Also, if it would run through the entire array (i.e. when all the numbers would be the same), it would have checked 11 elements by the time it ended instead of 10, and it wouldn't return anything.
bool IsInOrder(int numHold[])
{
bool inOrder = true;
for (int i = 0; i < 9; i++)
{
if (numHold[i] > numHold[i+1])
{
inOrder = false;
break;
}
}
return inOrder;
}
Firstly, the true and false branches are the wrong way round.
Secondly (assuming true/false has been fixed), you conclude that the entire sequence is in the ascending order as soon as you've seen two numbers that are in order. That's not correct: you can't return true until you've examined every pair.
Lastly, the loop's terminal condition is off by one.
bool IsInOrder(int numHold[]) {
for (int i = 0; i < 9; i++) {
if (numHold[i] >= numHold[i+1]) {
return false;
}
}
return true;
}
Related
I am working on a Tic Tac Toe assignment for my class. And I cannot get the while loop to keep looping after it takes in a search number thats already been removed from the Array. Example ;
string array[] = { "1", "2", "3", "4", "5",} ;
if I search for a 5, and it is in there still, it will change it to a "X". But if I search for a 5 again, it will quit the entire loop instead of just asking for another input. I need it to keep asking for an input and keep checking the input until the entire array has been changed to X's and O's.
I have tried a for loop, while loop, and even bools to keep the loop going until all values have been changed. but nothing is working.
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
string array[] = { "1", "2", "3", "4", "5" };
string search;
bool found = true;
bool keeprunning = true;
while (keeprunning) {
// for(int i = 0; i < 6; i++){
while (found) {
cout << "Enter a character to search for: ";
getline(cin, search);
for (int i = 0; i < 5; i++) {
cout << "Items in the array " << array[i] << endl;
if (search == array[i]) {
found = true;
array[i] = "X";
cout << "\nPresent" << endl;
cout << array[i] << endl;
break;
}
if (i == 4) { // i has to be set to 1 less than the size of the array, so that it only fires after
// the array has been scanned through and the inputted value hasn't been found.
cout << "\nNOT PRESENT.\n";
found = false;
break;
}
if (search != array[0] && search != array[1] && search != array[2] && search != array[3] && search != array[4]) {
keeprunning = false;
cout << "\n\nThere are no more available places to change\n\n";
}
cout << "New array data\n";
for (int i = 0; i < 6; i++) {
cout << array[i] << " ";
}
}
}
}
First of all, the while (keeprunning) loop is adding nothing to the solution. You should take that out.
What's happening is that when you search for a string that is not in the array (e.g. because it has been overwritten with an X) you set found = false. This means that while (found) at the top of the loop is no longer true, so the loop (including prompting the user to input a number) stops running.
Without fully understanding your requirement I suspect you need to do 3 things:
Think about how you DO want to terminate the loop, otherwise, your program could run forever. For example, if you input (for example) a q (for quit) you could detect that, perform a break, and exit the loop.
Look into using continue instead of break. A continue instruction stops executing further code within the loop and goes around the loop again.
Use a do-while loop instead of a while loop. A do-while loop executes at least once and tests whether it should go round again at the bottom of the loop. A while loop depends on some condition being true - that's why you had to initialise the value of found to be true.
I am trying to write code that will search a 4 by 4 matrix called matrix[4][4].
Users will be able to type their own values in. At the end it questions the user what value does the user wish to search for. The code I have written will display the wrong message. For example, even if the matrix has a 22 in it the program will say that the matrix does not contain 22. This is the loop that searches the matrix.
int result;
cout << "Which value would you like to search for in the matrix?: ";
cin >> result;
int search = 0;
for (search = 0; search < 4; search++)
{
for (int value = 0; value < 4; value++)
{
if (matrix[search][value] == result)
{
cout << "Your matrix contains " << result << endl;
return search;
}
else
cout << "Your matrix does not contain " << result << endl;
return 0;
}
}
I want the program to display the right output. If user searches for a 30 and the matrix contains a 30, it should not say that the matrix does not contain a 30.
You should reply that the value is not found only after searching all of the matrix.
As Sam Varshavchik said, on the first iteration of the inner loop, it checks to see whether the first element is what is being searched for, or else it tells you that the element was not found, without checking any other value since it then returns 0.
Since you usually don't have the element you're looking for on the first element, you should only say that the value has not been found once the outer loop finishes, and we know that if the loops didn't return anything, then the code will arrive at the section where it tells the user that the element was not found.
So, the loop would look like this:
int search = 0;
for (search = 0; search < 4; search++)
{
for (int value = 0; value < 4; value++)
{
if (matrix[search][value] == result)
{
cout << "Your matrix contains " << result << endl;
return search;
}
}
}
//If the program gets here, it has checked all elements
cout << "Your matrix does not contain " << result << endl;
return 0;
My code uses what I thought would be a simple while loop. It checks if the randCard already exists in the vector I have and, if it does, makes a new randCard.
I've added cout statements within the loop to try to find which processes it's running through and discovered it's only running through the while loop, none of the nested for loops. The problem is as follows:
bool isSame = true;
//Make sure they don't be the same cards
while (isSame){
cout << "While entered" << endl;
for(int i = 0; i < notToUse.size(); i++){
if(randCard == notToUse.at(i)){
randCard = rand() % 24;
}
cout << "First for ran" << endl;
}
for (int i = 0; i < notToUse.size(); i++){
if (randCard == notToUse.at(i)){
cout << "Recheck loop" << endl;
break;
}
else{
cout << "Else ran" << endl;
isSame = false;
}
}
}
randCard is from a class of type Cards. The vector notToUse consists of cards indices that have already been used. The end cout statements end up looking like:
While entered
While entered
While entered
While entered
While entered
It seems like the for loops aren't even accessed. How can I fix this?
For anyone who might stumble upon this, the answer was resolved in the comments. The vector was of size 0, so the for loops didn't even run.
This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 4 years ago.
The goal of this code is to pass an array through a function (which I'm already having a difficult time understanding). I went through with a pen and paper and traced the code and I think I just don't know enough to understand what's going wrong. All the test scores I throw in just push back a ridiculously large negative number. I'm not asking for you guys to do my homework because I really want to try and understand what I'm doing, but any help would really be appreciated right now.
#include <iostream>
//function prototype
double average(int studentScores[], int size);
double studentScores[4];
bool runAgain(void);
int main() {
do {
int studentScores[4], size = 4, result;
string score;
cout << "This program will calculate the average of four diffrent exam scores." << endl;
for (int i = 0; i < size; i++) {
studentScores[i] = 0;
cout << "Please Enter Exam Score " << i + 1 << ": ";
getline(cin, score);
}
for (int i = 0; i < size; i++) {
result = (studentScores[1] + studentScores[2] + studentScores[3] + studentScores[4]) / size;
studentScores[i]++;
}
cout << "The Average Exam score is " << result << endl;
} while (runAgain());
system("pause");
return 0;
}
//function implementation
double average(int studentScores[], int size) {
for (int i = 0; i < size; i++) {
return (studentScores[i]++ / size);
}
}
bool runAgain(void) {
char userResponse;
cout << "\nWould you like to run again (y or n): ";
cin >> userResponse;
if (userResponse == 'y' || userResponse == 'Y')
return(true);
return(false);
}
First obvious bug:
int studentScores[4]
studentScores has 4 elements, numbered studentScores[0] through studentScores[3].
But your code accesses studentScores[4] in
result = (... + studentScores[4]) / ...
which doesn't exist (and doesn't access studentScores[0], which does).
Glad to try to help ya out without giving you the answer.
I'm gonna sprinkle some questions throughout your code that you should be asking yourself in future programs whenever you get unexpected output.
#include <iostream>
//function prototype
double average(int studentScores[], int size);
double studentScores[4];
bool runAgain(void);
int main() {
do {
int studentScores[4], size = 4, result;
string score;
/* Above, you declared a string to store the user's input in.
In C++, the string "4" DOES NOT equal the integer 4.
How will you handle the fact that the variable 'score' is of type
string, but you want to work with integers?
Is there an easy way to get rid of this issue? (hint: use cin)
*/
cout << "This program will calculate the average of four diffrent exam scores." << endl;
/* In the below for-loop, think about what the value of 'score' will be
after each iteration. (Hint, getline replaces the existing value of score).
Also, where is the code that saves the user's inputted numbers to an array?
Learn how to write values to an array http://www.cplusplus.com/doc/tutorial/arrays/
*/
for (int i = 0; i < size; i++) {
studentScores[i] = 0;
cout << "Please Enter Exam Score " << i + 1 << ": ";
getline(cin, score);
}
/* In the for-loop below, you already noticed that your array has random
values in it. The comment about the above for-loop should address that issue.
Equally important though is understanding what the heck is happening in this
loop below. After you fix the bug in the for-loop above (which will
get the values in the array to equal the user's inputs), you'll be faced
with issues in this loop below.
My advice is to understand what happens when the program
executes "studentScores[i]++". First, it gets the number in the array at
the ith+1 position, then it increments that number by 1. Cool, but what
are you doing with the result of that? It's not being put to use anywhere.
Also, note that because the array is never being updated,
the line above it just calculates the same number and stores it in 'result'
every iteration of the loop.
*/
for (int i = 0; i < size; i++) {
result = (studentScores[1] + studentScores[2] + studentScores[3] + studentScores[4]) / size;
studentScores[i]++;
}
cout << "The Average Exam score is " << result << endl;
} while (runAgain());
system("pause");
return 0;
}
// this function doesn't seem to be used, but understanding what
// is wrong with it will help you understand how to code.
// First, note that once a function hits 'return', it will
// never execute any more code in that function.
// So here, your return statement in the for-loop will prevent an
// actual loop from occuring (since the function will exit as soon as the first loop iteration is entered)
// Second, note that you are just getting the value in the array and adding 1 to it
// before dividing it by 'size', which is not the formula for an average.
double average(int studentScores[], int size) {
for (int i = 0; i < size; i++) {
return (studentScores[i]++ / size);
}
}
bool runAgain(void) {
char userResponse;
cout << "\nWould you like to run again (y or n): ";
cin >> userResponse;
if (userResponse == 'y' || userResponse == 'Y')
return(true);
return(false);
}
I hope these comments helped :) Keep at it!
Don't forget that arrays start at index 0. Trying to access studentScores[4]
will give you an unexpected number.
I've recently (very, very recently) have gotten into programming in C++. I'm writing a program to find the highest prime number below prime. However, when I execute the code, nothing is displayed, and in the console it says this:
Process returned -1 (0xFFFFFFFF) execution time : 0.409 s
Press ENTER to continue.
I've tried some debugging, and I've figured out the problematic section is lines 17-19 (the if statement), but I can't figure out what I'm doing wrong.
C++
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
//cout << "maybe here?";
int prime = 1000;
//cout << "here";
while(true){
//cout << "here2";
int testr = ceil(sqrt(prime));
cout << testr;
bool isprime = true;
for(int i = 0; i < testr; i++){
cout << i << " ";
if(testr % i == 0){
isprime = false;
}
}
if(isprime){
break;
}else{
prime--;
}
}
cout << prime;
}
Any and all help is appreciated! Thanks!
Additional Info:
I'm using Code::Blocks on Mac OSX 64 bit. I'm used to programming in Java, so it may just be a C++ thing I'm unaware of.
Quite a few issues.
1) The answer to your question "find the lowest prime number below prime" is 2, no programming required.
2) Assuming you want to find the greatest prime number below prime, you should test all numbers from prime - 1, downwards.
3) The very first iteration of your loop:
for(int i = 0; i < testr; i++){
cout << i << " ";
if(testr % i == 0){
will cause an exception: division by 0.
The reason is that you are trying to divide by 0 in your for loop you should begin with 2. Take a look at this one, it's optimal I guess.
bool isPrime(int n) {
if(n<2)
return false;
for(int i=2;i*i<=n;i++)
if(n%i==0)
return false;
return true;
}