C++ part 8 – While loop

I have written a code that is a bit different than the java code. Below is the code:
#include <iostream>
using namespace std;
int main()
{

int user_input, computer_number = 15;
string choice;

do {
cout << “Enter the first integer: ” << endl;
cin >> user_input;

if(user_input == computer_number) {
cout << user_input << “==” << computer_number << endl;
}else if(user_input < computer_number) {
cout << user_input << “<” << computer_number << endl;
}else if(user_input > computer_number) {
cout << user_input << “>” << computer_number << endl;
}

cout << “Do you want to continue(y/n)?: ” << endl;
cin >> choice;
}while(choice == “y” || choice == “Y”);

system(“PAUSE”);
return 0;
}

and below is the output picture

blabla

And I also have another version of the above code

#include <iostream>

using namespace std;
int main()
{

int user_input, computer_number = 15;
string choice;

do {

cout << “Enter the first integer: ” << endl;
cin >> user_input;

if(user_input == computer_number) {
cout << user_input << “==” << computer_number << endl;
}else if(user_input < computer_number) {
cout << user_input << “<” << computer_number << endl;
}else if(user_input > computer_number) {
cout << user_input << “>” << computer_number << endl;
}

cout << “Type exit to end the program, else type anything to continue: ” ;
cin >> choice;

}while(choice != “exit” || choice == “EXIT”);

system(“PAUSE”);
return 0;
}

Below is a while loop code similar to the Java example that we went through in the previous post:

#include <iostream>
using namespace std;
int main()
{
int x = 0;

while(x <= 100) {
cout << x << endl;
x++;
}

system(“PAUSE”);
return 0;
}

with the output

Image

but I thought to make it more interesting to add something little more different for example, what would happen if we would not have any functions for the x variable like in the below code and output picture

#include <iostream>
using namespace std;
int main()
{
int x = 0;

while(x <= 100) {
cout << x << endl;
}

system(“PAUSE”);
return 0;
}

below is the output

Image

where basically what happens is that because x never has the increment functionality, the compiler will go through the loop forever printing 0’s until you terminate the whole program.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s