Вы находитесь на странице: 1из 44

The goto statement in c++

We have gone through the while loop, for loop and do-while loop. The another way to do loop in c++ is through using the goto statement. The goto statement was used in olden days but it is not suitable for creating modern applications. But since c++ supports it, you should have knowledge about it, as you may encounter a c++ source code containing goto statements, in that case you will know what it is and how it works.

How the goto statement works?


It consist of label and statements that comes under that label. A label is named by you and it is followed by a colon sign (:). During execution of program, when goto is encountered, it jumps to the statements that comes under the label specified by goto statement. To get a clear idea, analyze the below program example.

/* A c++ program example that uses goto statement to display number from 0 to 9 */

#include <iostream> using namespace std; int main () { int i=0; loop: cout << i << endl; i++; if (i<10) goto loop; return 0; }

Why goto should not be used?


The use of goto should be avoided to make the program more readable and reliable. The goto statement can cause the program execution to jump to any location in source code and in any direction backward or forward. This makes the program hard to read and understand and also makes it difficult to find bugs.

Since now we have more tightly controlled and sophisticated loops like while loop, for loop and do-while loop, the use of obsolete statement like goto is not at all recommended in creating loops. Please do comment if you don't understand any part or want to know more or just want to say thanks. I love programming and love to teach my friends. Your suggestions and appreciation will make this blog much better. Want to learn more? View List Of All Chapters Posted by Mohammed Homam at 8:33 AM 5 comments Labels: c++ example, c++ program, c++ programming, goto statement

Tuesday, October 25, 2011


Repetition Statement: The Do-While Loop in c++

Repetition Statement: The Do-While Loop in c++


We have already gone through The While Loop and The For Loop. Now its time for The DoWhile Loop.

/* A c++ program example that uses do-while loop to display number from 0 to 9 */
// Program 1 #include <iostream> using namespace std; int main () { int i = 0; do { cout << i << endl; i++; } while (i < 10); return 0; }

The do-while loop works just like the for loop and while loop but with one exception. Unlike the for loop and while loop, the do-while loop will execute at least once. The for loop and the while loop checks the condition and then the body of loop executes but in case of do-while, the body is executed first and then it checks the condition.

/* A c++ program example that demonstrates how do-while loop distinguishes from the for loop and while loop */
// Program 2 #include <iostream> using namespace std; int main () { // The while loop int i = -1; while (i != -1) { cout << "Inside the while loop. " << endl; cout << "Please enter a number or -1 to quit: "; cin >> i; } // The for loop int j = -1; for (; j != -1; ) { cout << "Inside the for loop. " << endl; cout << "Please enter a number or -1 to quit: "; cin >> j; } // The do-while loop int k = -1; do { cout << "Inside the do-while loop. " << endl; cout << "Please enter a number or -1 to quit: "; cin >> k; } while (k != -1); return 0; } When you run the above program, only the body of do-while gets executed and others do not. The initial value is set to -1 and the condition is such that the value should not be equal to -1. The for loop and while loop checks the condition first and hence their body is not executed, the do-while loop executes the body first and hence it gets executed even though the condition is false, as it checks the condition after executing the body.

Use Do-While when you want the body of the loop to execute at least once, even if the condition is false at the start or else you could make use of the for loop and while loop. Posted by Mohammed Homam at 11:56 PM 2 comments Labels: c++ programming, looping statement, repetition statement, the do while loop

Thursday, June 23, 2011


Repetition Statement: The For Loop in c++

Repetition Statement: The For Loop in c++


To understand this you must first go through The While loop in c++. The below program, Program 1 does the same thing that the Program 1 of previous chapter The While Loop does. An integer i is declared and then three expression of the loop: initializer, loop-test and counting expression, all are passed as parameters in for loop. The variable i is initialized to 0 then it will test the condition whether the value of i is less than 10. If the condition is true, the body of loop will execute. The incrementation statement will be last statement to be executed by the for loop.

/* A c++ program example that uses for loop to display number from 0 to 9 using incrementation in the loop */
// Program 1 #include <iostream> using namespace std; int main () { int i; for (i=0; i<10; i++) { cout << i << endl; } return 0; } If you are just going to use the variable within the body of loop, then better declare it in the for loop itself. This will make your program more reliable. The below programs declare variable in the for loop.

/* A c++ program example that uses for loop to display multiplication of 8*/

// Program 2 #include <iostream> using namespace std; int main () { for (int i=8; i<=80; i+=8) cout << i << endl; return 0; }

/* A c++ program example that tells you whether the number is even or odd. Number ranges from 1 to 20. */
// Program 3 #include <iostream> using namespace std; int main () { for (int i=1; i<=20; i++) { if (i%2==0) cout << i << "is an even number." << endl; else cout << i << "is an odd number." << endl; } return 0; } The operator "%" is called the remainder/modulo operator as already been described in Mathematical Operators. The statement i%2==0 simply means that the remainder of i divided by 2 equals to 0.

/* A c++ program example that uses for loop to diplay the square root and cube of numbers from 1 to 10. */
// Program 4

#include <iostream> #include <iomanip> using namespace std; int main () { cout << "Number " << "Square " << "Cube" << endl; for (long i=1; i<=10; i++) { cout << setw (2) << i << setw (8) << i*i << setw (8) << i*i*i << endl; } return 0; }

/*A c++ program example that displays multiplication table of a number provided by the user.*/
// Program 5 #include <iostream> #include <iomanip> using namespace std; int main () { int number; cout << "Enter a number to get its multiplication table: "; cin >> number; cout << endl; cout << "-------------" << endl; for (int i=1; i<=10; i++) { cout << number << " x " << setw (2) << i << " = " << setw (3) << number*i << endl; cout << "-------------" << endl; } return 0; }

