You are on page 1of 58

Structure of C++

program
Output Operator

 C++ introduces two new features, cout and << .


 The identifier cout is a predefined object that represents the standard output
stream in C++
 The standard output screen represents the the screen
 The operator << is called insertion operator or put to operator.
 It sends the content of the variable on its right to the object on the left.
 Example: cout<< “C++ is better than C”;
Input Operator

 The identifier cin is a predefined object in C++ that corresponds to the


standard input stream.
 Input stream represents the keyboard.
 The operator >> is known as the extraction or get from operator.
 It extracts the value from the keyboard and assigns it to the variable on its
right.
 It is similar to scanf
 Example: cin >> number1
iostream file

 # include <iostream>
 This directory causes the pre processor to add the contents of the iostream
file to the program.
 It contains declarations for the identifier cout and the operator <<.
 Some old versions of C++ uses a header file called as iostream.h
 The header file must be included at the beginning of all the program that
contains the input- output statements.
Return type main()

 In C++ main() returns an integer type value to the operating system.


 Therefore, every main() in C++ ends with a return(0) statement ; otherwise,
an error or a warning might occur .
 Since the main() returns an integer type value return type of the main
method is explicitly set to null.
Namespaces

 Namespaces is a new concept introduced in C++


 It defines a scope for the identifiers used in the program
 For using identifiers namespaces scope must be defined using directive such
as
using namespace std;
 Here std is the namespace that defines ANSI C++ libraries
 All the C++ program must include this directory
A simple C++ program
# include <iostream>
using namespace std;
int main()
{
float num1,num2, sum, avg;
cout << “Enter two numbers “;
cin >> num1;
cin >> num2;
sum = num1+ num2;
avg = sum /2 ;

cout << “ sum= “ << sum << “\n”;


cout << “ avg =“ << avg << “\n”;

return 0;
}
Tokens

 The smallest individual units in the program are known as tokens


 C++ has the following tokens
 Keywords
 Identifiers
 Constants
 Strings
 Operators
Keywords

 Keywords implement specific C++ language features.


 They are explicitly reserved keywords and cannot be used as the names for
the program variables or other user- defined program elements.
 Many of the keywords are common in C and C++ programming language
 Additional keywords in C++are as follows
1. auto
2. break
3. continue
4. static
5. default and many more
Identifiers and Constants
 Identifies refers to the names of variables, functions, arrays classes etc
entered by the programmers
 There are fundamental requirements of every programming language.
 Each language has its own rules for naming an identifiers
 Rules are common for C and C++
1. Only alphabetic character, digit and underscore are permitted
2. The name cannot start with a digit
3. Uppercase and lowercase characters are distinct
4. A declared keyword cannot be used as a variable name
Constants

 Constants refer to fixed values that do not change during the execution of the
program

 They include integers, characters , floating point numbers and strings


Basic data types
 Both C and C++ compilers support all the built in data types
 With the exception of void datatype the basic datatype have several
modifiers preceding them to serve the need of the situation
 The modifiers signed and unsigned , long and short can be applied to
character and integer data types
 However the modifier long can also be applied to double data types
 The void datatype is used to specify two things
1. To specify the return type of a function when it is not returning any value
2. To indicate an empty argument list of a function
 Example: void funct1 (void)
Datatypes
User defined datatypes
1. Structures
 A structure is a user-defined data type in C/C++.
 A structure creates a data type that can be used to group items of possibly different
types into a single type.
struct structureName
{
member1;
member2;
member3;
. . . memberN;
};
Unions
 union is a user defined data type.
 In union, all members share the same memory location.
 Size of union is decided by the size of largest member of union.
union union_name
{  
member definition;
} union_variables;
Classes
 A class is a user-defined data type that we can use in our program, and it works
as an object constructor, or a "blueprint" for creating objects.
class MyClass
{       
             
    int myNum;       
 
    string myString;  
};
Enumeration

 Enum is a user defined data type


 In this we specify a set of values for a variable and the variable can only take one out of
