0% found this document useful (0 votes)
9 views

A Guide To C++

Uploaded by

payo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

A Guide To C++

Uploaded by

payo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 48

A guide to C++

HOW TO OPERATE C++ ON CODEBLOCKS


How to open a file in codeblocks:

1. Click on the ‘file’ tab.


2. Move the cursor onto ‘new’, and select ‘empty file’.
3. Once you get the ‘untitled’ blank project, right click on it and save it with the .cpp
extension.
BASIC OPERATIONS IN C++
C++ language has numerous libraries that include predefined functions to make programming easier. In C language, header
files contain the set of predefined standard library functions. You request to use a header file in your program by including it
with the C preprocessing directive “#include”. All the header file have a ‘.h’ an extension. By including a header file, we can
use its contents in our program.

Types of header files:


• #include<iostream>: It is used as a stream of Input and Output using cin and cout.
• #include<stdio.h>: It is used to perform input and output operations using functions scanf() and printf().
• #include<string.h>: It is used to perform various functionalities related to string manipulation like strlen(), strcmp(),
strcpy(), size(), etc.
• #include<math.h>: It is used to perform mathematical operations like
Basic parts of a C++
program
Comments
• Comments are added to the program using the double slash (//) before the statement. They are not executed with the
program and are used only to comment on certain parts of the program.

Using “namespace std”


• We include the ‘using namespace std;’, in order to use all elements of a standard c++ library.

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.

This is why assigning the correct data type is very important.

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.

Condition Meaning TRUE or FALSE


(5 ==5) 5 is equal to 5 TRUE
(6 >= 4) 6 is greater than or equal to TRUE
4
(6>4) 6 greater than 4 TRUE
(6 = 4) 6 equal to 4 FALSE
(5*3) != (13+2) (5*3 = 15) not equal to FALSE
(13+2 = 15)
Conditional Operators

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:

This is the constant declared


Type casting
The process of converting a value from one data type to another during arithmetic operation is called casting or type of
casting. C++ Type casting can be divided into two types

• 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

Drink some coffee


Control statements
Control Statements A C++ control statement redirects the flow of a program in order to execute additional code. These
statements come in the form of conditionals (if-else, switch) and loops (for, while, do-while).

There are two types of control structures:


• Decision making and branching(if, if-else, nested if, else-if ladder, switch statement)
• Repetitive / Iterative (while, do-while, for loops)

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

PROGRAM TO FIND THE BIGGER


NUMBER OUT OF TWO NUMBERS
PROGRAM TO CHECK IF THE
NUMBER IS ODD OR EVEN
LOGIC BEHIND THE PROGRAM:
If the number is even, when divided by 2 it should have a remainder of
0. Hence, why we use the modulo (%), as the modulo displays the
remainder.

So if the remainder is 0, it is even. If not it is an odd number


PROGRAM TO CHECK IF A STUDENT
PASSED OR FAILED:

LOGIC BEHIND THE PROBLEM:


Here to find out if the student has passed, we take in the marks they
received and find their average marks. The passing criteria is based
upon if the mark average is greater than or equal to 50.
Nested if-else
statements:
Nested if-else statements are ‘if’ statements inside of ‘if’ statements.

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

Sometimes instead of using the ‘int main()’ main


function, we use the ‘void main’ main function
PROGRAM TO FIND THE ROOTS OF A LOGIC BEHIND THE PROGRAM:
QUADRATIC EQUATION Here we use the mathematical formula to find the roots of a quadratic
equation.

Line 11 evaluates the discriminant part of the equation

Line 12 to 19: If the discriminant is greater than 0, the roots are


considered to be different, and now we compute the roots according
to the formula

Line 20 to 25: If the discriminant is equal to 0, the roots


are considered to be real and same. Hence we compute
only one root.

Line 26 to 32: if the discriminant is lesser than 0, the


equation will have a real and imaginary part.
WAP TO FIND THE COMMISSION ON A SALESMAN’S TOTAL SALES.
THE COMMISSION ON A SALESMAN’S TOTAL SALES IS AS FOLLOWS:

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.

In a very basic term, a switch statement evaluates an expression,


tests it and compares it against the several cases written in the
code. As soon as a match with any case is found, the control
will enter that case and start executing the statements written in
that case until a break statement has been found. As soon as a
break statement appears, the switch statement terminates, and
the program control exits the switch.

It might sometimes happen that no case matches up with the


value of the expression. For such cases, we mention a default
case that will always execute in case if no match is found. The
cases in a block of a switch statement are represented by
different numbers or string, which is known as an identifier. The
value of the expression or the value provided by the user is
compared with these cases until the match is found.
Some guidelines for writing switch case statements
• Order the cases alphabetically or numerically –
improves readability.
• Put the normal cases first ; put the exceptional
cases later.
• Order cases by frequency:-put the most frequently
executed cases first and the least frequently used
cases later.
• Use default case to detect errors and unexpected
cases [user friendly messages].
• Relational operators cannot be used in switch
statements
PROGRAM TO COMPUTE BASIC ARITHMETIC OPERATIONS USING SWITCH STATEMENTS
#include<conio.h> --- It is a header file used in c and cpp and it
includes inbuilt functions like getch() and clrscr().It stand for console
input ouput i.e. it takes input from keyboard and displays it on screen.

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)

