Using the leftshift operator << in c++!

Recently in a test within college I came across the use of the shift operator. We had to work out the answer by hand so I thought I’d do a post about it. I have also written a program to help you understand it.

This was the question I was asked.

What is the value of c after the following?

int a=12
int b=2;

int c=a<<b;

Answer: 48

How to work it

Its actually really simple to work out.

The leftshift operator is the equivalent of moving all the bits of a number a specified number of places to the left:

[variable]<<[number of places]

1. Convert the variable to binary.
12 in binary is 1100.

2. Add the number of places onto the number.
This case it is 2 therefore add on 2 0's.

3. The number is now 110000.

4. count the number of 0's.
This case there is 4 0's

5. Now times the variable by the number of 0's.
12*4 in this case = 48.

8. We have now got our answer.

The code to work it out:

#include <iostream>

using namespace std;

int main()
{
    int firstNum, secondNum;
    
    int result;
    
    cout << "Using the shift operator <<!" << endl;
    
    cout << "Indicates the bits are to be shifted to the left." << endl;
    
    cout << "Please enter your first whole number" << endl;
    
    cin >> firstNum;
    
    cout << "Please enter you second whole number" << endl;
    
    cin >> secondNum;
    
    result = firstNum << secondNum;
    
    cout << result << endl;
    
    return 0;
}//main

Toads and Frogs Game!

This game was a C++ coursework task we where assigned in college. I had never actually heard of it before so I thought it would be an interesting game to share here. Please note, this was my first assignment for C++ so the practise used may not be the best, but if you do have any suggestions i’d love to hear them.

Code:


#include <iostream>

using namespace std;

// declaring functions
void showMessage();
void startGame();
void playerMove();
void winner();
void restartGame();
bool playToad(int n);
bool playFrog(int n);

//setting how many places on board
const int N = 6;

//moves for game
const int MOVES [N] = {0,1,2,3,4,5};

//game characters
char gameCharacters[N] = {'T','T', '.', '.', 'F', 'F'};

//ending loop for running game
bool gameOver = false;

//whos turn is it
int player = 1;

int main()
{
    //calling the function to print out for the start menu
    startGame();
    do
	{
        //calling functions for to see who won and to see whos go it is
        winner();
        playerMove();
        
		string s="";
        
        //reading in users input
		getline(cin,s);
		if (s.length()>0)
		{
            switch(s[0])
            {
                case '0':
                {
                    //finding out which player it is and then calling function
                    if (player ==1)
                    {
                        playToad(0);
                        
                        player ++;
                        
                    }//if
                    
                    else
                    {
                        playFrog(0);
                        player --;
                    }//else
                    
                }//case0
                    
                    break;
                    
                case '1':
                {
                    if (player ==1)
                    {
                        playToad(1);
                        
                        player ++;
                        
                    }//if
                    
                    else
                    {
                        playFrog(1);
                        player --;
                    }//else
                }//case1
                    
                    break;
                    
                case '2':
                {
                    if (player ==1)
                    {
                        playToad(2);
                        
                        player ++;
                        
                    }//if
                    
                    else
                    {
                        playFrog(2);
                        player --;
                    }//else
                    
                }//case 2
                    
                    break;
                    
                case '3':
                {
                    if (player ==1)
                    {
                        playToad(3);
                        
                        player ++;
                        
                    }//if
                    
                    else
                    {
                        playFrog(3);
                        player --;
                    }//else
                    
                }//case 3
                    break;
                    
                case '4':
                {
                    if (player ==1)
                    {
                        playToad(4);
                        
                        player ++;
                        
                    }//if
                    
                    else
                    {
                        playFrog(4);
                        player --;
                    }//else
                    
                }//case 4
                    break;
                    
                case '5':
                {
                    if (player ==1)
                    {
                        playToad(5);
                        player ++;
                        
                    }//if
                    
                    else
                    {
                        playFrog(5);
                        player --;
                    }//else
                    
                }//case 5
                    break;
                    
                case 'q':
                {
                    exit(0);// quit the program
                }//case q
                    break;
                    
                case 'r':
                {
                    restartGame(); // resarting
                }//case r
                    break;
                    
                default:
                {
                    showMessage();
                }//default
                    
            }//switch
            
        }//if
        
	}//do
    
    while(gameOver == false);
    
    return 0;
}//main

bool playToad(int n)
{
    if(gameCharacters[n]== 'T')
    {
        if(n<N-1)
        {
            // if the space is empty
            if(gameCharacters[n+1]=='.')
            {
                //moving
                gameCharacters[n] = '.';
                gameCharacters[n+1]='T';
                
                //printout new array
                for(int count=0; count<N; count++)
                {
                    cout << gameCharacters[count];
                }//for
                
                cout << endl;
                
                return true;
            }//if
            
            if(n<N-2)
            {
                if(gameCharacters[n+2]=='.')
                {
                    //moving
                    gameCharacters[n] = '.';
                    gameCharacters[n+2]='T';
                    
                    for(int count=0; count<N; count++)
                    {
                        cout << gameCharacters[count];
                    }//for
                    
                    cout << endl;
                    
                    return true;
                }//if
                
                else
                {
                    return false;
                }//else
                
            }//if
            
            else
            {
                return false;
            }//else
            
        }//if
        
        else
        {
            return false;
        }//else
    }//if
    
    else
    {
        return false;
    }//else
}//bool