Posted by Mohammed Homam at 11:11 AM 7 comments

Monday, May 23, 2011


Repetition Statement: The While Loop in c++

Repetition Statement: The While Loop in c++


The fundamental to programming are control statements. You must learn to have good command over control statement, if you want to program. Sequence, selection and repetition are three types of control statement. It specifies the order in which the statement are executed. (1) Sequence Structure: The sequence structure is built into c++. The c++ statement are executed in sequence, that is one after the other if not directed otherwise. Hope you know this. If not then remember from now on. (2) Selection Statement: Selection statement are of three types: if, if-else and switch statement. We have already learned these in previous chapters. (3) Repetition Statement: Repetition statement are of three types: while loop, for loop and do-while loop. We have to learn about these in this and coming chapters. In programming, often the situation arises in which you have to repeatedly execute a particular code or set of codes. Suppose you want to print your name to the console five times. What you will do? If you have no knowledge of repetition statement, you will write your name in cout 5 times. Something like below:

/* A c++ program example that should have been written using repetition statements */
// Program 1 #include <iostream> using namespace std; int main () { cout << "Mohammed Homam" << endl; cout << "Mohammed Homam" << endl; cout << "Mohammed Homam" << endl; cout << "Mohammed Homam" << endl; cout << "Mohammed Homam" << endl; return 0;

} But what if you have to print it 100 or 1000 times? It would be bothersome and also the code will be too lengthy if we use the above method. To simplify such task we use repetition statement.

The While Loop

/* A c++ program example that uses while loop to print the name 5 times using incrementation in the loop */
// Program 2 #include <iostream> using namespace std; int main () { int i = 0; while (i < 5) { cout << "Mohammed Homam" << endl; i++; }

return 0; } Now lets analyse that what's happening in the above program. Look at the program while reading the each statement of explanation. We declared an integer i and intialised it to 0. After that while loop checks whether i is less than 5. Currently the value of i is 0 and hence the condition i<5 is true. Since the condition is true, the body of while is executed. The body of while loop contains two statement: one that displays the name and other that increments the value of i by 1. After executing the increment statement, now the new value of i is 1. The while loop will again check the condition and since 1 is less than 5 the body of while will execute again. This will go on until the value of i is incremented to 5. Once the value of i is 5, the condition will become false as a result of which the body of loop won't execute and will terminate. What's the use of increment statement in the above program? If you don't increment the value of i in the above program, then value of i will always be 0 and hence the condition i < 5 will also be always true. It means your loop will never stop, it will go on and on. This is called infinite loop. Try this by removing i++; from above program. Compile and run it again. Press ctrl+c to terminate the program.

/* A c++ program example that uses while loop to print the name 5 times using decrementation in the loop */
// Program 3 #include <iostream> using namespace std; int main () { int i = 5; while (i > 0) { cout << "Mohammed Homam" << endl; i--; } return 0; }

The above program does the same thing as its above program. The logic used is different. Here we gave the intial value to i as 5. Now the condition is, that i must be greater than 0. As the body of while loop is executed each time, the value of i is decremented by 1. The loop terminates when the value of i becomes 0.

/* A c++ program example that uses while loop to print number from 0 to 9 using incrementation in the loop */
// Program 4 #include <iostream> using namespace std; int main () { int i = 0; while (i < 10) { cout << i << endl; i++; } return 0; }

/* A c++ program example that uses while loop to print number from 0 to 9 using decrementation in the loop */
// Program 5 #include <iostream> using namespace std; int main () { int i = 9; while (i >= 0) { cout << i << endl; i--; } return 0; } The above program were simplest one's to get started into looping. In the next chapter we will learn about the for loop. Posted by Mohammed Homam at 5:33 AM 7 comments

Thursday, December 9, 2010


Conditional (Ternary) Operator in c++ [? :]

Conditional (Ternary) Operator in c++ [? :]


The condional operator can often be used instead of the if else statement. Since it is the only operator that requires three operands in c++, it is also called ternary operator. For example, consider the assignment statement : x = y > 3 ? 2 : 4; If y is greater than 3 then 2 will be assigned to variable x or else the value 4 will be assigned to x.

/* A simple c++ program example to demonstrate the use of ternary operator. */


// Program 1

#include <iostream> #include <iomanip> using namespace std; int main () { int first, second; cout << "Enter two integers." << endl; cout << "First" << setw (3) << ": "; cin >> first; cout << "Second" << setw (2) << ": "; cin >> second; string message = first > second ? "first is greater than second" : "first is less than or equal to second"; cout << message << endl; return 0; }

Compare the above "Program 1" and below "Program 2" with "Program 2" and "Program 3" of Selection Statement (if-else if-else) in c++ respectively, for better understanding.

/* A c++ program example to demonstrate the use ternary operator.*/


// Program 2

#include <iostream> #include <iomanip> using namespace std; int main () { int first, second; cout << "Enter two integers." << endl; cout << "First" << setw (3) << ": "; cin >> first;

cout << "Second" << setw (2) << ": "; cin >> second; string message = first > second ? "first is greater than second" : first < second ? "first is less than second" : "first and second are equal"; cout << message << endl; return 0; } Posted by Mohammed Homam at 7:41 AM 3 comments Labels: c++ example, c++ operators, c++ programming, c++ programs, c++ source code, ternary operator

Saturday, November 27, 2010


The switch statement in c++

The switch statement in c++


The program that we create should be readable. To increase the readability of the program we should use tools that is simple to read and understand. When possible use switch statement rather than if else statement, as it can be more readable than if else statement. But switch statement has limitation. It can't replace if else completely but can be helpful at certain situation. It can't do everything thing that if else statement can do. For example, switch statement can take only int or char datatype in c++. The following programs will help you to understand the switch statement.

/* A simple c++ program example that demonstrate the use of switch statement in c++ by taking character input.*/
// Program 1

#include <iostream> using namespace std; int main () { char permit; cout << "Are you sure you want to quit? (y/n) : "; cin >> permit;

switch (permit) { case 'y' : cout << "Hope to see you again!" << endl; break; case 'n' : cout << "Welcome back!" < < endl; break; default: cout << "What? I don't get it!" << endl; } return 0; }

/* A c++ program example that demonstrate the use of switch statement in c++ by taking integer input. */
// Program 2 #include <iostream> #include <iomanip> using namespace std; int main () { const int CHEESE_PIZZA = 11; const int SPINACH_PIZZA = 13; const int CHICKEN_PIZZA = 14; cout << " *********** MENU ***********" << endl; cout << setw (9) << "ITEM" << setw (20) << "PRICE" << endl; cout << " (1) Cheese Pizza" << setw (8) << "$" << CHEESE_PIZZA << endl; cout << " (2) Spinach Pizza" << setw (7) << "$" << SPINACH_PIZZA << endl; cout << " (3) Chicken Pizza" << setw (7) << "$" << CHICKEN_PIZZA << endl; cout << endl; cout << "What do you want? "; int option; cin >> option; cout << "How many? "; int quantity;

cin >> quantity; int price; switch (option) { case 1: price = CHEESE_PIZZA; break; case 2: price = SPINACH_PIZZA; break; case 3: price = CHICKEN_PIZZA; break; default: cout << "Please select valid item from menu. " << endl; return 1; } int amount = price * quantity; cout << "Your Bill: $ " << amount << endl; return 0; }

Explanation for the above program:


In the above program we take an integer value from the user which is stored in 'option' variable. We pass this value to switch statement. The switch statement has 3 cases: case 1, case 2 and case 3. The case 1: is similar to if (option == 1). This is the advantage of switch statement over if else statement. You don't need to type the name of variable again and again if you are doing selection operation on same variable. You just put the variable name on switch statement and then just specify the value after 'case'. One more thing to be noted is that it requires 'break' statement at the end of each 'case'. If you remove the break statement then it will jump to the case that follows it. Try it and check by yourself. The 'default' is same as else in if else statement. Posted by Mohammed Homam at 12:23 PM 6 comments Labels: c++ programming, c++ examples, c++ programs, learn c++, switch statement

Monday, September 20, 2010


Logical Operators: AND(&&) OR(||) NOT(!) in c++

Logical Operators: AND(&&) OR(||) NOT(!) in c++

To understand this chapter better, first go through relational operators. In a program, we often need to test more than one condition. To simplify this logical operators were introduced. In your school you might have learnt Boolean Algebra (Logic).

The three logical operators ( AND, OR and NOT ) are as follows:


1) AND (&&) : Returns true only if both operand are true. 2) OR (||) : Returns true if one of the operand is true. 3) NOT (!) : Converts false to true and true to false. Operator Operator's Name && && && || || || ! ! AND AND AND OR OR OR NOT NOT Example Result

3>2 && 3>1 1(true) 3>2 && 3<1 0(false) 3<2 && 3<1 0(false) 3>2 || 3>1 3>2 || 3<1 3<2 || 3<1 !(3==2) !(3==3) 1(true) 1(true) 0(false) 1(true) 0(false)

/* A c++ program example that demonstrate the working of logical operators. */


// Program 1 #include <iostream> using namespace std; int main () { cout << "3 > 2 && 3 > 1: " << (3 > 2 && 3 > 1) << endl; cout << "3 > 2 && 3 < 1: " << (3 > 2 && 3 < 1) << endl; cout << "3 < 2 && 3 < 1: " << (3 < 2 && 3 < 1) << endl; cout << endl;

cout << "3 > 2 || 3 > 1: " << (3 > 2 || 3 > 1) << endl; cout << "3 > 2 || 3 < 1: " << (3 > 2 || 3 < 1) << endl; cout << "3 < 2 || 3 < 1: " << (3 < 2 || 3 < 1) << endl; cout << endl; cout << "! (3 == 2): " << ( ! (3 == 2) ) << endl; cout << "! (3 == 3): " << ( ! (3 == 3) ) << endl; return 0; }

In earlier chapter Selection Statement (if-else if-else), we were required to check two conditons: for username and password. If both username and password are correct then only "You are logged in!" message appears. We checked these two condition using nested if-else statement. However i told you at the end of that chapter that in the "Program 1" nesting can be avoided by using logical operator. Here we will rewrite the "Program 1" of Selection Statement (if-else if-else) using logical operator.

/* A c++ program example that uses a logical operator in selection statement if-else.*/
// Program 2 #include <iostream> #include <string> using namespace std; const string userName = "computergeek"; const string passWord = "break_codes"; int main () { string name, pass; cout << "Username: "; cin >> name; cout << "Password: "; cin >> pass; if (name == userName && pass == passWord) { cout << "You are logged in!" << endl; } else cout << "Incorrect username or password." << endl;

return 0; }

/* A simple c++ program example that uses AND logical operator */


// Program 3 #include <iostream> #include <iomanip> using namespace std; int main () { int first, second, third; cout << "Enter three integers." << endl; cout << "First "<< setw (3) << ": "; cin >> first; cout << "Second "<< setw (2) << ": "; cin >> second; cout << "Third "<< setw (3) << ": "; cin >> third; if (first > second && first > third) cout << "first is greater than second and third." << endl; else if (second > first && second > third) cout << "second is greater than first and third." << endl; else if (third > first && third > second) cout << "third is greater than first and second." << endl; else cout << "first, second and third are equal." << endl; return 0; }

/* A simple c++ program example that uses OR logical operator*/

// Program 4 #include <iostream> using namespace std; int main () { char agree; cout << "Would you like to meet me (y/n): "; cin >> agree; if (agree == 'y' || agree == 'Y') { cout << "Your name: "; string name; cin >> name; cout << "Glad to see you, "+name << endl; } else if (agree == 'n' || agree == 'N') cout << "See you later!" << endl; else cout << "Please enter 'y' or 'n' for yes or no." << endl; return 0; }

/* A simple c++ program example that uses NOT logical operator*/


// Program 5 #include <iostream> using namespace std; int main () { char agree; cout << "Would you like to meet me?" << endl; cout << "Press 'y' for yes and any other character for no: "; cin >> agree;

if ( ! (agree == 'y' || agree == 'Y') ) { cout << "See you later!" << endl; } else { cout << "Your name: "; string name; cin >> name; cout << "Glad to see you, "+name << "!" << endl; } return 0; }

Nested if-else statements in c++

Nested if-else statements in c++

/*A c++ program example that takes input from user for username and password and then makes decision.*/
// Program 1 #include <iostream> #include <string> using namespace std; const string userName = "computergeek"; const string passWord = "break_codes";

int main () { string name, pass; cout << "Username: "; cin >> name; cout << "Password: ";

cin >> pass; if (name == userName) { if (pass == passWord) cout << "You are logged in!" << endl; else cout << "Incorrect username or password." << endl; } else cout << "Incorrect username or password." << endl; return 0; }

/*A c++ program example that takes input from user for username and if username is correct then only asks for password and makes decision.*/
// Program 2 #include <iostream> #include <string> using namespace std; const string userName = "computergeek"; const string passWord = "break_codes"; int main () { string name, pass; cout << "Username: "; cin >> name; if (name == userName) { cout << "Password: "; cin >> pass; if (pass == passWord) cout << "You are logged in!" << endl; else cout << "Incorrect password." << endl; } else

cout << "Incorrect username." << endl; return 0; }

Programming Advice & Explanation:


Whenever possible avoid nesting or deep nesting as it makes program difficult to read. We should program in a manner that it can be read and understood easily by us and other programmers. For example, in the "Program 1" the nesting can be avoided by using logical operator. However in "Program 2" the nesting is required as we want to take input for password only if username is correct. In the next chapter we will learn about logical operators and will rewrite the "Program 1" using it. Please do comment if you don't understand any part or want to know more or just want to say thanks. I love programming and love to teach my friends. Your suggestions and appreciation will make this blog much better. Want to learn more? View List Of All Chapters Posted by Mohammed Homam at 4:23 AM 13 comments Labels: c++ examples, c++ programming, c++ programs, conditional statements, nested ifelse

Wednesday, August 11, 2010


Selection Statement (if-else if-else) in c++

Selection Statement (if-else if-else) in c++


To understand this chapter you should know about Comparison Operators which is explained in previous chapter. Selection statements are very important in programming because we make decisions using it.

/* A simple c++ program example to demonstrate the if statement. */


// Program 1 #include <iostream> #include <iomanip> using namespace std;

int main () { int first, second; cout << "Enter two integers." << endl; cout << "First " << setw (3) << ": "; cin >> first; cout << "Second "<< setw (2) << ": "; cin >> second; if (first > second) cout << "first is greater than second." << endl; return 0; }

/* A c++ program example to demonstrate if-else statements */


// Program 2 #include <iostream> #include <iomanip> using namespace std; int main () { int first, second; cout << "Enter two integers." << endl; cout << "First " << setw (3) << ": "; cin >> first; cout << "Second "<< setw (2) << ": "; cin >> second; if (first > second) cout << "first is greater than second." << endl; else cout << "first is less than or equal to second." << endl; return 0; }

/* A c++ program example to demonstrate if-else if-else statements. */


// Program 3 #include <iostream> #include <iomanip> using namespace std; int main () { int first, second; cout << "Enter two integers." << endl; cout << "First " << setw (3) << ": "; cin >> first; cout << "Second "<< setw (2) << ": "; cin >> second; if (first > second) cout << "first is greater than second." << endl; else if (first < second) cout << "first is less than second" << endl; else cout << "first and second are equal." << endl; return 0; }

Note: All the above three programs satisfies the condition that if first value is greater then display the message "first is greater than second". Question: When to use if, if-else and if-else if-else ? Answer: It depends upon your program. The number of possibilities your program has. For example, in the above program there are three possibilities. The value could either be greater, smaller or equal. All these possibilities are covered using if-else if-else statements. Depending upon the possibilities you can add more "else if" statement before the final else statement. It is good programming to cover all the possibilities to make your program perfect. In the next chapter we will learn about nested if statements. Posted by Mohammed Homam at 4:19 AM 6 comments Labels: c++ examples, c++ programming, c++ programs, if-else if-else, selection statement

Wednesday, July 28, 2010


Relational Operators (Comparison Operators) in c++

Relational Operators (also known as Comparison Operators)in C++


There is often need to compare two values in program. Such as whether the value in one a variable is greater than the value in the other variable. Depending upon the situation we can perform different operation for different cases. Relational Operators (also known as Comparison Operators) are used to compare two values. The result of comparison is a boolean value. The boolean value can either be true or false. In c and c++, 1 represents true and 0 represent false. However in c++ the data type bool has been introduced, which holds only two values either true or false. The value true in bool corresponds to 1 and 0 corresponds to false.

List of Relational Operators (aka Comparison Operators)

Operator < <= > >= == !=

Operator's Name less than less than or equal to greater than

Example 5<10 5<=10 5>10

