C++ Variables & Constants

In the previous topic, we have discussed data types in C++ in detail. Today we will discuss variables and constants in C++.

A named memory location or memory cell is called a variable. The program's input data and its results are stored in variables during execution. During the execution of the program, the value of a variable can be changed but its name can not be changed.

Variables are created in random access memory. As we know that RAM is a temporary memory so data stored in it is also temporary. It can only be used during execution. When the program ends, the data stored in the variable is automatically removed.

In C++, all the variables are declared first:
  • Name of variable: an identifier that represents a memory location.
  • Address of variable: memory location of the variable.
  • Contents of variable: the value stored in a memory location.

Variable Declaration:

  • Variable declaration is the process of specifying the name and the type of variable.
  • Before a variable is used, it can be declared anywhere in the program before its execution.
  • Information is provided to the compiler about the variable by variable declaration.
  • The compiler determines the memory required for each variable.
  • After the declaration, the required memory of bytes is allocated to variables.
  • Once the variable is declared then its name and data type can not be changed but its value can be changed during execution.
  • For example, an integer required 2 bytes of memory but a character required one byte of memory. During execution int and char data types can not be changed but integer value can be changed from 5 to 9 and character can be changed from ‘f’ to ‘g’.

SYNTAX of declaring a variable in C++

  • data-type: type of data that is stored in a variable.
  • variable-name: tell us about the memory location of the variable.

For example:

int num1=25, num2=1000;
We can also write it like this:
int num1,num2; num1=25; num2=1000;

Types of Variables 

Types of Variables can be categorized in two ways

  • Types of variables regarding data types
  • Types of variables regarding the scope

Types of variables regarding data type:

Based on the data type of variable, there are the following categories of variables in C++

  • int: holds an integer value i.e. 1, 2, 3, 50 etc.
  • char: holds character values like ‘c’, ‘F’, ‘B’, ‘p’, ‘g’, ‘q’ etc.
  • bool: holds boolean value true or false(0 or 1).
  • double: holds double-precision floating-point value.
  • float: holds single-precision floating-point value.

Example

Different types of variables can be declared as follow:

  • int marks;
  • float average;
  • char grade;
  • double salary;

Variables having the same data type can be declared in a single line. Each variable in line should be separated by a comma as follows:

int  a, b, c;

Types of variables regarding scope

When we discussed the Hello Program, we have seen the curly braces in the program like this:

int main { //Some code }

When variables are declared in curly braces then their scope is limited within these braces. The variable declared in main() function can not be used outside the main() function.

There are two types of variables based on their scope.

  1. Global variable
  2. Local variable

Global Variable

Global variables are always declared outside of any function.

  • Their scope is in the complete program so can be accessed anywhere in the program.
  • Can be accessed in the main() function, in the user-defined function and anywhere in the program.

Global variable example

Let us have a global variable myvar and it is declared outside of main. We can access the variable twice in the main() function easily.

#include <iostream> using namespace std; // This is a global variable char myvar = 'G'; int main() { cout <<"Value of myvar: "<< myvar<<endl; myVar='m'; cout <<"Value of myvar: "<< myvar; return 0; }
Output:
  • Value of myvar: G
  • Value of myvar: m

Local variable

  • They are declared inside the curly braces of any loop or control statement, main function, user-defined function and their scope is limited only to the curly braces so they can be used only within the curly braces.

Local variable example

#include <iostream> using namespace std;   char myFuncn() { // This is a local variable char myVar = 'X’; } int main() { cout <<"Value of myVar: "<< myVar<<endl; myVar='H’; cout <<"Value of myVar: "<< myVar; return 0; }
Output:
  • As we are trying to access the variable outside its scope so a compile-time error will occur.
  • Local and global variables may or may not have the same name.
  • We can see an example having the same name for local and global variables.
#include <iostream> using namespace std; // This is a global variable char myVar = 'X'; char myFuncn() { // This is a local variable char myVar = 'Y’; return myVar; } int main() { cout <<"Funcn call: "<< myFuncn()<<endl; cout <<"Value of myVar: "<< myVar<<endl; myVar='A'; cout <<"Funcn call: "<< myFuncn()<<endl; cout <<"Value of myVar: "<< myVar<<endl; return 0; }
Output:

Funcn call: X

Value of myVar: Y

Funcn call: X

Value of myVar: A

As the scope of the local variable is limited so the changed value of the variable is only responded for the global variable and the value of the local variable remained the same ‘ X’.

 

RULES FOR DECLARING VARIABLES:

There are some rules in C++ for naming variables
  • Variable can be a letter, number and underscore(-).
  • Variable’s first letter should be a letter or underscore. The variables 6second, $6payment and 5kg are invalid.
  • In the variable name, blank spaces can not be added. ‘ my var’ is an invalid variable.
  • Both upper and lower cases can be used. User-defined variables are written in lower and constants are written in upper case conventionally.
  •  special symbols can not be used in variables as a name.
  • Reserved words can not be used as a variable name. e.g int, for, while etc can not be used as a variable name.
  • The no of characters in the variable should not be more than 31.
  • A variable can not be declared for more data types. It should be declared for only one data type.
Variable declaration vs variable definition:
  •  The variable declaration tells us about the part where the variable was first declared before its use.
  • While variable definition tells us about that part where variable assigned memory location and value
  • Variable definition and declaration did at a time mostly.
#include <iostream> using namespace std; int main() { // declaration and definition of variable 'b123' char b123 = 'a'; float b; // multiple definitions and declararions int _c, _d45, e; cout << b123 << endl; return 0; }

Variable Initialization:

Variable initialization is the process of assigning a value to the variable.
  • = sign is used to initialize a variable
  • The variable name is written on the left side of = and the value is given on the right side of =.
  • Compiler allocated some memory to the variable when it is declared.

Syntax

type_ name variable=value;
  • type_name: indicates the data type of the variable
  • variable: name of the variable
  • assignment operator used to initialize a variable
  • value: value to initialize a variable

Example

#include <iostream> using namespace std; int main() { int a = 10; int b; cout << " value of variable a : "<< a; // static initialization cout << "\nEnter the value of variable b : "; // dynamic initialization cin >> b; cout << "\n value of variable b : "<< b; return 0; }

Output

value of variable a : 10 Enter the value of variable b : 18 value of variable b : 18

CONSTANTS IN C++

  • Constants are those quantities that cannot be changed during program execution.
  • It is used in the program wherever it is needed.
There are two common types of constants in C++
  1. Literal constant
  2. Symbolic constant

Literal constant

It is typed directly in the program and used when needed. Example
  • cout<<” Hi guys”;
The following statement contains "Hi guys" string literal constant.
  • int age = 19;
Age is an integer variable and 19 is a literal constant.

TYPES OF LITERAL CONSTANTS: 

There are 5 common types of literal constants are used in C++
  • Integer constant
  • Floating-point constant
  • Character constant
  • String constant
  • Bool constant

Integer literal constant

It can be a decimal, hexadecimal or octal constant. Examples:
  • 85         // decimal
  • 0213       // octal
  • 0x4b       // hexadecimal
  • 30         // int
  • 30u        // unsigned int
  • 30l        // long
  • 30ul       // unsigned

 Floating-point literals

Floating-point literal constant contain four parts
  • Integer part
  • Decimal part
  • Fractional part
  • Exponent part
Decimal forms include a decimal point, exponent or both. Exponent forms include integer part, fractional part or both

Examples

  • 3.14159       // Legal
  • 314159E-5L    // Legal
  • 510E          // Illegal: incomplete exponent
  • 210f          // Illegal: no decimal or exponent
  • .e55          // Illegal: missing integer or fraction

Character constants

  • These constants are enclosed in single quotes
  • Upper case letters are stored in wchar_t type and lower case letters are stored in char type
  • A character literal can be a simple character (e.g., 'x'), an escape sequence (e.g., '\p’), or a universal character (e.g., '\u0C0').
  • The characters with backslash have special meanings. These characters with a backslash are given below.
Escape sequence Meaning
\\ \ character
\' ' character
\" " character
\? ? character
\a Alert or bell
\b Backspace
\f Form feed
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
\ooo Octal number of one to three digits
\xhh . . . Hexadecimal number of one or more digits
 

Example

#include <iostream> using namespace std;   int main() { cout << "Hello\tWorld\n\n"; return 0; }

Output

Hello   World

String constants

They are enclosed in double-quotes. It may contain
  • Characters
  • Escape sequence
  • Universal character
String literals are used to break long lines into multiple lines.

Examples

"hello, dear" "hello, \ dear" "hello, " "d" "ear"

Program for defining a constant

#include <iostream>
using namespace std;
#define VAL1 20
#define VAL2  6
#define Newline '\n'
int main()
{
   int tot;
   tot = VAL1 * VAL2;
   cout << tot;
   cout << Newline;
}

Programs

#include <iostream> using namespace std;   #define LENGTH 5 #define WIDTH  20 #define NEWLINE '\n'   int main() { int area;   area = LENGTH * WIDTH; cout << area; cout << NEWLINE; return 0; } Program # 2 #include <iostream> using namespace std;   int main() { const int SIDE = 40; int area; area = SIDE*SIDE; cout<<"The area of the square with side: " << SIDE <<" is: " << area << endl; return 0; }

Bool constants

Three keyword literals exist in C++: true, false and nullptr:
  • For Boolean variables, we have true or false literals/ constants.
  • nullptr indicates the null pointer value.
1 2 3 bool foo = true; bool bar = false; int* p = nullptr;

Symbolic constants 

  •  It is the Symbolic name given to the Symbolic values that cannot be changed
  • A Symbolic constant PI having the value 3.141593 is used where needed and its value can not be changed.
There are two ways by which Symbolic constants can be derived.
  1. const Qualifier
  2. define Directive
The syntax for const Qualifier
const <Data_Type> <Variable_Name>
The syntax for define directive
<Return_Type> <Function_Name>() const
Example
#include <iostream> using namespace std;   const int a = 100;    // Const Variable   class TestConst { public: void display() const   // Const Function/ define directive { cout << "Value of a in the const function is " << a; } };   int main () { Test int1; int1.display(); cout << a; return 0; }

Comparison table for Constants and Variables

We have discussed above the clear understanding of variables, their types and some programs to make grip on the topic. We have also discussed constants and their types and some programs to make ideas clear. At the end, we make a clear comparison between constants and variables.

In the next section, we will discuss operators, expressions and comments in C++. Till then take care and have fun. Thanks for reading.

C++ Data Types

In the previous section, we have had an overview of a detailed Introduction to C++. Today, we will have a look at the data types in C++. It's our 2nd tutorial in the C++ programming language series.

In the previous tutorial, we have seen the basics of C++ and have also discussed a small code. We have discussed various programming terms in the previous tutorial and from now on, we are going to discuss those terms in detail. So, today's lecture is on Data Types in C++, let's get started:

C++ Data Types

A  data type defines the type and the set of operations that can be performed on the data. Various types of data are manipulated by the computer. The data is given as an input to the program. According to the program's set of instructions, data is processed and then output is returned on the screen. Before designing the actual program data, its type and operations performed on it are defined and used to process the data. At the start of the program, the type of each data value is identified. Various data types are provided by C++ and the computer’s memory allocates each data type differently.

Types of data types in C++

  1. Built-in data types
  2. derived data types 
  3. user-defined data types

Built-in Data Types in C++

  • Integral, floating-point and void data types are provided by C++ as built-in data types.
  • The integral and floating-point data types can be treated with different types of modifiers.
  • The size or range of data type is changed by using these modifiers.
  • Short, long, signed and unsigned are various modifiers.
Three main built-in data types provided by C++ are:

1. Integral data type

  • Integer data type: keyword int is used to express integer data type.
  • It normally requires 4 bytes of memory and ranges from -2147483648 to 2147483647.
long b = 4523232; long int c = 2345342; long double d = 233434.56343; short d = 3434233; // Error! out of range unsigned int a = -5;    // Error! Used for storing only +ive  numbers and 0

Example

 

Character data type in C++

  • Characters are stored by using character data type.
  • Char is used to representing character data type.
  • It normally requires 1 byte of memory.
  • char test = 'h';
  • As each character is assigned by a unique ASCII code which is an integer so that’s why characters are included in integral data type.
  • When we store a character in memory, we actually store a unique numeric code associated with that character in memory.
  • And when the computer is instructed to print characters, it basically prints characters associated with the numeric code.
  • Here's the chart showing ASCII codes of alphabetical characters:

2. Floating data types in C++:

  • Variables holding real numbers are defined by using floating-point data type. In C++  three data types are used to represent floating-point numbers.
  1. float
  2. double
  3. Long double
float area = 64.74; double volume = 134.64534;
  • Values having floating-point types are expressed in terms of precision and range.
  • The accuracy in the fractional part of the value is precision.
  • Range: it is for the range of fractions and numbers.
  • The floating point number is stored as mantissa E or the power of 10.

3. Void data type

  • The meaning of void is without any value and is used where functions do not return any value.
  • A function does not take any argument when the void is used to define an empty parameter list and a function does not return any value when it is used to return value to the function.
  • 0 bytes of memory is allocated to it and hence it cannot store anything. As a result, it cannot be used to declare simple variables but it can be used to define generic pointers.

C++ Void Pointer

#include <iostream> using namespace std; int main() { void* ptr; float f = 2.3f;   // assign float address to void ptr = &f;   cout << &f << endl; cout << ptr << endl;   return 0; }
Output
0xffd117ac 0xffd117ac

Bool and wcha_t:

  • In C++, Boolean and wide-character data types are also used.
  • Boolean values are defined by bool data type.
  • Bool data type contains only 2 integers 0 and 1.
  • False is represented by 0 and 1 is used to represent true.
  • Only 1 bit of storage is required by bool data type.
  • As it is stored as an integer so it can be considered as an Integral data type. The results of logical operations performed on data are represented by the bool data type.

bool cond = false;

  • In addition to char data type, wchar_t is used to store 16- bit wide characters in C++. Large character sets are allocated with non-English languages so wchar-t is used to store wide characters.

wchar_t test = $# // storing dollar and hash character;

User-Defined Data Types in C++

C++ provides various user-defined data types
  • structures, 
  • unions, 
  • enumerations and
  • classes.

Structure, Union and class

Important features of the C language are structures and unions. Similar or dissimilar data types assigned a single name are grouped by structure and union. However, in C++ the concept of structure and union is modified by adding some new features to provide support to object-oriented programming. Class is defined as a new user-defined data type by C++ and it forms the basis of object-oriented programming. A class functioned as a template that can be used to define the data and functions that are included in an object of a class. Classes are declared using the keyword class. The object of the class can be created when the class is declared.

Enums in C++

A set of integer constants that are named and specify all the values that can be assigned to variables Enumerators are the set of these permissible values. For example, consider the statement.

enum Colour{red, green, blue, white};       // declaring an enum type

  • In this statement, an enumeration data-type color (Colour is a tag name), consisting of enumerators red, green, blue and white is declared.
  • These enumerators represent only integer values, so any arithmetic operation can be performed on them.
  • By default, the first enumerator in the enumeration data type will have the value zero.
  • The value of the next enumerators is increased by one. Hence,
    • the value of red is 0,
    • the value of green is 1
    • the value of blue is 2 and
    • the value of white is 3.
We can also assign values explicitly to enumerators as shown here.
enum country {US, UN=2, India, china} ;
  • Value for the US is 0 by default in this declaration
  • the value of UN is 2
  • Russia is 3 and
  • China is 4
When enum is declared then its variables assign the values specified in enum.

country country1, country2;

For example, consider these statements.
  • Country1 Pakistan; // valid
  • country2 China; // invalid
Int data types can not be assigned to enumerators because they are treated as integers.

Derived Data Types in C++

Derived data types are derived from built-in data types. C++provide 4 major derived data types that are
  • arrays, 
  • Functions, 
  • references and
  • pointers.

Array

  • The set of elements having the same data type and same name formed an array.
  • In memory, all the elements are stored one after another location.
  • An index or subscript is used to access an element.
  • The position of the element is indicated by the subscript value.

Declaring Arrays:

  • Syntax to declare a one-dimensional array:
//intExp indicates number of elements dataType arrayName[intExp]; //declares array num containing 4 elements of type int: //num[0], num[1], num[2],and num[3] int num[4];

Accessing Array Elements:

  • Syntax to access array element:
 
// intExp is used to specify position array Name[intExp]   //fourth element in array num num[3];
One dimensional array example
  1. Initialize
  2. Input
  3. Output
  4. Sum and Average
  5. Find largest element value
  6. Find the smallest element value
  // name of the constant is initialized const int arraySize=5;   double list[arraySize];   //initialize 7 variables int i=0; double smallest=0.0; double largest=0.0; double sum=0.0; double average=0.0; int maxi=0; int mini=0;   //1. Array us initialized for (i=0; i < arraySize; i++) list[i]=0.0;   //2. Give value for each element in array list, beginning w/first element for (i=0; i < arraySize; i++) cin >> list[i];   //3. Resulted value for each element in array list, beginning w/first element for (i=0; i < arraySize; i++) cout << list[i] << " ";   //4. Sum and Average elements in array list, and display for (i=0; i < arraySize; i++) sum = sum + list[i]; average = sum / arraySize;   cout << "Sum = " << sum; cout << "\nAverage = " << average;   //5. find largest element value in array list, and display for (i=0; i < arraySize; i++) if (list[maxi] < list[i]) maxi = i; largest = list[maxi];   cout << "\nLargest = " << largest;   //6. find smallest element value in array list, and display for (i=0; i < arraySize; i++) if (list[mini] > list[i]) mini = i; smallest = list[mini];   cout << "\nSmallest = " << smallest;

 Function in C++

  • The function is used to carry out a specific well-defined task. It is a self-contained program segment.
  • In C++ one or more functions can be used in a program and can be invoked from the other parts of the program when needed.
#include <iostream> using namespace std; int fact(int n); // function prototype   int main(){ int nv,ans; cout<<" Input n:"; cin>> nv; ans = fact(nv);// calling a function cout<<"Answer is:"<<ans<<endl; }
int fact(int n){  // int to another int int ans =1; for(int i= 3; i<= n; i++) ans *=i; return ans are; // function providebanswer to the caller }
function prototype, calling main program and the complete function definition shown in the above program

C++ Reference

The alternate name of the variable is a reference. So we can say that a reference is an alias for the variable in the program. Both variable and reference allocate the same memory location so they can be interchangeably used in a program. When we make changes in variables, these changes are also made in reference and vice versa. –  reference type variable in C++ is treated as a constant pointer that can be dereferenced.
  • Constant reference type variable must be initialized first and can not be used as a reference to other variables.
  • Ampersands (&) are used with reference type variables. For example,
int result  = 0; int &ref_result =  result; … ref_result =  100;

C++ Pointers

  • The variable which can be used to store the memory address of another variable is called a pointer.
  • Memory is used dynamically by pointers.
  • In run time, memory can be allocated and de-allocated with the use of pointers which increases the efficiency of the program.
  • Assignment and dereferencing are two major operations performed by pointers. Assignment operation assigns a value to the pointer and dereferencing takes reference by indirection technique.
  • If ptr is a pointer variable with the value 7080,  and the cell whose address is 7080 has the value 206, then the assignment j = *ptr sets j to 206.
  • The assignment operation j = *pta
  • Pointers should be used with care because they are flexible.
  • Used for management addressing and dynamic storage.
  • Pointer arithmetic in C++ makes them more interesting than other programming languages.
  • The asterisk (*) is used for dereferencing operation, and the ampersand (&) for producing the address of a variable. For example, in the code
int *ptr; int count, init; … ptr = &init; count =  *ptr
  • single assignment statement can take place the value of two assignment operators.
count =  init;

Example: Pointer Arithmetics in C++

int list[10]; int *ptr; ptr = list;
  • *(ptr+5)   is equivalent to list[5]   and  ptr[5] *(ptr+i)   is equivalent to  list[i]   and  ptr[i] –
  • Domain type is not needed to be fixed.
So, that was all for today. I hope you have enjoyed today's lecture. In the next tutorial, we will discuss the variables and constants in C++. Stay tuned !!! :)

 Introduction to C++

Hello friends, I hope you all are doing great. In today's tutorial, I am going to give you a detailed introduction to the C++ Programming language. In cross-platform programming languages, C++ is the most popular that can be used to work on low and high-level applications. Bjarne Stroustrup was the founder of C++. He modified C language to develop C++ language. Control over system resources and memory can be attained by using C++. In 2011, 2014, and 2017 it was modified to C++11, C++14, and C++17. C++ is a middle-level language. It is advantageous to both programming languages low-level (drivers, kernels) and higher-level applications (games, GUI, desktop apps etc.).

Uses of C++

C++ is one of the world's most famous programming languages. It is used in today's OS, embedded systems and GUIs. It provides a clear structure to programs, permits codes to be reused and lowering development costs as its an object-oriented language. Since it is portable and can be used to create applications that can be used on multiple platforms. It is very easy to learn. As it is close to C# and Java, so switching to C++ or vice versa is very simple.

It is used in

  • Operating systems e.g. Linux-based OS 
  • Browsers like UC browser, chrome, opera and firefox.
  • Games and graphics e.g. Photoshop
  • Clouds like Dropbox
  • Database engines like reedit

Features of C++

Rich library support:

  • It is a simple language as programs can be split into logical units and parts. It has rich library support and many data types.

Platform Dependent and Machine Independent:

  •  It is machine-independent but platform-dependent. It does not run on windows but is executable on Linux.

Middle-level language:

  • It is a middle-level language as we can do both low-level programmings(drivers, kernels, networking etc.) and build large-scale user applications (Media Players, Photoshop, Game Engines etc.) as a high-level language.

3rd party libraries:

  • C++ has rich library support as well as 3rd party libraries (e.g. Boost libraries) for easy, smart and rapid development.

Fast execution:

  • For C++ speed of execution is very fast because it is compiled and highly procedural language.
  • Garbage-collection, dynamic typing etc. slow the execution of the program overall. Since there is no additional processing in C++ so it is fast than others.

Provides direct Memory-Access:

  • It provides pointer support to manipulate storage addresses. This helps in low-level programming ( indirect control over memory addresses).

Object-Oriented language:

  • It is better than C with respect to object orientation that helps it to maintain extensible programs so large-scale applications can be built easily.
  • Its friends and virtual features violate some important rules rendering it a completely object-oriented language.

Amazing facts of C++:

Some interesting facts about C++ are listed below

  • C++ name tells us that C language modified with ++ incremental operator is C++ language
  • The most famous language C ++ is used in commercial software.
  • Four primary features of OOP are supported by C++
    1. Inheritance
    2. Encapsulation
    3. Abstraction, and
    4. Polymorphism
  • From Simula67 Programming language C++ gained the features of OOP.
  • For a C++ program to execute(at least main() function) , a function is the least requirement.

Basic concepts of C++ :

Basic concepts like syntax, variables, loop type etc will be discussed here.

Syntax of C++:

Here is the C++ basic program

#include <iostream.h> using namespace std; int main() { cout << "Hi this is C++"; }
  • iostream is a header file and provides us with input & output streams.
  • namesspace std tells the compiler to use standard namespace. It can be used in 2 ways.
  • the return type of main () is int.
  • count << is used to print anything on the screen.

Comments in C++:

  • // is used to add single comment. For multiple comments /*multiple comments*/ is used

Data types in C++:

There are built-in as well as user-defined data types in C++.

  • In C++, classes are user-defined data types.
  • Built-in data types are int, float, double etc.
  • Derived data types are Array, function, pointer and reference.

C++ Program to get a sum of 3 numbers

//Program to receive three integer numbers and display their sum #include <iostream> using namespace std; int main() {       int num1, num2, num3, Sum;       //variables num1, num2, num3 and sum are declared as integers cout << "\n Enter Number 1: "; cin >> num1; cout << "\n Enter Number 2: "; cin >> num2; cout)<< “\n Enter Number 3: “; cin>>num3; Sum = num1 + num2 + num3; cout << "\n The sum of " << num1 << num2 “ and " << num3 << " is " << Sum; }

Modifiers in C++

In C++, special words(called modifiers) are used to modify built-in data types. There are four main data type modifiers in C++, they are:

  • Long
  • Short
  • Signed    and
  • unsigned

These modifiers are with built-in data types to make them more precise and for expanding their range.

  • long and short modify the maximum and minimum values that a data type can hold.
  • Signed types include both +ive and _ive numbers as is the default type.
  • Unsigned, numbers do not have any sign, so they are always positive.

Variables in C++ :

  • Variable is used in C++ to store any value, which can be changed in the program.
  • Variable is declared in many ways each with different memory location and functioning.
  • It is the name of the memory location allocated by the compiler to the variable.

Variables are divided into two main types,

  • Global Variables
  • Local variables

Global variables

Global variables are those which declared only a single time and used again and again. They are declared outside the main() function. If only declared then assigned different values at different times in program lifetime. But when they are declared and initialized at the same time then they can be assigned any value at any point in the program.

For example: Only declared, not initialized

include <iostream> using namespace std; int x;                // Global variable declared int main() { y=10;                 // Initialized once cout <<"first value of y = "<< y; y=20;                 // Initialized again cout <<"Initialized again with value = "<< y; }

Local Variables

  • Local variables exist only between the curly braces, in which they are declared.
  • Outside the curly braces, they are unavailable and lead to a compile-time error.
Example :
include <iostream> using namespace std; int main() { int j=10; if(j<20)        // if condition scope starts { int m=100;   // Local variable declared and initialized }              // if condition scope ends cout << m;      // Compile time error, m not available here }

C++ Program to find the curved surface area of a cylinder (CSA) (CSA = 2 pi r * h)

#include <iostream> using namespace std; int main() { float pi = 3.14, Radius, Height, CSA; cout << "\n Curved Surface Area of a cylinder"; cout << "\n Enter radius (in cm): "; cin >> Radius; cout << "\n Enter height (in cm): "; cin >> Height; CSA = (2*pi*Radius)*Height;       system("cls"); cout << "\n radius: " << Radius <<"cm"; cout << "\n height: " << Height << "cm"; cout << "\n Curved Surface Area of a Cylinder is " << CSA <<" sq. cm."; }

Output:

  • Curved Surface Area of a cylinder
  • Enter radius (in cm): 7
  • Enter height (in cm): 20
  • radius: 7cm
  • height: 20cm
  • The curved Surface Area of a Cylinder is 879.2 sq. cm.

Operators in C++ :

  • Operators take one or more arguments and generate a new value.
  • For example : addition (+), subtraction (-), multiplication (*) etc, are all operators.
  • These are used to perform different operations on variables and constants.

Errors in C++:

There are three types of errors that occur in C++ programming

Syntax Error:

  • The syntax is a set of grammatical rules to make a program. Every programming language has unique grammatical rules.
  • when grammatical rules of C++ are violated Syntax Errors occur.
  • For example: if you type as follows, C++ will throw an error.

 cout << “Hi welcome to C++”

  • As per the grammatical rules of C++, there should be a semicolon at the end of the statement. But, this statement does not end with a semicolon so Syntax Error occurs.

Logical Error:

It may be happened by the wrong use of variable or operator or order of execution etc. This means that the program is grammatically correct, but it contains some logical errors. So, “Logic Error” is also called Semantic error.

Run time error:

  • During the execution of the program when some illegal action takes place, run time error occurs
  • For example, if a program tries to open a file that does not exist then it will result in a run-time error.

Control Statements in C++:

  • The sequence of flow of instructions is changed by the use of control Statements.

Selection statement

  • Statements can run sequentially, selectively or iteratively in a program. Sequence, selection and iteration processes are handled by every programming language.
  • If the statements are executed sequentially then the flow is called a sequential flow. In some situations, if the statements alter the flow of execution then this flow is called a control flow.

Sequence statement

  • The sequential statement is executed one after the another only once from top to bottom.
  • These statements do not alter the flow of execution and are called sequential flow statements. These statements always end with a semicolon (;).

Selection statement

  • When a condition is provided then selection statements are used.
  • In case when the condition is true then a true block (a set of statements) is executed otherwise a false block is commanded to execute.
  • This is also called a decision statement because it helps in making decisions for the set of statements to be executed.
  • Selection statements are if, if-else and nested if statements.

if statement

  • The general syntax of the if statement is:
if (expression) true-block; statement-x;
  • and flow chart for if statement is

 if-else statement

  • The syntax of the if-else statement is given below:
if ( expression) {       True-block; } else {       False-block; }
  • And the flow chart for if-else statement is:

C++ program to find either number is Even or Odd

#include <iostream> using namespace std; int main() { int Num, rem; cout<< "\n enter a number: "; cin>>Num; rem = Num % 2; if (rem==0) cout<< "\n The given number" <<Num<< " is Even"; else cout<< "\n The given number "<<Num<< " is Odd"; return 0; }

Output

  • Enter number: 12
  • The given number 12 is Even

Nested if

It has three forms
  • If nested inside if part
  • If nested inside else part
  • If nested inside both if part and else part

Iteration statement

  • The iteration statement is a set of statements that are executed again and again depends upon conditions.
  • If a condition evaluates to true, the set of statements (only true) is executed again and again.
  • As soon as the condition seems to be false, the repetition stops. This is also known as looping statement 
  • The set of statements that are executed repeatedly is called the body of the loop.
  • The condition on which exits from the loop is called exit-condition or test-condition.
  • There are 3 kinds of loops in C++
    1. For loop
    2. While loop
    3. Do while loop

for loop

  • The for loop is the easiest loop which allows code to be executed again and again.
  • The general syntax is:
for (initialization(s); test expression; update expression(s)) {      statement 1;         statement 2;       …………. }

C++ program to sum from 1 to 5 using for loop

#include <iostream> using namespace std; int main () { int i,Sum=0; for(i=1; i<=5;i++) { sum=sum+i; } cout<<"The sum of 1 to 5 is "<<Sum; return 0; }

Output

  • The sum of 1 to 5 is 15

While loop

  • It allows the loop statements to be executed as long as the condition is true.
  • The while loop syntax is:
while ( test expression ) {       body of the loop; }
  • Flow chart for while loop is given below

 C++ program to sum from 1 to 6 using while loop

#include <iostream> using namespace std; int main () { int i=1,SUM=0; while(i<=6) { SUM=SUM+i; i++; } cout<<"The sum of 1 to 6 is "<<SUM; return 0; }

Output

  • The sum of 1 to 6 is 21

do-while loop

  • The do-while loop is used as an exit-controlled loop. In a do-while loop, after executing the body of the loop, the condition is evaluated.
  • The do-while loop syntax is:
do {       body of the loop; } while(condition);
  • The flow chart of the do-while loop is shown below

 Examples of C++ programs:

1. C++ Program to find the Total marks of three subjects

#include <iostream> using namespace std; int main() { Int n1, n2 , n3, Sum; cout << "\n Enter Mark 1: "; cin >> n1; cout << "\n Enter Mark 2: "; cin >> n2; cout << "\n Enter Mark 3: "; cin >> n3; Sum = n1 + n2 + n3; cout << "\n The sum = " << Sum; }

2. C++ program to find the Area of a Circle

#include <iostream> using namespace std; int main() { int Radius; float Area; cout << "\n Enter Radius: "; cin >> Radius; Area = 3.14 * Radius * Radius; cout << "\n The area of circle = " << Area; }
So, that was all for today. In the next tutorial, we are going to discuss the Data Types in C++ in detail. If you have any questions regarding this tutorial, ask in the comments. Thanks for reading !!!

How to use Comments in C++

Hello friends, hope you all are fine and enjoying your lives. Today, I am going to show you How to use comments in C++. In the previous tutorials, we first have a look at Introduction to C++ in which we have discussed a simple c++ program. After that we have discussed How to use Escape Sequence in C++, which is also essential because escape sequence is a very simple concept but is used quite a lot on C++ projects os you must have its knowledge.

Today, we are gonna discuss Comments in C++ i.e. how to use Comments in C++ and why to use Comments in C++. Just like escape sequence, comments in C++ is also very basic concept but its really important and a programmer must know How to use Comments because without it the code becomes really difficult and is quite difficult to debug. So, let's get started with How to use Comments in C++.

How to use comments in C++ ??

  • Let me first explain what are comments in c++.
  • Suppose you are working on some project in C++ and you complete your project and simply forget about it. Then after 2 years, somehow you got the same project and you have to use the same code then you open your code and your face must look like this. :O
  • Because the code is too lengthy and you are not understanding your own code. :)
  • Here comes the benefit of comments.
  • Comments are not part of your code, Instead they are just used to add additional writing about the code from which you can remember what this code is actually doing.
  • Let me add some comments in the Hello World program which we have designed in the Introduction to C++ tutorial.
#include <iostream> // Including Library
 
using namespace std; // Including Namespace Standard
 
int main(void) // Starting the Main Loop
{
     cout<<"Hello World!!!"<<endl; //Printing Hello World in output
     return 0; // Returning 0 value
}
  • Now in the above code you can see I have used additional lines in front of each command.
  • These additional lines are called comments and as the name suggests these are the comments about the code.
  • So, now by simply looking at the code you can understand what each line is doing.
  • Now you must have noticed that before starting each comment, I have used // two forward slashes.
  • So, in C++ whenever you add two forward slashes, the compiler simply ignores everything written in front of these slashes, and these are called comments.
  • Its one way to add a comment in C++.
  • Now, sometimes there's a case when you need to add like four to five comment lines in your code then in order to add // this sign before each line you can simply enclose all the comments in between /* Here's your comment */.
  • Let's have a look at this comment system below:
/*
Hello World Code
Designed by: www.TheEngineeringProjects.com
This code will print Hello Wold on output.
Date: 5/19/2016
*/

#include <iostream> // Including Library
 
using namespace std; // Including Namespace Standard
 
int main(void) // Starting the Main Loop
{
     cout<<"Hello World!!!"<<endl; //Printing Hello World in output
     return 0; // Returning 0 value
}
  • So, in this way you can add the comments in /* */ these signs.
  • You can see in above code that in the start I have given a small explanation of the project and have mentioned who designed it and when designed it.
  • So, you can add such description in the comments in C++.
  • Another benefit of code comes in debugging of your project.
  • You think that soe of your code is not working properly then you can simply comment that code and test the remaining.

So, these are different uses and benefits of comments in C++. I hope you guys get some knowedge out of it. So, that's all for today, will meet you guys in the coming tutorial.

How to use Escape Sequence in C++

In today's tutorials, we are going to have a look at escape sequence in C++. In our previous tutorial, Introduction to C++ we have designed a small Hello World program and if you haven't studied it yet then you should first check that one out as I am gonna take it further from there.

In that tutorial, we have designed a code which prints the Hello world on the output screen. The code used for printing it on the output screen is as follows:

How to use Escape Sequence in C++ ??

  • Now, suppose if I want to print out "Hello World" , instead of Hello World.
  • In simple words, I wanna add "" these symbols as well on each side of Hello World.
  • But if you add them in the above program then it will generate errors.
  • So, what to do now ? Here comes the benefit of escape sequence in c++.
  • The escape sequence used to print "" these symbols in output is this symbols which is also know as back slash.
  • So, now by using this escape sequence, the code will look like something as shown below:
#include <iostream>
 
using namespace std;
 
int main(void)
{
     cout<<""Hello World!!!""<<endl;
     return 0;
}
  • Now in this way we can quite easily print the "Hello World" on the screen.
  • Now suppose you want to print itself then again what you need to do is to write two back slashes like this .
  • The first back slash is the escape sequence while the second one will print as it is.
  • There are many other uses of this back slash like if we add n after this escape sequence then it will work as a new line so instead of using this endl, we can use n as shown in below code:
#include <iostream>
 
using namespace std;
 
int main(void)
{
     cout<<""Hello World!!!"n";
     return 0;
}
  • Now you can see in the above code I have used n and removed the endl and still it will work the same.
  • Now if you want to and a TAB in the output then you can use t.
  • So, there are many benefits of this escape sequence in c++.
  • Similarly r is used for carriage return.
  • v is used for vertical tab.
  • b is used for backspace.
These are different escape sequence uses in C++ and I hope you have got it now that How to use Escape sequence in c++. In the coming tutorial, I will explain How and why to use comments in C++. That's all for today, take care and have fun !!! :)

Introduction to C++

Hello friends, hope you all are fine and having fun with your lives. Today, I am going to start a new series of tutorials on C++ Programming. and here's my first tutorial in this series which is Introduction to C++. I am gonna share a lot of tutorials in this series in future, in which I am gonna explain all about C++. In the initials tutorials, we will cover the basics of C++ Programming and later on we will also cover the pro concepts of C++ Programming.

I am planning on posting around 20 to 30 tutorials in this C++ Programming series, and I am quite sure that it will cover all about C++ and if you are a new learner then it will help you quite a lot.. I have started this series on a request of one of my readers. He suggested me this idea and I like it quite a lot so I though to pursue it. So, today let's have a look at Introduction to C++, which is quite essential when you are learning a new language you must have its introduction first.

Introduction to C++

  • So, now let me first write a simple C++ code, which is gonna print Hello World on the screen.
  • Below is given the very basic C++ code and I am gonna explain this code below to give an Introduction to C++ in detail:
#include <iostream>

using namespace std;

int main(void)
{
     cout<<"Hello World!!!"<<endl;
     return 0;
}
  • The above code is the simplest C++ code which is gonna print Hello World on the screen.
  • If you read the above code from start then you can see the first statement in the above code is #include <iostream>.
  • This first statement is actually including a library in our code file.
  • The C++ Compiler already has a lot of libraries in it which we use in our program and can get benefit out of it.
  • So, now question is what are these libraries. In any compiler the libraries are designed to create functions and then you can use these functions quite easily.
  • Let me explain it in a simple way. For example you want to add two numbers 2 + 2, now you know that the operator + is used for addition but the C++ won't know about it unless you add the library for math.
  • So, here we want to print something on our screen so the C++ will not print it on the screen unless we include this iostream library in it.
  • There are many builtin libraries for C++ like conio, arithmetic etc. which we will cover in later tutorials.
  • But for rite now, I think you have got the idea what is library, and you really don't need to know what they are doing. :)
  • Next line used is using namespace std, its a namespace standard library and you just have to add it as it is in the C++ Library.
  • Now next we have the int main(void) command. Its basically a function, which is called the main function.
  • In C++ the compiler works top to bottom and the first thing it goes into is the main function so your code must have the main function otherwise it will generate error.
  • This Main function is of the form as shown below:
int main(void)
{
  
}
  • Now in this main function, you can add anything you wanna add or execute.
  • We can create many functions in C++ coding which we will surely cover in coming tutorials but the Main function will always remain single means you can't add another Main function in it.
  • Now after the Main function, we have added a line whose initials are cout, its a c++ commands which is used to print something out and you can see rite after cout we have written a string "Hello World!!!".
  • So, because of cout command our code is printing this Hello World on the screen.
  • If you notice we have << these signs between cout and our string to print.
  • These signs are called insertion operators.
  • At the end of this statement we have endl, which is called end line, and its similar to pressing enter button and after it we have our semi colon (;). Semi colon tells the C++ that our statement is ended.
  • So, as a whole its called a statement, and in this statement we first printed out Hello World!!! and then we Entered and finally we added a semi colon to tell our program that statement has ended.
  • Now in the next statement we have return 0; , it will return nothing back and will just stop.
  • So, in our simple above program we have Main function with two statements and its printing Hello World on the screen.
  • It was kind of an Introduction to C++ in which we have designed a small program and then discussed it.
So, that's all about the introduction to C++, and I hope you guys have learned something out of it. In the coming tutorials, I am gonna post more about C++ and we will cover about variable used in it and how we can make complex codes on c++. So stay tuned and have fun !!! :)
Syed Zain Nasir

I am Syed Zain Nasir, the founder of <a href=https://www.TheEngineeringProjects.com/>The Engineering Projects</a> (TEP). I am a programmer since 2009 before that I just search things, make small projects and now I am sharing my knowledge through this platform.I also work as a freelancer and did many projects related to programming and electrical circuitry. <a href=https://plus.google.com/+SyedZainNasir/>My Google Profile+</a>

Share
Published by
Syed Zain Nasir