bool playFrog(int n)
{
    if(gameCharacters[n]== 'F')
    {
        if(n>N-5)
        {
            if(gameCharacters[n-1]=='.')
            {
                //moving
                gameCharacters[n] = '.';
                gameCharacters[n-1]='F';
                
                for(int count=0; count<N; count++)
                {
                    cout << gameCharacters[count];
                }//for
                
                cout << endl;
                
                return true;
            }//if
            
            if(n>N-4)
            {
                if(gameCharacters[n-2]=='.')
                {
                    //moving
                    gameCharacters[n] = '.';
                    gameCharacters[n-2]='F';
                    
                    for(int count=0; count<N; count++)
                    {
                        cout << gameCharacters[count];
                    }//for
                    
                    cout << endl;
                    
                    return true;
                }//if
                
                else
                {
                    return false;
                }//else
                
            }//if
            
            else
            {
                return false;
            }//else
            
        }//if
        
        else
        {
            return false;
        }//else
    }//if
    
    else
    {
        return false;
    }//else
}//playfrog

void showMessage()
{
    cout << "Enter 0-5 for move, q to quit, r to restart game." << endl;
}//showMessage()

//Show the menu of possible operations
void startGame()
{
    cout << "Enter 0-5 for move, q to quit, r to restart game." << endl;
    
    cout << gameCharacters << endl;
    
    //to print out the moves in the array
    for(int count =0; count< N; count++)
    {
        cout << MOVES[count];
    }//for
    
    cout << endl;
    
}//startGame()


void playerMove()
{
    if (player == 1)
    {
        cout <<  "Enter move for Toad <<" << endl;
    }//if
    
    else
    {
        cout <<  "Enter move for Frog <<" << endl;
    }//else
}//playermove

void winner()
{
    if (gameCharacters[0] == '.' && gameCharacters[1]=='T' && gameCharacters[2]=='T' && gameCharacters[3]=='F' && gameCharacters[4]=='F' && gameCharacters[5]=='.')
    {
        
        if (player==2)
        {
            cout << "Toad Wins!" << endl;
            restartGame();
        }//if
        
        else
        {
            cout << "Frog Winds!" << endl;
            restartGame();
        }//else
        
    }//if
    
    else if (gameCharacters[0] == '.' && gameCharacters[1]=='.' && gameCharacters[2]=='T' && gameCharacters[3]=='T' && gameCharacters[4]=='F' && gameCharacters[5]=='F')
    {
        
        if (player==2)
        {
            cout << "Toad Wins!" << endl;
            restartGame();
        }//if
        
        else
        {
            cout << "Frog Winds!" << endl;
            restartGame();
        }//else
    }//if
    
    else if (gameCharacters[0] == '.' && gameCharacters[1]=='F' && gameCharacters[2]=='.' && gameCharacters[3]=='T' && gameCharacters[4]=='T' && gameCharacters[5]=='F')
    {
        
        if (player==2)
        {
            cout << "Toad Wins!" << endl;
            restartGame();
        }//if
        
        else
        {
            cout << "Frog Winds!" << endl;
            restartGame();
        }//else
    }//if
    
    else if (gameCharacters[0] == 'T' && gameCharacters[1]=='T' && gameCharacters[2]=='F' && gameCharacters[3]=='F' && gameCharacters[4]=='.' && gameCharacters[5]=='.')
    {
        
        if (player==2)
        {
            cout << "Toad Wins!" << endl;
            restartGame();
        }//if
        
        else
        {
            cout << "Frog Winds!" << endl;
            restartGame();
        }//else
    }//if
    
    
    
    
}//winner

void restartGame()
{
    cout << "Would you like to play again?" << endl;
    cout << "1: To replay" << endl;
    cout << "2: To exit" << endl;
    
    string again = "";
    
    do
    {
        getline(cin, again);
        
        if (again.length()>0)
        {
            switch (again[0])
            {
                case '1':
                {
                    
                    gameCharacters[0] = 'T';
                    gameCharacters[1] = 'T';
                    gameCharacters[2] = '.';
                    gameCharacters[3] = '.';
                    gameCharacters[4] = 'F';
                    gameCharacters[5] = 'F';
                    player=1;
                    
                    startGame();
                    
                }//case 1
                    break;
                    
                    
                case '2':
                {
                    exit(0);
                }//case 2
                    
                    break;
                    
                default:
                {
                    cout << "Invalid input" << endl;
                    cout << "1: To replay" << endl;
                    cout << "2: To exit" << endl;
                }//default
                    
            }//switch
            
        }//if
        
    }//do
    
    while (!(again=="1" || again=="2"));
    
}//restartGame()