a small set of possible values. We use enum keyword to define a Enumeration.
enum week {sun,mon,tue,wed,thu,fri,sat};
Derived Data types
1. Arrays
 An array in C or C++ is a collection of items stored at contiguous memory locations
and elements can be accessed randomly using indices of an array.
 They are used to store similar type of elements as in the data type must be the same for
all elements.
 They can be used to store collection of primitive data types such as int, float, double,
char, etc of any particular type. 
 Example : char string[3] = “xyz” ;
Functions

 A function is a block of code which only runs when it is called.


 You can pass data, known as parameters, into a function.
 Functions are used to perform certain actions, and they are important
for reusing code: Define the code once, and use it many times. In
 Example :
void myFunction()
{
  // code to be executed
}
Pointers

 A pointer however, is a variable that stores the memory address


as its value. 
 A pointer variable points to a data type (like int or string) of the
same type, and is created with the * operator.
 Example : int *ip
Symbolic constants
 Symbolic constant is a way of defining a variable constant whose value
cannot be changed.
 It is done by using the keyword const.
 Example : const int size = 10;
Operators C++

 Arithmetic operator
 Comparison operator
 Assignment operator
 Logical operator
 Bitwise operators
Arithmetic operator

 + : Adds two operands


 - : Subtracts second operand from the first
 *: Multiplies both operands
 /: Divides numerator by denominator
 %: Modulus Operator and remainder of after an integer division
 ++: Increment operator, increases integer value by one.
 —: Decrement operator, decreases integer value by one.
#include <iostream>
using namespace std;
int main()
{
int x, y;
int sum;
cout << "Type a number: ";
cin >> x;
cout << "Type another number: ";
cin >> y;
sum = x + y;
cout << "Sum is: " << sum;
return 0;
}
Comparison operator
 ==: Checks if the values of two operands are equal or not, if yes then
condition becomes true.
 != : Checks if the values of two operands are equal or not, if values are not
equal then condition becomes true.
 > : Checks if the value of left operand is greater than the value of right
operand, if yes then condition becomes true
 < : Checks if the value of left operand is less than the value of right operand, if
yes then condition becomes true
 > = : Checks if the value of left operand is greater than or equal to the value of
right operand, if yes then condition becomes true.
 < = : Checks if the value of left operand is less than or equal to the value of
right operand, if yes then condition becomes true.
Logical operators

 && : Called Logical AND operator. If both the operands are non-zero, then
condition becomes true.
 || : Called Logical OR Operator. If any of the two operands is non-zero, then
condition becomes true.
 ! : Called Logical NOT Operator. Use to reverses the logical state of its operand.
If a condition is true, then Logical NOT operator will make false.
Bitwise operator

 & : Binary AND Operator copies a bit to the result if it exists in both operands.
 | : Binary OR Operator copies a bit if it exists in either operand.
 ^ : Binary XOR Operator copies the bit if it is set in one operand but not both.
 ~ : Binary Ones Complement Operator is unary and has the effect of 'flipping'
bits.
 << : Binary Left Shift Operator. The left operands value is moved left by the
number of bits specified by the right operand.
 >> : Binary Right Shift Operator. The left operands value is moved right by the
number of bits specified by the right operand.
Assignment operator
 = : Simple assignment operator, Assigns values from right side operands to left
side operand.
 += : Add AND assignment operator, It adds right operand to the left operand
and assign the result to left operand. ( C+=A ; C=C+ A)
 -= : Subtract AND assignment operator, It subtracts right operand from the left
operand and assign the result to left operand.
 *= : Multiply AND assignment operator, It multiplies right operand with the left
operand and assign the result to left operand.
 /= : Divide AND assignment operator, It divides left operand with the right
operand and assign the result to left operand.
 % = : Modulus AND assignment operator, It takes modulus using two operands
and assign the result to left operand.
Control Structures
 Control Structures are just a way to specify flow of control in programs.
 Any algorithm or program can be more clear and understood if they use self-contained
modules called as logic or control structures.
 It basically analyses and chooses in which direction a program flows based on certain
parameters or conditions. 
 One method of achieving the objective of an accurate error resistant and maintainable