There are three types of looping control statements:


1. While loop
2. For loop
3. Do …. While loop
While Loop:

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:

LOGIC BEHIND THE PROGAM:


In Line 1, the variable x is set to 0. The expression in the while
statement (in Line 2), x <= 20, is evaluated. Because the expression
x <= 20 evaluates to true, the body of the while loop executes next.

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.

After executing the statements in Lines 3 and 4, the expression in


the while loop (Line 2) is evaluated again. Because x is 5, the
expression x <= 20 evaluates to true and the body of the while loop
executes again.

This process of evaluating the expression and executing the body of


the while loop continues until the expression, x <= 20 (in Line 2),
no longer evaluates to true.
For Loop:
The initial statement, loop condition, and update statement (called for loop control statements) enclosed within the parentheses
control the body (statement) of the for statement.

Syntax:

Flowchart:

The for loop executes as follows:

1. The initial statement executes.


2. The loop condition is evaluated. If the loop condition evaluates
to true:
3. Execute the for loop statement.
4. Execute the update statement (the third expression in the
parentheses).
5. Repeat Step 2 until the loop condition evaluates to false.
Examples of ‘for
loop’:
They are the same program but, the difference is found in line
9.
LOGIC BEHIND THE PROGRAM:
At line 7, we set the int to 2. To get even numbers until 10,
we first set the condition so that it stops at 10 which is (i
<= 10). Next we, add 2 to the int i, so that we get all even
numbers.
EXPLANATION OF THE PROGRAM:
Line 7: we declare the data type of i as int.
Line 8: We declare the sum as int and initialize it to 0.
Line 9: we initialize i to 1.

Line 11: We display a statement to tell the user to enter a


number
Line 12: we use the cin statement to store the number
entered into the variable ‘n’.

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;

Line 19: Displays the sum


WHY DO WE INITIALIZE THE SUM TO 0
So basically what is expected from a variable named in this manner might be to store the sum of a collection of data.

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.

So in runtime sum would undergo to changes like this

sum = (((((1) + 2) + 3) + 4) + 5)
//what i want to express with bracket are the iterations.

And finally sum would store 15 in it.

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.

members x[0] x[1] x[2] x[3] x[4] x[5] x[6]


Array 1 2 3 4 5 0 0
indices 0 1 2 3 4 5 6
HOW TO INSERT AND PRINT ELEMENTS OF AN ARRAY
Using Array Indices
A simple solution is to iterate over the elements of an array and print each element.

What is ‘size_t’ in c++:


It’s a type which is used to
represent the size of objects in LOGIC BEHIND THE CODE:
bytes and is therefore used as Since we leave the size of the array
the return type by the sizeof empty, the size will be equal to the
operator . number of elements we enter.

Line 9: here we use size_t and declare it


to n, to make the size of the array ‘input’
equal to n.

Line 11: here we use a for loop to print


our the statements, we state that as long
as ‘i’ is lesser than n, we can print out the
elements. The elements are printed using
the increment operator i++.
A SIMPLER METHOD TO PRINT OUT SHORT ARRAYS

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy