A Guide To C++
A Guide To C++
int main():
The execution of any c++ program starts with the main function, hence it is necessary to have a main function in your
program.
Curly Brackets {}
It is used to indicate the starting and ending point of any function.
return 0
Return signifies the end of a function. Here, the function is main, so when we hit return 0, it exits the program.
Input and Output statements in C++
OUTPUT STATEMENT IN C++: INPUT STATEMENT IN C++:
• The output statement is often used like a ‘print’ • With cin and ‘>>’ operators, it is possible to read input
statement. from the keyboard.
• It is used to either print out statements, or display • It always returns the variable type that you use. [If you
statements along with values. use an integer, you will receive an integer]
• We use the ‘<<‘ operator in the ‘cout’ statement.
• We use ‘endl’ and ‘\n’ at the end of the statement, to have
a new line.
How to use them
Here we declare the variable ‘a’. And by declare we mean that
we create a variable ‘a’ and specify its ‘data type’
The ‘cout’ statement here is used to display the message ‘ENTER THE VALUE
OF A’, this tells the user to input a number.
Then the ‘cin’ statement will assign the number entered as the value of ‘a’.
The ‘cout’ statement here will display the message “VALUE OF A IS:”, and after
displaying that message will display the value assigned to ‘a’ because of the ‘<<a;’
Data types in C+
+
Data types are assigned to variables, in order to specify what kind of data can be stored in them. If a ‘int’ data type is declared,
the variable will only store integers and nothing else.
Data Type Bit size Function Data Tye Bit size Function
char 1 byte Stores alphabets Void 0 Empty
unsigned char 1 byte Bool Stores only true and false
signed char 1 byte
int 2 bytes Numbers without
fractional part
unsigned int 4
signed int 4
short int 2 This is how we declare data
types
Long int 8 Large numbers
Float 4 Numbers with
fractional part
double 8 Same as float
long double 12
Some examples of assigning data types:
The reason why only ‘s’ is displayed, when I’ve entered ‘sada’, is because
the data type assigned to ‘name’ is ‘char’. And ‘char’ can only store one
byte. Hence, only ‘s’ is displayed.
The reason why only 2 is stored in the variable ‘num’ instead of 2.8, is
because the data type assigned to ‘num’ is int, and int doesn’t store
decimal values.
Operators in C++
Operator Meaning LOGICAL OPERATORS
+ Addition Operator Meaning
- Subtraction && Logical AND
* Multiplication || Logical OR
/ Division ! Logical NOT
% Modulo (only reminder is displayed)
Increment and Decrement
RELATIONAL OPERATORS operators
M=5
Operator Meaning
Y = ++M
< Is less than
<= Is less than or equal to M is first incremented to M+1 which is 6 and is
then assigned to Y. So M and Y are both 6.
> Is greater than
>= Is greater than or equal to M=5
== Is equal to Y = M++
!= Is not equal to Y is first assigned to M value, and is then
incremented to 6
When is it TRUE or FALSE
A condition is said to be TRUE if it meets the condition set upon it, and FALSE if not.
The conditional operator is an operator used in C and C++. The ?: operator returns one of two values depending on the result of an expression.
If expression 1 evaluates to true, then expression 2 is evaluated. If expression 1 evaluates to false, then expression 3 is evaluated instead.
SYNTAX:
if(condition)
{
var = X; Var = (condition) ? X : Y;
}
Else
{
var = Y;
}
EXAMPLE:
If(y < 10)
{
var = 30; Var = (y<10) ? 30 : 40
}
Else:
{
var = 40;
}
Operator precedence and
associativity
Operator associativity refers to the way the program executes the code. For example, arithmetic operators are first computed
on the left and then assigned to a variable, hence it associativity is Left to Right.
Operator Category Operators Associativity Function
Unary operators +, -, ++, - - R to L Positive/negative value of a number or
increment and decrement of a number
Arithmetic operators *, /, %, +, - L to R Basic arithmetic functions
Relational operators <, <=, >, >= L to R Verifies the relationship between two
entities. [Ex: (10<y), (x>=y), etc]
Equality operators == , != L to R Checks whether two entities are equal or
not
Logical AND && L to R Displays TRUE only if both conditions are
met
Logical OR || L to R Displays TRUE is any one condition is true
Assignment Operator =, +=, -=, *=, /=, %/ R to L Performs the operation (*, +, -, /) on the
value and then assigns it to the variable.
Constants – what are they and why are they
used
As the name suggests, constants are fixed values. We use them in lengthy or complex evaluations, when the value of a
particular entity won’t change. For example, in a program to find the area of a circle, the value of pi wont change, and if we
keep manually entering the value of pi, there is a possibility of making an error.
Syntax:
• Explicit C++ Type Casting (Here we specify the data type in which the value is to be converted to)
• Implicit C++ Type Casting (Here the compiler automatically converts the value)
In line 10, we perform the operation of a/b. This means that ‘a’ is
divided by ‘b’. This translates to 15/2, which is 7.5, but since it is an
int type, it is saved as 7.
In line 11, we perform the operation a/float(b), this means that ‘a’ is divided by
‘b’, after ‘b’ is converted to a float from an int. It now translates to 15/2.0, which
gives the output 7.5.
In line 12, we perform the operation float(a/b). Since ‘(a/b)’ is in the bracket, a is
divided by b, only after the division is the output converted into a float, which
gives the output 7.
I tend to clean my
kitchen…… but nvm
Take a break
If statements:
Here we first input the numbers 10 and 20, and 10 is assigned to ‘a’ and 20 to ‘b’. Now the condition given is (a>b). With
the current of ‘a’ and ‘b’, the condition is not met or is considered false. Hence the ‘else’ statement is executed
Here we assign ‘a’ as 19 and ‘b’ as 3. Now the condition (a>b) is met or
considered True. Hence the statement is executed
For example:
Here the first ‘if’ loop is from line 11 to 25, and another ‘if’ loop
is nested inside the first ‘if’ loop from line 13 to 20
Else-if Ladder
In C/C++ if-else-if ladder helps user decide from among multiple options. The C/C++ if statements are executed from the
top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and
the rest of the C else-if ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
Syntax: Flowchart:
WRITE A PROGRAM USING ELSE-IF LADDER TO
CALCULATE GRADE FOR THE MARKS ENTERED
If the sales exceed or are equal to 100 and less than or equal to
500, the salesman will receive 10% of the sales.
10% of sales = sales * 0.1
If the sales exceeds 500, the sales person will get 8% of the
sales – 500, plus a 100 extra.
exceed 500 = [(sales – 500) * (0.08) ] + 100
Switch
statement
Switch case statements are controlled statement that is regarded
as a substitute for if-else statements. A switch statement in c++
is a multiway branch statement that provides a way to organize
the flow of execution to parts of code based on the value of the
expression.
getch() is a predefined non-standard function in “conio.h” clrscr() function is also a non-standard function defined in
header. It is used to tell the compiler to wait until the user “conio.h” header. This function is used to clear the console
enters a character. This is often used at the end of the main screen. It is often used at the beginning of the program
function (before the return statement) so that we can see (mostly after variable declaration but not necessarily) so
the output. If we don’t use getch() at the end, the program that the console is clear for our output.
is executed but we cannot see the output.
The below code can be rewritten as shown in the next slide
Hence, if the switch statements are the same, we
can write it like this
Looping Control
Statements
In programming languages – while coding a program, sometimes it is necessary to repeat a set of statements several times
(Looping Control Structures ). A way to repeat statements is to type the same statements in the program over and over.
For example, if you want to repeat some statements 100 times, you type the same statements 100 times in the program.
However, this solution of repeating statements is impractical, if not impossible. Fortunately, there is a better way to repeat a set
of statements.
As noted earlier, C++ has three repetition, or looping control structures that allow you to repeat a set of statements until certain
conditions are met.
Note: The variable that controls the loop is called loop control variable (LCV)
In C++, while is a reserved word. Of course, the statement can be either a simple or compound statement. The expression acts
as a decision maker and is usually a logical expression. The statement is called the body of the loop. Note that the parentheses
around the expression are part of the syntax.
Syntax: Flowchart
Example of while
loop:
The body of the while loop consists of the statements in Lines 3 and
4. The statement in Line 3 outputs the value of x, which is 0. The
statement in Line 4 changes the value of x to 5.
Syntax:
Flowchart:
Line 14: we introduce the while loop and make (I <= n).
This is so that the i doesn’t exceed n.
Line 16: sum is set to sum + I
Line 17: i is set to i + 1;
So just assume you have a list with values - [1,2,3,4,5] and you want to get the sum. A classic way is iterating through all of the elements and
add each number to the variable sum.
sum = (((((1) + 2) + 3) + 4) + 5)
//what i want to express with bracket are the iterations.
But we need to initialize it before using. If we initialized with 1 or another instead of 0 the sum would have a different value - in this case 16.
#version Sum = 0
sum = 0 + (1+2+3+4+5)
= 15
#version sum = 1
sum = 1 + (1+2+3+4+5)
= 1 + 15
= 16
Do while loop
The statement executes first, and then the expression is evaluated. If the expression evaluates to true, the statement executes
again. As long as the expression in a do…while statement is true, the statement executes. To avoid an infinite loop, you must,
once again, make sure that the loop body contains a statement that ultimately makes the expression false and assures that it
exits properly.
Syntax: Flowchart:
LOGIC BEHIND THE PROGRAM:
Line 7: we start the do function. This function is so that we do the
condition.
Line 12: the loop is performed until (x <= 20)
Arrays
Why do we need arrays?
It is a group of variables of similar data types referred to by a single element. We can use normal variables (v1, v2, v3, ..)
Its elements are stored in a contiguous memory location. when we have a small number of objects, but
The size of the array should be mentioned while declaring it. if we want to store a large number of
Array elements are always counted from zero (0) onward. instances, it becomes difficult to manage
Array elements can be accessed using the position of the element in the them with normal variables. The idea of an
array. array is to represent many instances in one
The array can have one or more dimensions. variable.
Advantages:-
Code Optimization: we can retrieve or sort the data efficiently.
Random access: We can get any data located at an index
position.
Disadvantages:-
Size Limit: We can store only the fixed size of elements in the
array. It doesn’t grow its size at runtime.
Few Things to Remember:
• The array indices start with 0. Meaning x[0] is the first element stored at index 0.
• If the size of an array is n, the last element is stored at index (n-1). In this example, x[5] is
the last element.
• Elements of an array have consecutive addresses. For example, suppose the starting
address of x[0] is 2120.
Then, the address of the next element x[1] will be 2124, the address of x[2] will be 2128,
and so on.
Here, the size of each element is increased by 4. This is because the size of int is 4 bytes.
Initializing an
array:
In C++, if an array has a size n, we can store up to n number of elements in the array. However, what will happen if we
store less than n number of elements.