You are on page 1of 30

“COMPUTER PROGRAMMING REVIEWER”

Learning C++ Program


As your objective is to learn the C++ programming language, two questions naturally arise.
(1) What is a computer program?

 A computer or a program is a sequence of statements whose objectives is to accomplish a task.

(2) What is programming?

 Programming is a process of planning and creating a program.

History of C++ ( C with Classes)


 C++ is a portable language that works equally well on Microsoft Windows, Apple Mac
OS, Linux and Unix systems which was developed by Bjarne Stroustrup (B-yar-ne Strov-
stroop)
 Stroustrup C++ creation has held a spot among the world’s top programming languages
for decades and still remains a contemporary and useful choice for software development on
desktop computers, servers, embedded devices like phones and many other computing
environments.
 Originally, it was designed as an improvement upon the C programming, which was
developed by Bell Labs.
 Developed in the early 1970s, C’s name is derived from the B programming language,
which in turn was derived from the BCPL language.
 C gained a large following, in part due to its use in the development of the UNIX
operating system. Due to both its popularity and the number of versions on the market, an
American National Standards Institute (ANSI) committee was formed in 1982 to create a
standard for the C language, which was adopted in 1989.
 Stroustrup began with the idea that object-oriented programming would be an important
addition to C, and created C with Classes.
 In 1983, Stroustrup’s contributions officially became known as C++, its name stemming
from C and adding the ++ (increment) operator.
 It was not until 1998 that the international standard for C++ was established.
About the C++ Developer
 Bjarne Stroustrup (B-yar-ne Strov-stroop), a Danish computer scientist at Bell Labs in
the United States
 Born on December 30, 1950
 He is a visiting professor at Columbia University, and works at Morgan Stanley as a
Managing Director in New York
 He received a master's in mathematics from Aarhus University in 1975 and a PhD in
computer science from Cambridge University in 1979.
History of Programming Language
What is C++ ?

 C++ is based on C and it retains much of that language, including a rich operator set.
 C++ is a highly portable language, and translators for it exist on many different machines and
systems.
 C++ compilers are highly compatible with the existing C programs because maintaining such
compatibility was a design objective.
 Programming in C++ does not require a graphics environment, and C++ programs do not
incur runtime expense from type checking or garbage collection.
 C++ has improved on C in significant ways, especially in supporting strong typing.
 The class syntax was added to the language which was an extension of the struct construct in
C.
 C++ is superior than C in supporting object-oriented programming. C++ may even replace C
in becoming a general purpose programming language.
 C++ program is a collection of functions.
 Every C++ program has a function called main.
Features of C++ 

 OOP (Object-Oriented Programming): C++ is an object-oriented language, unlike C


which is a procedural language. This is one of the most important features of C++. It
employs the use of objects while programming.
 Platform or Machine Independent/ Portable: In simple terms, portability refers to
using the same piece of code in varied environments. C++ is ultra-portable and has
compilers available on more platforms than you can shake a stick at. Languages like Java are
typically touted as being massively cross platform, ironically they are in fact usually
implemented in C++, or C.
 Simple: When we start off with a new language, we expect to understand in depth. The
simple context of C++. gives an appeal to programmers, who are eager to learn a new
programming language.
 Mid-level programming language: C++ is regarded as a middle-level language, as it
comprises a combination of both high-level and low-level language features. It is a superset
of C, and that virtually any legal C program is a legal C++ program. 
 Case sensitive: Just like C, it is pretty clear that the C++ programming language treats
the uppercase and lowercase characters in a different manner.
 Compiler-Based: Unlike Java and Python that are interpreter-based, C++ is a compiler
based language and hence it a relatively much faster than Python and Java.
 DMA (Dynamic Memory Allocation): Since C++ supports the use of pointers, it allows
us to allocate memory dynamically. We may even use constructors and destructors while
working with classes and objects in C++.
 Rich Library: The C++ programming language offers a library full of in-built functions
that make things easy for the programmer. These functions can be accessed by including
suitable header files.
 Fast: C++ is compiler-based hence it is much faster than other programming languages
like Python and Java that are interpreter-based.
 Recursion: When function is called within the same function, it is known as recursion in
C++. The function which calls the same function, is known as recursive function

C++ Variables
Variables are containers for storing data values.
In C++, there are different types of variables (defined with different keywords), for example:

 int - stores integers (whole numbers), without decimals, such as 123 or -123

 double - stores floating point numbers, with decimals, such as 19.99 or -19.99

 char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single
quotes

 string - stores text, such as "Hello World". String values are surrounded by double quotes

 bool - stores values with two states: true or false

Declaring (Creating) Variables


To create a variable, you must specify the type and assign it a value:
Syntax:
type variable = value;
Where type is one of C++ types ( such as int) and variable is the name of the variable ( such as x
or myName). The equal sign is used to assign values to the variable.
To create a variable that should store a number, look at the following example:
Example: Copy and Run the sample C++ code in  online C++Compiler (Links to an external
site.)
🧮Problem: Create a variable called myNum of type int and assign it the value 15:
#include <iostream>
using namespace std;
main(){
int myNum = 15;
cout << myNum;      
}
OUTPUT:

15

 
 You can also declare a variable without assigning the value, and assign the value later:

Example: Copy and Run the sample C++ code in  online C++Compiler (Links to an external
site.)
#include <iostream>
using namespace std;
main(){
int myNum ;
myNum = 15;
cout << myNum;      // OUTPUT is 15
}
OUTPUT:

15

 Note that if you assign a new value to an existing variable, it will overwrite the
previous value:
 
Example: Copy and Run the sample C++ code in  online C++Compiler (Links to an external
site.)
#include <iostream>
using namespace std;
main(){
int myNum = 15;            // myNum is 15
myNum = 10;                  // Now myNum is 10
cout << myNum;          // Outputs 10
}
OUTPUT:

10
📀Other Types
A demonstration of other data types:
Example:
int myNum = 5;               // Integer (whole number without decimals)
double myFloatNum = 5.99;    // Floating point number (with decimals)
char myLetter = 'D';         // Character
string myText = "Hello";     // String (text)
bool myBoolean = true;       // Boolean (true or false)
 

📀Display Variables

 The cout object is used together with the << operator to display variables.


 To combine both text and a variable, separate them with the << operator"

Example: Copy and Run the sample C++ code in  online C++Compiler (Links to an external
site.)
#include <iostream>
using namespace std;
main(){
int myAge = 35;
cout << "I am " << myAge << " years old.";
}
OUTPUT:

I am 35 years old.

📀Add Variables Together

 To add a variable to another variable, you can use the + operator.


Example: Copy and Run the sample C++ code in  online C++Compiler (Links to an external
site.)
#include <iostream>
using namespace std;
main(){
int x = 5;
int y = 6;
int sum = x + y;
cout << sum;     //OUTPUT 11
}
OUTPUT:

11

📀Declare Many Variables


To declare more than one variable of the same type, use a comma-separated list:
Example: Copy and Run the sample C++ code in  online C++Compiler (Links to an external
site.)
#include <iostream>
using namespace std;
main(){
int x = 5,  y = 6,  z = 50;
cout << x + y + z;            //OUTPUT 61
}
OUTPUT:

61

x = 5, y = 6, z = 50;


<< x + y + z;
📀C++ Identifiers 
 All C++ variables must be identified with unique names.
 These unique names are called identifiers.
 Identifiers can be short names (like x and y) or more descriptive names (age, sum,
totalVolume).
Note: It is recommended to use descriptive names in order to create understandable and
maintainable code:
Example: Copy and Run the sample C++ code in  online C++Compiler (Links to an external
site.)
#include <iostream>
using namespace std;
main() {
// Good name
int minutesPerHour = 60;

// OK, but not so easy to understand what m actually is


int m = 60;

cout << minutesPerHour << "\n";      //OUTPUT 60


cout << m;                                                        //OUTPUT 60
}
OUTPUT:

60

📗The general rules for constructing names for variables (unique identifiers) are:
 Names can contain letters, digits and underscores
 Names must begin with a letter or an underscore (_)
 Names are case sensitive ( myVar and myvar are different variables).
 Names cannot contain white spaces or special characters like !, #, %, etc.
 Reserved words (like C++ keywords, such as int ) cannot be used as names.
 

📀C++ Constants
When you do not want others ( or yourself) to override existing variable values, use the const
keyword ( this will declare the variable as "constant", which means unchangeable and read-
only)
Example: Copy and Run the sample C++ code in  online C++Compiler (Links to an external
site.)
#include <iostream>
using namespace std;
main() {
const int myNum = 15;
myNum = 10;
cout << myNum;


OUTPUT:

In function 'int main()


6.9:error:assignment of read-only variable 'myNum'

 
 You should always declare the variable as constant when you have values that are
unlikely to change:
Example: Copy and Run the sample C++ code in  online C++Compiler (Links to an external
site.)
#include <iostream>
using namespace std;
main() {
const int minutesPerHour = 60;
const float PI = 3.14;
cout << minutesPerHour << "\n";
cout << PI;

}
OUTPUT:

60
3.14

C++ Data Types

 As explained in the Variables discussion, a variable in C++ must be a specified data type:

Example:Copy and Run the sample C++ code in  online C++Compiler (Links to an external
site.)
#include <iostream>
#include <string>
using namespace std;
main () {
// Creating variables
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
double myDoubleNum = 9.98; // Floating point number
char myLetter = 'D'; // Character
bool myBoolean = true; // Boolean
string myString = "Hello"; // String

// Print variable values


cout << "int: " << myNum << "\n";
cout << "float: " << myFloatNum << "\n";
cout << "double: " << myDoubleNum << "\n";
cout << "char: " << myLetter << "\n";
cout << "bool: " << myBoolean << "\n";
cout << "string: " << myString << "\n";
}
OUTPUT:

int: 5
float: 5.99
double: 9.98
char: D
bool: 1
string: Hello

 
Basic Data Types

 The data type specifies the size and type of information the variable will store:

📀C++ Numeric Data Types ( int, float, double)

 Use int when you need to store a whole number without decimals, like 35 or 1000,
and float or double when you need a floating point number ( with decimals), like 9.99 or
3.14.

Example:Copy and Run the sample C++ code in  online C++Compiler (Links to an external
site.)
#include <iostream>
using namespace std;
main(){
int myNum1 = 1000;
float myNum2 = 5.75;
double myNum3 = 19.99;
cout << myNum1 <<"\n";
cout << myNum2 <<"\n";
cout << myNum3;
}
OUTPUT:

1000
5.75
19.99

📀C++ Boolean Data Types

 A boolean data type is declared with the bool keyword and can only take the values true
or false.  When the value is returned, true =1 and false =0.

Example:Copy and Run the sample C++ code in  online C++Compiler (Links to an external
site.)
#include <iostream>
using namespace std;
main() {
bool isCodingFun = true;
bool isFishTasty = false;
cout << isCodingFun << "\n";
cout << isFishTasty;
}
OUTPUT:

1
0

📀C++ Character Data Types

 The char data type is used to store a single character.  The character must be surrounded


by single quotes, like 'A' or 's'.

Example:Copy and Run the sample C++ code in  online C++Compiler (Links to an external
site.)
#include <iostream>
using namespace std;
main () {
char myGrade = 'B';
cout << myGrade;
}
OUTPUT:

 
Other Example:Copy and Run the sample C++ code in  online C++Compiler (Links to an
external site.)
#include <iostream>
using namespace std;
main () {
char a = 65, b = 66, c = 67;
cout << a;
cout << b;
cout << c;
}
OUTPUT:

ABC

📀String Types

 The string type is used to store a sequence of characters (text).  This is not a built-in type,
but it behave like one in its most basic usage.  String values must be surrounded by double
quotes(" ").
 To use strings, you must include an additional header in the source code,
the <string> library:

Example:Copy and Run the sample C++ code in  online C++Compiler (Links to an external
site.)
#include <iostream>
#include <string>
using namespace std;
main() {
string greeting = "Hello ";
cout << greeting;
}

OUTPUT:

 Hello

C++ Operators

 Operators are used to perform operations on variables and values.


 In the example below, the + operator is often used to add together two values, like in the
example above, it can also be used to add together a variable and a value, or a variable and
another variable.

Example:Copy and Run the sample C++ code in  online C++Compiler (Links to an external
site.)
#include <iostream>
using namespace std;
main() {
int sum1 = 100 + 50;                     // 150 (100 + 50)
int sum2 = sum1 + 250;             // 400 (150 + 250)
int sum3 = sum2 + sum2;         // 800 (400 + 400)
cout << sum1 << "\n";
cout << sum2 << "\n";
cout << sum3;
}
OUTPUT:

150
400
800

 
C++ Different Operators:
1)  Assignment Operators-  Assignment operators are used to assign values to variables.
3) Relational or Comparison Operators

Comparison operators are used to compare two values.


Note: The return value of a comparison is either true (1) or false (0).
4) Logical Operators
Logical operators are used to determine the logic between variables or values.

“2.0”

 Sequential Control Structure

📚Topics
This module will cover the following topics:

1. Control Structures
2. Types of Control Structures
o Sequential Control Structures
o Selection Control Structures
 The if statement
 The else statement
 The nested if statement
 The switch statement
 The nested switch statement
📀Control Structures

 "Statements used to control the flow of execution in a program".


 Means a statement through which we control the behavior of our program like what kind
of
 function it will perform, when it will terminate or continue under certain circumstances or
conditions.
 These instructions enable us to group individual instructions into a single logical unit
with one entry point and one exit point. To make it more clearer, suppose we have lot of
statements in our program by using control structure we control their working like either all
statements will evaluate at once on the basis of certain condition or will evaluate one by one
or will not be evaluated.

📀There are Three Types of Control Structures


1) Sequential Control Structure :

 As name refers instructions  are executed in the sequence in which they are written in the
program.
 Refers to the line-by-line execution by which statements are executed sequentially, in the
same order in which they appear in the program.
 The simplest of the three fundamental control structure.

EXAMPLE:  Copy and Run in online C++ Compiler


#include <iostream>
using namespace std;
 main() {
int x;
cout << "Type a number: ";               // Type a number (100)  and press enter
cin >> x;                                                     // Get user input from the keyboard
cout << "Your number is: " << x;
}
OUTPUT:

Type a number: 100


Your number is : 100
 
Selection Control Structures

📀There are Three Types of Control Structures


2) Selection Control Structure :

 A structure which select which statement or block of statements will execute on the
basis of our programming logic.
 allows one set of statement to be executed if a condition is true and another set of
actions to be executed if a condition is false.

C++ Conditions 
C++ supports the usual logical conditions from mathematics:

 Less than:  a < b


 Less than or equal to: a <=b
 Greater than: a > b
 Greater than or equal to: a >=b
 Equal to a == b
 Not Equal to: a !=b

You can use these conditions to perform different actions for different decisions.
C++ has the following conditional statements:
 Use if to specify a block of code to be executed, if a specified condition is true

 Use else to specify a block of code to be executed, if the same condition is false

 Use else if to specify a new condition to test, if the first condition is false

 Use switch to specify many alternative blocks of code to be executed


Type of Selection Control Structure

 The if Statement - use to specify a block of C++ code to be executed if a condition is


true.

Syntax:  if (condition)
     // block of code to be executed if the condition is true
Note:  The if  keyword should be in lowercase letter.  Uppercase (IF or If) will generate an
ERROR.
Example1: Copy and Run in online C++ Compiler
#include<iostream>
using namespace std;
main() {
     int grade = 50;
      if (grade >= 50)
            cout<<("PASSED");
     }
OUTPUT:

PASSED

Example 2: Copy and Run in online C++ Compiler


#include<iostream>
using namespace std;
main() {
     int grade = 40;
      if (grade > = 50)
            cout<<("PASSED");
     }
OUTPUT:

Type of Selection Control Structure

 The else Statement - use to specify a block of C++ code to be executed if a condition
is false.
Syntax:  if (condition)
{
     // block of code to be executed if the condition is true
{
else
{
// block of code to be executed if the condition is false
}
Note:  The if  keyword should be in lowercase letter.  Uppercase (IF or If) will generate an
ERROR.
Example1: Copy and Run in online C++ Compiler
#include<iostream>
using namespace std;
main() {
     int grade = 50;
      if (grade > = 50)
            cout<< "PASSED";
     else 
           cout<< "FAILED";
     }
OUTPUT:
PASSED

Example 2: Copy and Run in online C++ Compiler


#include<iostream>
using namespace std;
main() {
 int grade = 40;
      if (grade > = 50)
            cout<<("PASSED");
      else 
           cout<< "FAILED";
     }
OUTPUT:

FAILED

 Type of Selection Control Structure

 The else if Statement - use to specify a new condition if the first condition is false.

Syntax:  if (condition)
{
     // block of code to be executed if the condition is true
{
else if (condition)
{
// block of code to be executed if the condition is false
}
        else 
    {
            // block of code to be executed if the condition is false
       }
Note:  The if  keyword should be in lowercase letter.  Uppercase (IF or If) will generate an
ERROR.
Example1: Copy and Run in online C++ Compiler
#include<iostream>
using namespace std;
main() {
     int grade =70 ;
      if (grade > = 50 && grade <=75)
          {  cout<< "GOOD";
     }
     else   if (grade > 75 && grade <=100)
          { cout<< "VERY GOOD";
     }
   else
          { cout<< "INVALID GRADE";
     }
OUTPUT:

GOOD

Example 2: Copy and Run in online C++ Compiler


#include<iostream>
using namespace std;
main() {
 int grade = 85;
    if (grade > = 50 && grade <=75)
          {  cout<< "GOOD";
     }
     else   if (grade > 75 && grade <=100)
          { cout<< "VERY GOOD";
     }
   else
          { cout<< "INVALID GRADE";
     }
OUTPUT:

VERY GOOD
 

Example 3: Copy and Run in online C++ Compiler


#include<iostream>
using namespace std;
main() {
 int grade = 105;
    if (grade > = 50 && grade <=75)
          {  cout<< "GOOD";
     }
     else   if (grade > 75 && grade <=100)
          { cout<< "VERY GOOD";
     }
   else
          { cout<< "INVALID GRADE";
     }

OUTPUT:

INVALID
GRADE

Type of Selection Control Structure

 The Nested if Statement s- It is always legal to nest if-else statements, which means
you can use one if or else if statement inside another if or else if statement(s).

Syntax: 
if (condition 1)
{  // block of code to be executed if the condition 1 is true
      if (condition 2)
       { // block of code to be executed if the condition 2 is true
    }
}
Example 1: Copy and Run in online C++ Compiler
#include<iostream>
using namespace std;
main() {
     int x = 1 ,   y= 5;
//check the condition
 if (x=1)       
{   //if the condition is true then check the  following
    if (y=5)     
      {   //if the condition is true then display the  following
       cout<< "Value of x is 1 and y is 5";
       }
 }
}   //end of main
     
OUTPUT:

Value of x is 1 and y is 5

Example 2: Copy and Run in online C++ Compiler


#include<iostream>
using namespace std;
main() {
     int x = 1 ,   y= 10;
 if (x= =1)        // the condition is TRUE
{   
         if (y= =5)      // the condition is FALSE
           {   
             cout<< "Value of x is 1 and y is 5";
      }
         else if (y = = 10)    // the condition is TRUE
    {
          cout<< "Value of x is 1 and y is 10"     // this is the OUTPUT
         }
 }
}   //end of main
     
OUTPUT:

Value of x is 1 and y is 10
Example 3: Copy and Run in online C++ Compiler
#include<iostream>
using namespace std;
main() {
     int x = 2 ,   y= 10;
 if (x= =1)        // the condition is FALSE
{   
         if (y= =5)      
           {   
             cout<< "Value of x is 1 and y is 5";
      }
         else if (y = = 10)   
    {
          cout<< "Value of x is 1 and y is 10"   
         }
 }
else if (x= =2)        // the condition is TRUE
{   
         if (y= =5)      // the condition is FALSE
           {   
             cout<< "Value of x is 1 and y is 5";
      }
         else if (y = = 10)    // the condition is TRUE
    {
          cout<< "Value of x is 2 and y is 10"     // this is the OUTPUT
         }
 }
}   //end of main
     
OUTPUT:

Value of x is 2 and y is 10

 The Switch Statement Selection Control Structure

📀Type of Selection Control Structure


The switch Statement 

 The switch use to select one of many code blocks to be executed.


 The switch-case conditional simplifies the process of checking the same variable for a set
of different equality values. 
 Although the same task could be achieved by a series of if or if-else conditionals, switch
is simpler to develop and debug.

Syntax: 
 switch(expression) 
{   case 1:   // code block
                   break;
     case 2:  // code block
          break;
default:  // code block
}
This is how it works:

 The switch expression is evaluated once


 The value of the expression is compared with the values of each case.
 If there is a match, the associated block of code is executed
 The break and default keywords are optional, and will be described later in this chapter

 
Example 1: Copy and Run in online C++ Compiler
#include<iostream>
using namespace std;
main() {
     int day = 1;
    switch(day) 
{   case 1:   cout<<"Monday";  // this condition is TRUE, the output is Monday
                   break;
     case 2: cout<<"Tuesday";     
          break;
default:   cout<<"Invalid Number of Day";
}
}// end of main
     }
OUTPUT:

Monday

 
   
Example 2: Copy and Run in online C++ Compiler
#include<iostream>
using namespace std;
main() {
     int day = 2;
    switch(day) 
{   case 1:   cout<<"Monday";
                   break;
     case 2: cout<<"Tuesday";     // this condition is TRUE, the output is Tuesday
          break;
default:   cout<<"Invalid Number of Day";
}
}// end of main
     }
OUTPUT:

Tuesday

 
Example 3: Copy and Run in online C++ Compiler
#include<iostream>
using namespace std;
main() {
     int day = 2;
    switch(day) 
{   case 1:   cout<<"Monday";
                   break;
     case 2: cout<<"Tuesday";     
          break;
default:   cout<<"Invalid Number of Day";  // all condition are FALSE, the output is  Invalid
Number of Day
}
}// end of main
     }
OUTPUT:

Invalid  Number of Day


📀The break Keyword
 When C++ reaches a break keyword, it breaks out of the switch block.
 This will stop the execution of more code and case testing inside the block.
 When a match is found, and the job is done, it's time for a break. There is no need for
more testing.
 A break can save a lot of execution time because it ignores the execution of all the rest of
the code in the switch block.

📀The default Keyword


 The default keyword specifies some code to run if there is no case match.
 The default  keyword must be used as the last statement in the switch and it does not need
a break.
 Type of Selection Control Structure

 The Nested switch Statement - It is possible to have a switch as a part of the


statement sequence of an outer switch. Even if the case constants of the inner and outer
switch contain common values, no conflicts will arise.

Syntax
 switch(expression) 
{   case 1:   // code block
                {      case A:  // code block
                       break;
                      case B:  // code block
                    break;
             }
                  break;
 
case 2:   // code block
                {      case A:  // code block
                       break;
                      case B:  // code block
                    break;
             }
                 break;

   default:  // code block


}
Example 1: Copy and Run in online C++ Compiler
#include<iostream>
using namespace std;
main(){
int grade =40 ;
char gender='f';
switch(grade)
     { case 40: cout<<"Failed";     // condition is TRUE
        switch(gender)
               { case 'f': cout<<"\nFemale"; break;    // condition is TRUE
                case 'm': cout<<"\nMale"; break;
               }
        break;

    case 50 : cout<<"Passed";
            switch(gender)
                {case 'f': cout<<"\nFemale"; break;
                  case 'm': cout<<"\nMale"; break;
        }
      break;

default: cout<< "Invalid";


}
}
OUTPUT:

Failed
Female

You might also like