Result 1(true) 1(true) 0(false) 0(false) 0(false) 1(true)

greater than or equal to 5>=10 equal to not equal to 5==10 5!=2

/* A c++ program example to demonstrate that the result of comparison is always a boolean value, either 1 or 0. The value 1 represents true and 0 represents false. */

#include <iostream> #include <iomanip> using namespace std; int main () { cout << "5 <10" << setw (4) << ": " << (5 < 10) << endl; cout << "5 <=10" << setw(3) << ": " << (5 <= 10) << endl;

cout << "5 >10" << setw (4) << ": " << (5 > 10) << endl; cout << "5 >= 10" << setw (2) << ": " << (5 >= 10) << endl; cout << "5 == 10" << setw (2) << ": " << (5 == 10) << endl; cout << "5 != 10" << setw (2) << ": " << (5 != 10) << endl; return 0; }

This chapter is important to understand selection and looping statement. In coming chapters we will learn about selection and looping statement. Posted by Mohammed Homam at 2:54 AM 0 comments Labels: boolean value, c++ example, c++ operators, c++ program, c++ programming, comparison operators, relational operators

Tuesday, March 16, 2010


Maximum and minimum limit for numeric data type

Maximum and minimum value of numeric data type


In c++, the numeric data types are short, int, long, float, double and long double. Every data type has certain limits. There is minimum and maximum value that it can hold. If a variable of a given data type is assigned a value that is greater than the maximum limit or smaller than the minimum limit, it results into wrong output. This mistake does not produce compiler error or runtime error. Hence we should be careful while choosing data type for a variable. The below is a c++ program which is used to determine the maximum and minimum values that data type can hold.

A c++ program to determine the maximum and minimum values of numeric data types.
#include <iostream> #include <limits> using std::cout; using std::endl; using std::numeric_limits; int main () { cout << "The values for data type short ranges from: " << numeric_limits<short>::min () << " to " << numeric_limits<short>::max () << endl; cout << "The values for the data type int ranges from: "

<< numeric_limits<int>::min () << " to " << numeric_limits<int>::max () << endl; cout << "The values for the data type long ranges from: " << numeric_limits<long>::min () << " to " << numeric_limits<long>::max () << endl; cout << "The values for the data type float ranges from: " << numeric_limits<float>::min () << " to " << numeric_limits<float>::max () << endl; cout << "The values for the data type double ranges from: " << numeric_limits<double>::min () << " to " << numeric_limits<double>::max () << endl; cout << "The values for the data type long double ranges from: " << numeric_limits<long double>::min () << " to " << numeric_limits<long double>::max () << endl; return 0; } Posted by Mohammed Homam at 6:52 AM 1 comments Labels: c++ data type, c++ example, c++ program, maximum limit, minimum limit, numeric data type

Thursday, March 11, 2010


Using the sizeof keyword in c++

Determine the size of data type using sizeof keyword


When we compile the c++ program, the compiler translates that program into language of that machine in which you compile. For example, the size of the data type may vary on 16-bit and on 32-bit processor. In this case you might have to modify your source code to run your program properly. This is not the case in java. As java does not translates the program to machine language when it is compiled, rather it translates the program to bytecode. The java interpreter i.e. the java virtual machine (JVM) or the java run-time environment interprets the bytecode. Hence no modification is required. However in c++ we can find the amount memory allocated by each data type using the sizeof keyword. The below is the program by which you can know how much memory, a particular data type will require on the machine in which it is executed. For example with windows xp operating system which runs on pentium 4 processor the size of int and long is same, it is 4 bytes.

A C++ Program example to find the size of the data type using sizeof keyword..

#include <iostream> #include <iomanip> using namespace std; int main () { cout << "The size of bool is" << setw (9) << ": " << sizeof (bool) << " byte" << endl; cout << "The size of char is" << setw (9) << ": " << sizeof (char) << " byte" << endl; cout << "The size of short is" << setw (8) << ": " << sizeof (short) << " byte" << endl; cout << "The size of int is" << setw (10) << ": " << sizeof (int) << " byte" << endl; cout << "The size of long is" << setw (9) << ": " << sizeof (long) << " byte" << endl; cout << "The size of float is" << setw (8) << ": " << sizeof (float) << " byte" << endl; cout << "The size of double is" << setw (7) << ": " << sizeof (double) << " byte" << endl; cout << "The size of long double is" << setw (2) << ": " << sizeof (long double) << " byte" << endl; return 0; } Posted by Mohammed Homam at 5:39 AM 0 comments Labels: c++ example, c++ keywords, c++ notes, c++ program, sizeof keyword

Sunday, November 22, 2009


Increment And Decrement Operator : prefix and postfix

Increment And Decrement Operator in C++


In C++ Programming Language, increasing a value by 1 is called incrementing and decreasing value by 1 is called decrementing. As 1 is the most common value used to add, subtract and to reassign into variable. Although we have short-hand assingnment operator but special operator are provided in c++ programming to increase or decrease value by 1. The

increment operator(++) increases the variable's value by 1 and the decrement operator(--) decreases the value by 1.

A C++ Program example that demonstrate the use increment and decrement operator by comparing it with short hand assignment operator.
#include <iostream> int main () { using std::cout; using std::endl; int b = 4, c = 7; cout << "The value of b is : " << b << endl; b = b + 1; cout << "The value of b is : " << b << endl; b += 1; cout << "The value of b is : " << b << endl; b++; cout << "The value of b is : " << b << endl; cout << endl; cout << "The value of c is : " << c << endl; c = c - 1; cout << "The value of c is : " << c << endl; c -= 1; cout << "The value of c is : " << c << endl; c--; cout << "The value of c is : " << c << endl; return 0; }