code is to use one or any combination of the following three control structures
1. Sequential structure ( straight line)
2. Selection structure ( branching)
3. Loop structure ( iteration or repetition)
Sequential Structure
 Sequential Logic (Sequential Flow)Sequential logic as the name suggests follows a
serial or sequential flow in which the flow depends on the series of instructions given to
the computer.
 Unless new instructions are given, the modules are executed in the obvious sequence.
 The sequences may be given, by means of numbered steps explicitly. Also, implicitly
follows the order in which modules are written. 
 Most of the processing, even some complex problems, will generally follow this
elementary flow pattern.
Sequential structure
 Selection structures are implemented using If , If Else and Switch statements.
 Looping structures are implemented using While, Do
While and For statements.
The simple If statement
 if (condition) statement
where condition is the expression that is being evaluated. If this condition
is true, statement is executed.
 If it is false, statement is ignored (not executed) and the program continues on the
next instruction after the conditional structure.
 For example, the following code fragment prints out x is 100 only if the value stored in
variable x is indeed 100:

 if (x == 100)
  cout << "x is 100";
If- else
 We can additionally specify what we want that happens if the condition is not fulfilled by
using the keyword else.
 Syntax:

if (condition) 
statement1 
else 
statement2

For example:
if (x == 100)
  cout << "x is 100";
else
  cout << "x is not 100";
While loop

 While loop is an entry controlled loop.


 Syntax:
while(condition)
statement
Do- while loop

 Its functionality is exactly the same as the while loop except that condition in the do-


while is evaluated after the execution of statement instead of before, granting at least
one execution of statement even if condition is never fulfilled.
 Syntax:
do statement while (condition);
 Do while is an exit- controlled loop
For loop

 For loop is an entry controlled loop.


 It is used when an action is to be repeated for a predetermined number of
times.
 Syntax:
for( initial value, test, increment)
{
action 1;
}
action 2;
Switch statement
 It is a multiple branching statement where based on a condition the control is
transferred to one of the many possible points.
 Syntax is as follows:
switch(expression) case3: switch (x)
{ { {
case1: action; case 1:
{ }
cout << "x is 1";
action; case4:
break;
{
} case 2:
action;
case2:
}
cout << "x is 2";
{
default: break;
action;
{ default:
}
action; cout << "value of x unknown";
} }
}
Break statement
 Using break we can leave a loop even if the condition for its end is not fulfilled.
 It can be used to end an infinite loop, or to force it to end before its natural end.
 Example:
 #include <iostream>
cout << n << ", ";
int main ()
if (n==3)
{
{
int n;
cout << "countdown aborted!";
for (n=10; n>0; n--)
break;
{
}
}
return 0;
}
Continue Statement
 The continue statement breaks one iteration (in the loop), if a specified condition
occurs, and continues with the next iteration in the loop.

 Example:
for (int i = 0; i < 10; i++)
{
  if (i == 4)
{
    continue;
 }
  cout << i << "\n";
}
Arrays
 Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value.
 To declare an array, define the variable type, specify the name of the array followed
by square brackets and specify the number of elements it should store:
string fruits[4];
Example:
string fruits[4] = {“Apple", “Mango", “Orange", “Grapes"};

 To create an array of three integers


int myNum[3] = {10, 20, 30};
 Access the Elements of an Array
You access an array element by referring to the index number.
Example:
string fruits[4] = {“Apple", “Mango", “Orange", “Grapes"};
cout << fruits[0];

// Outputs Apple

 Change an Array Element


To change the value of a specific element, refer to the index number.
Example:
string fruits[4] = {“Apple", “Mango", “Orange", “Grapes"};
fruits[0] = “Watermelon";
cout << fruits[0];

// Now outputs Watermelon instead of Apple


Advantages of an Array in C/C++:
 Random access of elements using array index.
 Use of less line of code as it creates a single array of multiple elements.
 Easy access to all the elements.
 Traversal through the array becomes easy using a single loop.
 Sorting becomes easy as it can be accomplished by writing less line of code.
Disadvantages of an Array in C/C++:
 Allows a fixed number of elements to be entered which is decided at the time of
