if Statement in C++

The ability to control the flow of your program, letting it make decisions on what code to execute is valuable to the programmer. The if statement in c++ allows you to control if a program enters a section of code or not based on whether a given condition is true or false. Below you will find sample conditional statements and a list of relational operators to use with the statements.

Relational Operators

equals to ==
not equals to !=
less than <
greater than >
less than or equal to <=
greater than or equal to >=
not !
and &&
or ||

The if Statement

if (Boolean Expression) {

statement(s) to execute.

}

if…else Statement

if (Boolean Expression) {

statement(s) to execute if condition is true.

} else {

statement(s) to execute if condition is false.

}

if Statement Example

if (age == 20) {

cout << “I am twenty years old.”;

}

if…else Statement Example

#include <iostream>

using namespace std;

int main()
{

int age;

cout<<“Please input your age: “; cin>> age;
cin.ignore();

if ( age < 100 ) {

cout<<“You are pretty young!\n”;

} else if ( age == 100 ) {

cout<<“You are old\n”;

} else {

cout<<“You are really old\n”;

}

cin.get();

}

Switch Statement in C++

Switch statement is a substitute for long if statements that compare a variable to several integral values (integral values are simply values that can be expressed as an integer, such as the value of a char). The basic format for using switch case is outlined below. The value of the variable given into switch is compared to the value following each of the cases, and when one value matches the value of the variable, the computer continues executing the program from that point.

Switch Statement Syntax

switch (value) {

case this-value:

Code to execute if value == this-value
break;

case that-value:

Code to execute if value == that-value
break;

default:

Code to execute if value does not equal any of the cases
break;

}

Switch Statement Example

int age;
cout << “What is your age: “; cin >> age;

switch (age)
{

case 1:

cout << “You are 1 year old”;
break;

case 2:

cout << “You are 2 years old”;
break;

case 3:

cout << “You are 3 years old”;
break;

default:

cout << “You are older than 3 years”;

}

Break Statement

The break command can be used to exit a loop at any time. Here is an example that will print “Hello” 5 times and then break out of the loop.

int x;
for (x = 1; x <= 10; x++)
{

cout << “Hello\n”;
if(x == 5)
break;

}

Continue Statement

The continue command lets you start the next iteration of the loop. The following example will not print “Hello” on 5th iteration because the continue command goes back to the beginning of the loop.

int x;
for (x = 1; x <= 10; x++)
{

if(x == 5)
continue;
cout << “Hello\n”;

}

Loops in C++

Loops are probably one of the most important programming concepts in existence. There are so many applications of loops it would be impossible to list them all. To name a few though, things like parsing an array, trapping for errors, and animation. Also, since it will allow you to execute a block of code over and over, it saves time and typing. Now, depending on what kind of programming language you came from, loops might already be familiar to you, but if you’ve come from a low level programming language such as assembly or GWBasic, you are probably more familiar with jump or goto statements. Well, loops take into account all that lovely comparison crap you used to have to do before and puts it into one nice package.

C++ for Loop

The easiest and most used of these loops is the for loop.

for Loop Syntax

for ( variable initialization; condition; variable update ) {
Code to execute while the condition is true
}

for Loop Example

#include <iostream>
using namespace std;

int main() {

for ( int x = 0; x < 10; x++ ) {

cout<< x << “\n”;

}
return 0;

}

C++ while Loop

The while loop is almost exactly the same as the do loop except that its condition is tested at the start of the loop instead of at the end… and the format is slightly different. The easiest way to see this is simply to re-write the above example with a while loop.

while Loop Example

#include <iostream>

using namespace std;
int main()
{

int x = 0;

while ( x < 10 ) {

cout<< x << “\n”;
x++;

}

return 0;

}

C++ do.. while Loop

The do while loop is like the while loop except that the condition is tested at the bottom of the loop.

do.. while Loop Syntax

do {

statement(s);

} while (condition);