Prefixing And Postfixing In Increment And Decrement Operator.


Both increment (++) and decrement (--) operator come in two varieties : prefix and postfix. In prefix the increment or decrement operator is written before the variable's name (++a or --a) and in postfix the increment or decrement operator is written after the variable's name (a++ or a--). In simple statement it doesn't matter what you choose. But it differs in complex statement in which you increment or decrement value and also assign it to a variable in single statement.

The prefix operator is evaluated before the assignment. The postfix opertor is evaluated after the assignment. Follwing example makes it clear.

A C++ Program example that demonstrate the similarities and difference between prefix and postfix operator.
#include <iostream> int main () { using std::cout; using std::endl; int a = 10; a++; cout << "The value of a is : " << a << endl; ++a; cout << "The value of a is : " << a << endl; cout << "The value of a is : " << a++ << endl; cout << "The value of a is : " << ++a << endl; cout << endl; int b = 3; a = b++; cout << "The value of a is : " << a << endl; cout << "The value of b is : " << b << endl; a = ++b; cout << "The value of a is : " << a << endl; cout << "The value of b is : " << b << endl; return 0; }

Another C++ Program example that demonstrate the use of postfix and prefix operator.
#include <iostream> int main () { using namespace std;

int age = 18; cout << "I was " << age++ << " years old." << endl; cout << "Now I am " << age << " years old." << endl; cout << "One year passes...." << endl; cout << "I am " << ++age << " years old." << endl; return 0; } Posted by Mohammed Homam at 9:14 PM 0 comments Labels: c++ example, c++ operators, c++ program example, c++ programming, c++ programs, decrement operator, increment operator, prefix and postfix

Friday, November 20, 2009


Short Hand Assignment Operator in C++

Short Hand Assignment Operator in C++ Programming


Short hand assignemnt operators are also known as compound assignment operator. The advantage of using short hand assignment operator is that it requires less typing and hence provides efficiency.

A C++ Program example without using short hand assignment operator.


#include <iostream> int main () { using std::cout; using std::endl; int a = 3; cout << "Value of a is : "<< a << endl; a = a + 1; cout << "Value of a is : "<< a << endl; a = a - 1; cout << "Value of a is : "<< a << endl; a = a * 2; cout << "Value of a is : " << a << endl; a = a / 2;

cout << "Value of a is : " << a << endl; a = a % 2; cout << "Value of a is : " << a << endl; return 0; }

A C++ Program example that uses short hand assignment operator


#include <iostream> int main () { using std::cout; using std::endl; int a = 3; cout << "Value of a is : " << a << endl; a += 1; cout << "Value of a is : " << a << endl; a -= 1; cout << "Value of a is : " << a << endl; a *= 2; cout << "Value of a is : " << a << endl; a /= 2; cout << "Value of a is : " << a << endl; a %= 2; cout << "Value of a is : " << a << endl; return 0; }

Note :
From the above two example it is clear that statement a = a + 1 is same as a += 1 and a = a - 1 is same as a -= 1 and a = a * 1 is same as a *= 1 and

a = a / 1 is same as a /= 1 and a = a % 1 is same as a %= 1

C++ Constant : Types And Uses

C++ Constant : Types And Uses

What is Constant ?
As similar to variable constant are data storage location. As the name implies constant's value do not change. They remain constant throughout the program. Unlike variable whose value can be changed anywhere in the program. There are two types of constant in C++. They are as follows : 1) Literal Constant float PI=3.14; The value that is directly typed into the program is called literal constant. Here 3.14 is called literal constant. You cannot assign a value to 3.14. 2) Symbolic Constant Symbolic Constant are represented by name. There are two ways to declare a symbolic constant. They are as follows : 1) By using preprocessor directive #define. This is old way of declaring constant. It has now became obsolete way. 2) By using keyword const. This way is appropriate way to declare constant.

A C++ Program example that demonstrate the use of constant by using preprocessor directive #define
/* Area Of Circle Program */ #include <iostream> #define PI 3.14 using std::cout; using std::cin; using std::endl; int main () { int r;

cout << "Find the area of circle." << endl; cout << "Enter radius : "; cin >> r; float area = PI * r * r; cout << "The area of circle of radius << area << endl; return 0; } " << r << " is "

A C++ Program example that demonstrate the use of constant by using the keyword const
/* Area Of Circle Program */ #include <iostream> using std::cout; using std::cin; using std::endl; const float PI = 3.14; int main () { int r; cout << "Find the area of circle." << endl; cout << "Enter radius : "; cin >> r; float area = PI * r * r; cout << "The area of circle of radius " << r << " is " << area << endl; return 0; }

Another C++ Program example that demonstrate the use of constant

/* Program that calculate total income of the year */ #include <iostream> using std::cout; using std::endl; int main () { const int salary = 20000; float tax = (float) 10 / 100 * salary; // tax is 10% of salary float monthlyIncome = salary - tax; // bonus is 5% of salary float yearlyBonus = (float) 5 / 100 * salary; float yearlyIncome = (monthlyIncome*12) + yearlyBonus; cout << "My yearly income is " << yearlyIncome << endl; return 0; }

In the above program example, salary is declared as constant of type int. You can assign a value to constant only at the declaration time. This value could not be changed later on the program. If you do you will get compiler error " assignment of read-only variable 'salary' " and your program wont compile.

C++ Notes :
(1) The way to declare a string constant with #define : #define HOBBY "Programming" String constant must be enclosed with double-inverted commas. (2) The way to declare a character constant with #define : #define AGREE 'y' Character constant must be enclosed with single-inverted commas. (3) Numeric type of data are not enclosed with inverted commas. (4) The advantage of using const keyword is that you can create constant of various data types by mentioning it explicitly. For example : const unsigned short int myVal = 40; Please do comment if you don't understand any part or want to know more or just want to say thanks. I love programming and love to teach my friends. Your suggestions and appreciation will make this blog much better. Want to learn more? View List Of All Chapters

Posted by Mohammed Homam at 6:44 AM 0 comments Labels: c++ constant, c++ example, c++ notes, c++ program, c++ programming, const, literal constant, program example, symbolic constant, types of constant, uses of constant

Mathematical Operators

C++ Mathematical Operators


Addition (+) Subtraction (-) Multiplication (*) Division (/) Modulo (%)

A c++ program example that demonstrate the use of mathematical operators.


/* A C++ Program Example that performs Addition , Subtraction, Multiplication, Division and Modulo */ #include <iostream> int main () { using std::cout; using std::endl; int a = 9, b = 4; cout << "Addition is : " << a + b << endl; cout << "Subtraction is : " << a - b << endl; cout << "Multiplication is : "<< a * b << endl; cout << "Division is : " << a / b << endl; cout << "Modulo is : " << a % b << endl; return 0; }

Note :
Modulo operator is also known as remainder operator. Posted by Mohammed Homam at 12:27 AM 0 comments Labels: c++ example, c++ operators, c++ program, mathematical operator

Tuesday, November 10, 2009

List Of All C++ Keywords

List Of C++ Keywords :


Note: Do not use C++ Keywords as variable name.

asm auto bool break case catch char class const const_cast continue default delete do double

else enum explicit export extern false float for friend goto if inline int long mutable

new operator private protected public register

this throw true try typedef typeid

reinterpret_cast typename return short signed sizeof static static_cast struct switch template union unsigned using virtual void volatile wchar_t while

dynamic_cast namespace

In addition, the following words are reserved :


Note: Do not use reserved words as variable name. And bitor not_eq or or_eq xor xor_eq

and_eq compl bitand not

Posted by Mohammed Homam at 6:05 AM 2 comments Labels: c++ keywords, c++ reserved words, list of c++ keywords

Saturday, October 24, 2009


C++ Variable : Declare and Assign

C++ Variable : Declaration and Assignment

What is variable ?
Variable reserve space in memory to store the data. You can change the data you stored in the variable. Since the data could vary, it is called variable. When declaring variable you should specify what type of data it should store and how much memory it should reserve for it. The following table shows the type of data and size of memory it reserve for that data and also how many values you can store in that data type.

Type
bool unsigned short int short int unsigned long int
long int

Size
1 byte 2 bytes 2 bytes 4 bytes
4 bytes

Value
True or false 0 to 65535 -32768 to 32767 0 to 4,294,967,295
2,147,483,648 to 2,147,483,647

int (16 bit) int (32 bit) unsigned int (16 bit) unsigned int (32 bit) char float double

2 bytes 4 bytes 2 bytes 4 bytes 1 byte 4 bytes 8 bytes

32,768 to 32,767 2,147,483,648 to 2,147,483,647 0 to 65,535 0 to 4,294,967,295 256 character values 1.2e38 to 3.4e38 2.2e308 to 1.8e308

Note : The size of some variable type will differ on 16-bit and 32-bit processor. Imp* : You can use "short" instead of "short int" and "long" instead of "long int". On the 32-bit processor the value of short ranges from 32,768 to 32,767 but if you declare unsigned short the value ranges from 0 to 65535. You cannot store negative value in unsigned. Never declare unsigned before variable type if there is any possibility to store a negative value.

How to declare a variable ?

To declare a variable first type the variable-type (also known as data type) followed by the variable name and then teminate it by semicolon. For example : int number; In the above example, int is the data type and number is name of variable. You can give any name to the variable except for name used for keywords. Variable name can contain letters, numbers or underscore. But the first character should always be either letter or underscore.

How to assign value to a variable ?


There are two ways to assign value to a variable : 1) Assign the value directly in the program. 2) Ask from user to input a value and then assign that value.

A C++ program example that assign the value directly in the program.
#include <iostream> int main () { using std::cout; using std::endl; int a = 10, b = 20; int sum = a + b; cout << "Addition is : " << sum; return 0; }

A C++ program example that ask the user to input a value then assign that value.
#include <iostream> #include <iomanip> int main () { using namespace std; int a, b, sum;

cout << "Enter two number for addition." << endl; cout << "First" << setw (3) << ": "; cin >> a; cout << "Second" << setw (1) << ": "; cin >> b; sum = a + b; cout << "Addition is : " << sum; return 0; }

A C++ program example that demonstrate the declaration and assignment of various data types.
#include <iostream> #include <iomanip> int main () { using namespace std; short myShort = 2000; int myInt = 200000; long myLong = 5000000; float myFloat = 1255.549; double myDouble = 78079.3; char myChar = 'a'; char myString1[20] = "I love "; string myString2 = "C++ Programming"; cout << "myChar" << setw (5) << ": " << myChar << endl; cout << "myShort" << setw (4) << ": " << myShort << endl; cout << "myInt" << setw (6) << ": " << myInt << endl; cout << "myLong" << setw (5) << ": " << myLong << endl; cout << "myFloat" << setw (4) << ": " << myFloat << endl; cout << "myDouble" << setw (3) << ": " << myDouble << endl; cout << "myString1" << setw (1) << ": " << myString1 << endl; cout << "myString2" << setw (1) << ": " << myString2 << endl; return 0; }