declaration. Unlike a linked list, an array in C is not dynamic.
 Insertion and deletion of elements can be costly since the elements are needed to be
managed in accordance with the new memory allocation.
#include<iostream>

using namespace std;

int main()         cout<<"\n The Elements in the Array are : \n";


{
        int arr[50], num, i;
        for(i=0; i<num; i++)
        cout<<"\n How Many Elements You Want to Store into an Array? \n";
        {
        cin>>num;                 cout<<arr[i]<<"\t";
        }
        cout<<"\n Enter "<<num<<" Elements to Store into an Array : \n";
        return 0;
        for(i=0; i<num; i++) }

        {
                cin>>arr[i];
        }
Multidimensional Array
 In C/C++, we can define multidimensional arrays in simple words as array of arrays. 
 data_type array_name[size1][size2]....[sizeN];
data_type: Type of data to be stored in the array. Here data_type is valid C/C++ data
type
array_name: Name of the array
size1, size2,... ,sizeN: Sizes of the dimensions
Two-Dimensional Arrays
 The simplest form of the multidimensional array is the two-dimensional array.
 A two-dimensional array is, in essence, a list of one-dimensional arrays.
type arrayName [ x ][ y ];
 Where type can be any valid C++ data type and arrayName will be a valid C++ identifier.

Two-dimensional array: int two_d[10][20];


 Total number of elements that can be stored in a multidimensional array can be calculated by
multiplying the size of all the dimensions.
 For example:
The array int x[10][20] can store total (10*20) = 200 elements.
 Two-dimensional array can be thought as a table, which will have x number of rows
and y number of columns. A 2-dimensional array a, which contains three rows and
four columns.
 Thus, every element in array a is identified by an element name of the form a[ i ][ j ],
where a is the name of the array, and i and j are the subscripts that uniquely identify
each element in a.
 Multidimensional arrays may be initialized by specifying bracketed values for
each row.
 Following is an array with 3 rows and each row have 4 columns.
int a[3][4] = { {0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
# include <iostream>
using namespace std;
int main ()
{ // an array with 5 rows and 2 columns.
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}
};
// output each array element's value
for ( int i = 0; i < 5; i++ )
for ( int j = 0; j < 2; j++ )
{
cout << "a[" << i << "][" << j << "]: ";
cout << a[i][j]<< endl;
}
return 0;
}
COLUMN 0 COLUMN 1
a[0][0]: 0 ROW 0 A[0][0]:0 A[0][1]:0
a[0][1]: 0 ROW 1 A[1][0]:1 A[1][1]:2
a[1][0]: 1 ROW 2 A[2][0]:2 A[2][1]:4
a[1][1]: 2 ROW 3 A[3][0]:3 A[3][1]:3
a[2][0]: 2 ROW 4 A[4][0]:4 A[4][1]:8
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
C++ Strings

 Strings are used for storing text.


 A string variable contains a collection of characters surrounded by double quotes
string greeting = "Hello"
 Example
#include <iostream>
#include <string>
using namespace std;
int main()
{
string greeting = "Hello";
cout << greeting;
return 0;
}
String Concatenation
 The + operator can be used between strings to add them together to make a new string. This is
called concatenation
 Example
string firstName = "John ";
string lastName = “Rock";
string fullName = firstName + lastName;
cout << fullName;
 C++ uses the + operator for both addition and  concatenation.
 Numbers are added. Strings are concatenated.
Append
 A string in C++ is actually an object, which contain functions that can perform certain operations
on strings. For example, you can also concatenate strings with the append()function
 Example:
string firstName = "John ";
string lastName = “Rock";
string fullName = firstName.append(lastName);
cout << fullName;
String Length
 To get the length of a string, use the length() function
 Example:
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "The length of the txt string is: " << txt.length();
Access Strings
 You can access the characters in a string by referring to its index number inside
square brackets [].
 Example
string myString = "Hello";
cout << myString[0];
// Outputs H
Change String Characters
 To change the value of a specific character in a string, refer to the index number,
and use single quotes
 Example:
string myString = "Hello";
myString[0] = 'J';
cout << myString;
// Outputs Jello instead of Hello

You might also like