do.. while Loop Example

#include <iostream>

using namespace std;

int main()
{

int x;

x = 0;
do {

cout<<“Hello, world!\n”;

} while ( x != 0 );

return 0;

}

Functions in C++

A function is a block of statements which is used to perform a task. Any C++ program has at least one function which is main().  When you have a piece of code that is often repeated you should put it into a function and call that function instead of repeating the code.

Function Definition

You define a function in similar way as you define the main function. First put return type then the function name and function parameters in brackets. The function code goes between curly brackets.

returnType functionName( parameters ) {

statement(s);

}

Example

void PrintHello()
{

cout << “Hello\n”;

}

Calling a Function

Once you have created the function you can call it from the main program. Here is an example of how to call the PrintHello function.

void PrintHello()
{

cout << “Hello\n”;

}

void main()
{

PrintHello();

}

Local and Global Variables

If you declare a variable inside a function it is only accessible by that function and is called a local variable. If you declare a variable outside of all functions it is accessible by any function and is called a global variable.

Example

int g; // Global variable

void MyFunction()
{

int l; // Local variable
l = 5;
g = 7;

}

void main()
{

g = 3;

}

Function Arguments

The arguments are used to pass values to a function. Arguments goes between the brackets after the function name. You must choose the datatype of all parameters. Here is a function that receives a number as a parameter and then prints it.

void PrintNumber(int n, int m)
{

cout << n << m;

}

void main()
{

PrintNumber(5, 6);

}

Passing Parameters by Reference

You can either pass a parameter by reference or by value. The default is by value which means that a copy of the variable is made for that function. If you use a * in front of the parameter then you will be passing only a pointer to that variable instead of making another copy of it.

void PrintNumber(int *n)
{

cout << *n;

}

void main()
{

int i = 5;
PrintNumber(&i);

}

Returning Values

A function can return a value that you can store in a variable. We have been using void in the place of the return variable until now. Here is an example of how to return the number 5 from a function and store it in a variable.

int GetNumber()
{

return 5;

}

void main()
{

int i = GetNumber();

}

Pointers in C++

A pointer is a variable that holds a memory address. It is called a pointer because it points to the value at the address that it stores.

Pointers in C++

If you want to declare a pointer variable in c++ you must first choose what data type it will point to such as an int or a char. You then declare it as if you were declaring a variable in the normal way and then put a * in front of its name to show that it is a pointer. Here is an example of how to declare a pointer to an integer.

int *pi;

You can store the address of another variable in a pointer using the & operator. See the below example of how to store the address of a variable called i in the pointer called pi.

int i;
int *pi;
pi = &i;

You must dereference a pointer to get the value at the memory location that the pointer points to. You use the * operator to dereference a pointer. Here is an example of how we first set the value of i to 5 and then set its value to 7 by dereferencing the pointer.

int i = 5;
int *pi;
pi = &i;
*pi = 7;
cout << i;

new & delete operators

The new operator is used to allocate memory that is the size of a certain data type. It returns a pointer to the address of the newly allocated memory. Here is an example of how to allocate memory for an integer and then set its value to 5.

int *pi;
pi = new int;
*pi = 5;

The delete operator deallocates memory. You need to deallocate the memory for all the memory that you have previously allocated before exiting the program or else you will have memory leaks.

int *pi;
pi = new int;
*pi = 5;
delete pi;

Typed and untyped pointers

We have been using typed pointers so far because they point to a specific data type. An untyped pointer can point to anything. You declare an untyped pointer as the data type void.
void *up;

malloc() and free() functions

The malloc command allocates a certain number of bytes and returns a pointer to the first byte. You must use the free command to deallocate the memory that was allocated with malloc. To be able to use malloc and free you must include the malloc header file. Here is an example that allocates 100 bytes of memory and stores the address of it in the pointer called up and then deallocates the memory.

void *up;
up = malloc(100);
free(up);