Continue Statement – C++

What it does:

continue causes the number 4 to be skiped in this case when printed out.

Code:


#include <iostream>

using namespace std;

int main()
{
    for(int count =1; count<=8; count++)
    {
        if(count==4)
        {
            continue; //skips the part code in the loop
        }//if
        
        cout << count << endl;
    }//for
    
    cout << "Used coninue to skip printing 4" << endl;
    
    return 0;
}//main

Calculating Interest – C++

What it does:

Calculates the interest of a balance of 5 years. The interest is set a .05 initially and the bank balance is set at 1000. Prints out in a table with two headers for the year and amount.

Code:



#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

int main()
{
    double amount;
    double initalAmount = 1000.0;
    double rate = .05;
    
    //Headings
    cout << "Year" << setw(21) << "Amount on deposit" << endl;
    
    //setting floating point num
    cout << fixed << setprecision(2);
    
    //caculating the amount for 5 years
    for(int year=1; year<=5; year++)
    {
        //caculating the amount for specified year
        amount = initalAmount * pow(1.0 + rate, year);
        
        //displaying the amount + year
        cout << setw(4) << year << setw(21) << amount << endl;
    }//for
    
    return 0;
}//main

Break Statement in a Loop – C++

What it does:
The break statement causes immediate exit from that statement. Program execuition continues with the next statement. Common usages are to exit early from a loop, skip the reminder of a switch statement.

#include <iostream>

using namespace std;


int main()
{
    int count;
    
    for (count =1; count<=20; count++)
    {
        if(count == 10)
        {
            break; // this will break out of the loop even though it was meant to run till 20
        }//if
        
        cout << count << endl;
    }//for
    
    cout << "The loop has ended at " << count << endl;
    
    return 0;
}//main

A Table of Cube, Square and Fourth Numbers – C++

A program I wrote in labs in uni, as a set task. It prompts the user to enter a number where it then prints out in a table starting from 1 up to the number entered the user entered. It also includes the cubed, squared and fourth number. 

#include <iostream>
#include <cmath>
#include <conio.h>
#include <iomanip>

using namespace std;

int main()
{
	int n;
	cout << "Please enter an interger" << endl;
	cin >> n;
    
	cout << "Value" << setw(10) << "Square" << setw(12) << "Cube" << setw(13) << "Fourth" << setw(10) << endl;
    
	for(int run=1; run<=n; run++)
	{
        
		cout << run << setw(10) << left;
		cout << pow (run, 2) << setw(10) << left;
		cout << pow (run, 3) << setw(10) << left;
		cout << pow (run,4) << setw(10) << left << endl;
        
	}//for 
    
    _getch();
	return 0;
}//main

Guess The Number – C++

What it does:
Another program which I created in labs in uni, as a task. It randomly generates a number, the user would then enter a guess and it would return either too low or too high allowing them to decide whether or not they need to increase or decrease their guess.

Code:


#include <iostream>
#include <cstdlib>
#include <ctime>
#include <conio.h>

using namespace std;

int main()
{
	srand((int)time(0));
	int randomNumber = rand()%100;
	int userGuess;
    
	do
	{
		cout << "\nPlease enter a number between 0 and 100" << endl;
		cin >> userGuess;
        
		if(userGuess>randomNumber)
		{
			cout << "Your guess is too high" << endl;
		}//if
        
		else if(userGuess<randomNumber)
		{
			cout << "Your guess is too low" << endl;
		}//else if
        
        
	}//do
	while(randomNumber!= userGuess);
    
    
	cout << "\n Your guess is correct and your number was " << userGuess << endl;
	
	
	_getch();
	return 0;
}//main

Accessing value though pointer – c++

What it does:

In the program, value is changed twice. As you can see only ptr and howMany changed. This is because they are connected with each other and saving is not.

#include <iostream>
using namespace std;
int main()
{
  int number;
  int *ptr = &number;
  int howMany;
  *ptr = 6087;
  howMany = *ptr;
  cout << howMany << endl;
  *ptr = 7000;
  cout << *ptr << endl;
  cout << howMany << endl;
  return 0;
}//main

Changing a variable by using a pointer – C++

What it does:

A very simple program which will set a variable by using a pointer.

Points:

To declare a pointer you need to declare what type of variable it will point to.

Placing asterisk before the pointer is also called deferring the pointer.

#include <iosheader>
using namespace std;

int main()
{
    int numberOfChildren;
    int *ptr;

    ptr = &numberOfChildren;
    *ptr = 6098;
    cout << numberOfChildren << endl;

    return 0;
}\\main