C++ Notes:
(1)As we know that in english language statement ends with dot (full-stop). In programming languages like C, C++ and Java, statement ends with semicolon. Thus, "int age;" is called statement in C++ and since it declares a variable, it is called declaration statement. (2)This "age=20;" too is a statement as it ends with semi-colon. This statement assigns value to the variable, hence it is called assignment statement. (3)This "int age=20;" statement does two job. It declares variable as well as assigns value to it. This is compound statement of both declaration as well as assignment statement. (4)In C++ (=) is called assignment operator and not equal to as in mathematics. It is use to assign the value. In C++ equality operator is (==). (5)As already discussed in earlier lesson that cout in C++ is used to displays output to the console. Similarly, cin is used to take the input (a value) from the user and then assign it to its variable. Posted by Mohammed Homam at 11:17 AM 2 comments Labels: assign variable, c++ example, c++ notes, c++ programs, c++ source code, c++ variables, declare variable, types of variables, uses of variable, variables

Wednesday, October 21, 2009


C++ Comments : Types and Uses

C++ Comments : Types and Uses

Why to use commments ?


You write a program so that it performs the given set of instruction. When you increase the code by adding additional instruction to it, it may become confusing. You can use comments to simplify it by mentioning that how or what the given instruction does. If you give your code to any other programmer, it will be easier for him to understand your code if you use comments wisely. Also It will be helpful for you too. If you use comments you will have better idea about your program even if the program becomes large later on.

Types of comments
There are two types of comments used in C++. (1) Single line comments : Single line comments is accomplished by double-slash (//). Everthing that is followed by double-slash till the end of line is ignored by the compiler. It is reffered as C++-style comments as it is originally part of C++ programming. (2) Multi-line comments : Multi-line comments starts by using forward slash followed by asterisk (/*) and ends by using asterisk followed by forward slash (*/). Everthing between (/*) and (*/) are ignored by compiler whether it is one or more than one line. It is reffered as C-Style comment as it was introduced in C programming.

A C++ Program example that demonstrates the syntax and use of C++ Comments.
/* Program : C++ Comments Source code written by : Mohammed Homam Last modified date : 8:09 PM 10/21/2009 */ #include <iostream> int main () { using std::cout; using std::endl; cout << "C++ Programming" << std::endl; // It will display // C++ Programming return 0; } Posted by Mohammed Homam at 11:00 AM 4 comments Labels: c++, c++ comments, c++ example, c++ notes, c++ program, c++ programming, c++ source code, multi-line comments, single line comment, syntax of c++ comments, types of comments, use of comments

Saturday, September 19, 2009


The using and namespace keyword in C++

The using and namespace keyword in C++

Using the using keyword


You may feel it is inconvenient to write std:: in front of cout and endl every time. There is two solution provided by ANSI standard. It is done by use of the keyword using. The first solution is by calling specific standard library explicitly. For example, if we want to use cout and endl which is a part of standard library, we have to call standard library for cout and endl before using them. The following program demonstrates the first solution.

A C++ Program example that calls specific standard library.


#include <iostream> int main () {

using std::cout; using std::endl; cout << "Lets have a look on cout !!" << endl; cout << "The number 99 : " << 99 << endl; cout << "The sum of of 9 + 8 : "<< 9 + 8 << endl; cout << "The division of 7 / 18: "<< float (7 / 18) << endl; cout << "The multiplication of 6000 & 6000 : " << double (6000 * 6000) << endl; cout << "Replace Mohammed Homam with your name ..." << endl; cout << "Mohammed Homam is a C++ programmer" << endl; return 0; }

Using the namespace keyword


The second solution to avoid the inconvenience of writing std:: in front of cout and endl is by calling the entire standard namespace. It means that you don't have to call any standard library function explicitly. All standard library functions will be called by single statement. The following program demonstrates the second solution.

A C++ Program example that calls entire standard library.


#include <iostream> int main() { using namespace std; cout << "Lets have a look on cout !!" << endl; cout << "The number 99 : " << 99 << endl; cout << "The sum of of 9 + 8 : " << 9 + 8 << endl; cout << "The division of 7 / 18: "<< float (7 / 18) << endl; cout << "The multiplication of 6000 & 6000 : " << double (6000 * 6000) << endl; cout << "Replace Mohammed Homam with your name..." << endl; cout << "Mohammed Homam is a C++ programmer" << endl; return 0; } Posted by Mohammed Homam at 9:58 PM 0 comments Labels: c++ example, c++ keywords, c++ notes, c++ program, c++ programming, c++ source code, namespace keyword, using keyword, using namespace std

Monday, July 20, 2009


c++ cout (displays output to console)

Display output to console


In c++, cout is used to display the data to the console. The statement #include <iostream> is used add the file - iostream to the source code. The file - iostream (input-output-stream) is used by cout and its related function.

Syntax of cout ?
Type cout followed by insertion operator (<<) followed by your data and terminate it by semi-colon. The following program demonstrates the use of cout that displays integers, decimal equivalents string and so on.

A C++ Program example that demonstrate the various implementation of c++ cout
#include <iostream> int main () { std::cout << "Lets have a look on cout !!" << endl; std::cout << "The number 99 : " << 99 << endl; std::cout << "The sum of of 9 + 8 : " << 9 + 8 << endl; std::cout << "The division of 7 / 18: "<< float (7 / 18) << endl; std::cout << "The multiplication of 6000 & 6000: " << double (6000 * 6000) << endl; std::cout << "Replace Mohammed Homam with your name ..." << std::endl; std::cout << "Mohammed Homam is a C++ programmer" << std::endl; return 0; }

C++ Notes :
The \n symbol is an special formatting character. It is used to write new line to the screen. The manipulator std::endl is also used to write new line to the screen. like cout, endl is also provided by standard library. Therefore, std:: is added in front of endl just as it was added for

cout. But use of endl is preferred over \n because it is adapted to the operating system in use. The term float and double tells cout to display the number in floating-point value.

Вам также может понравиться