I'm having a problem on this one. using a for loop i need to make a user guess a number from 1-10 with only three tries,,, the correct number is 3 . It's running and all but it keeps showing the cout 'Your password is correct' & Program Over everytime. suggestions pls.
First of all: read this about using code-tags !! Then learn how to indent your code.
There's a lot wrong with this code. I've commented in red:
#include<iostream.h> // should be <iostream> without the .h
main() // should be int main()
{
int i, pass; // always give your vars a value: int i=0,pass=0;
cout<<"\n\t Enter a number:";
// this loop does nothing because i=1 and it loops until i is smaller then or equal to one, wich will happen on the first pas
for(i=1;i<=1;i++)
{
cin>>pass;
} // you probably don't want this brace here. It ends your loop.
{ // <-- useless brace
if (pass==3)
{
cout<<"\n\t The password you entered is correct";
}
else
// From here on, everything is wrong.
// You don't need to write the same code over and over again.
// That's what loops are for
{
cout<<"\n\t Enter a number:";
cin>>pass;
}
if (pass==3)
{
cout<<"\n\t The password you entered is correct";
}
else
{
cout<<"\n\t Enter a number:";
cin>>pass;
i++; // <--- don't do this. I is incremented by the for-loop
}
{// <-- useless brace
cout<<"\n\t Program Over!!!";
}// <-- useless brace
}// <-- useless brace
return 0;
}
I strongly recommend that you read this tutorial on loops . It is obvious that you don't understand them very well.
Here's something to get you started. Try it and play around with it.
#include <iostream>
using std::cin;
using std::cout;
int main(){
for (int i = 0; i < 3; i++){ // loop 3 times
int user_number = 0;
cout << "Enter a number: ";
cin >> user_number;
cout << "Number " << i+1 << " entered was: " << user_number << '\n';
}
}
You're probably using the Ancient Turbo C++ compiler. If this is the case, change the above code to :
#include <iostream.h>
int main(){
for (int i = 0; i < 3; i++){ // loop 3 times
int user_number = 0;
cout << "Enter a number: ";
cin >> user_number;
cout << "Number " << i+1 << " entered was: " << user_number << '\n';
}
}
And when you're done trying the code, upgrade your compiler to some free, and up-to-date
Nick Evan
Not a Llama
Moderator
10,112 posts since Oct 2006
Reputation Points: 4,142
Solved Threads: 403