0% found this document useful (0 votes)
19 views54 pages

Lab 1

Uploaded by

teseman2020
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)
19 views54 pages

Lab 1

Uploaded by

teseman2020
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/ 54

Fundamentals of C++ Programming

Languages
Structure of C++ program

 is made up of multiple source code files that cater to different components such as:-

 main function,
 variables,
 member functions,
 data types,
 class definition,
 namespaces,
 headers/ standard headers,
 input/ output statements, etc.
 comments,
Cont…
example

// First C++ Program --- Comment Line

# include <iostream> --- Inclusion of header files called as preprocessor statements.

using namespace std; --- using standard

int main ( ) --- Name of the main function or start of main () function.

{ -- Indicates beginning of main ()

cout<<“ “Hello World”; --- Executable output statement.

return 0; --- Program execute successfully

} --- End of main ()


Cont…
Preprocessor Section

• Preprocessor directives are invoked to perform various pre-processing tasks, such


as importing header files, declaring namespaces, defining constants, and other
such operations that need to be done before the program starts executing.
 #include<iostream>//importing header file. iostream handles input and output

 using namespace std; //importing std namespace

 #define PI 3.14159 //Defining a constant PI whose value is 3.14159


Cont…
example
#include <iostream>
using namespace std;
int main ()
{
int a, b, c;
cout<<“Enter values of a, b”;
cin>>a>>b;
c=a+b;
cout<<“The result is:”<<c;
return 0;
Cont…

In c++, there are a set of reserved words that you can not use as an
identifier, variable name , class name, method names, etc. Keywords are
standard identifiers and their function is predefined by the compiler.
Keywords in c++ programming language are:- break, case, char, new,
public, return, for, false, float, else, int, default, class,try, switch, while,
void, try,do goto, if, continue, true throw this privat, inline, struct... etc
Data Types
The C++ language supports various data types including:-

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

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

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

single quotes

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

double quotes

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


Variables
 A variable is used to store values or data in the code/ structure of a C++ program
to be used later on. there are different types of data that can be stored in the
program.

All C++ variables must be identified with unique names.

These unique names are called identifiers.

Identifiers can be short names (like x and y). But It is recommended to use
descriptive names.
Cont…
The general rules for naming variables are:

 Names can contain letters, digits and underscores

 Names must begin with a letter or an underscore (_)

 Names are case-sensitive (myVar and myvar are different variables)

 Names cannot contain whitespaces or special characters like !, #, %, etc.

 Reserved words (like C++ keywords, such as int) cannot be used as names
Declaring (Creating) Variables

 To create a variable, specify the type and assign it a value:

Syntax: Datatype variableName = value;

Example:

int my = 15;

cout << my;


Cont…

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

Example

int my;

my = 15;

cout << my;


Cont…

 Note that if you assign a new value to an existing variable, it will overwrite the
previous value:

Example

int my = 15; // my is 15

my = 10; // Now my is 10

cout << my; // Outputs 10


Cont…

 To declare more than one variable of the same type, use a comma-separated list:
Example
int x = 5, y = 6, z = 50;

 You can also assign the same value to multiple variables in one line:
Example
int x, y, z;
x = y = z = 50;

Q1. Create a variable named myNum and assign the value 100 to it.
Constants
 When you do not want others (or yourself) to change existing variable values, use
the const keyword (this will declare the variable as "constant", which means
unchangeable and read-only):

Example

const int my= 15; // my will always be 15

my = 10; // error: assignment of read-only variable 'my’.

 When you declare a constant variable, it must be assigned with a value:


Scope of Variables in C++.

There are mainly two types of variable scopes:

1. Local Variables

2. Global Variable
Local Variables

Variables defined within a function or block are said to be local to those functions.
 Anything between ‘{‘ and ‘}’ is said to inside a block.

 Local variables do not exist outside the block in which they are declared, i.e.
they can not be accessed or used outside that block.
 Declaring local variables: Local variables are declared inside a block.
Global Variables

As the name suggests, Global Variables can be accessed from any part of the
program.

 They are available through out the life time of a program.

 They are declared at the top of the program outside all of the functions or blocks.

 Declaring global variables: Global variables are usually declared outside of all of
the functions and blocks, at the top of the program. They can be accessed from any
portion of the program.
Cont…
Example using global variable

#include <iostream>
using namespace std;
int g; // Global variable declaration:
int main ()
{
// Local variable declaration:
int a, b;
// actual initialization
a = 10;
b = 20;
g = a + b;
cout << g;
return 0;
} output: 30
example using of local variables

#include<iostream>
using namespace std;

void func()
{
// this variable is local to the
// function func() and cannot be
// accessed outside this function
int age=18;
}
int main()
{
cout<<"Age is: "<<age;
return 0;
}
Cont…

Output:
Error: age was not declared in this scope

The above program displays an error saying “age was not declared in this scope”.
The variable age was declared within the function func() so it is local to that function
and not visible to portion of program outside this function. The function must be
called.
Example 2

#include<iostream>
using namespace std;

void func()
{
/* this variable is local to the
function func() and cannot be
accessed outside this function */

int age=18;
cout<<age;
}

int main()
{
cout<<"Age is: ";
func();

return 0;
}
Output: Age is: 18
Example using global variable
#include<iostream>
using namespace std;

int global = 5;

void display()
{
cout<<global<<endl;
}

int main()
{
display();

global = 10; Output:


display(); 5
} 10
Example

#include <iostream>
using namespace std;
int g;
int main()
{
int a = 4;
g = a * 2;
cout << g << endl;
return 0;
} output: 8
#include <iostream>
using namespace std;
int g = 10;
void func1()
{
g = 20;
cout << g << endl;
}
int main()
{
func1();
g = 30;
cout << g << endl;
return 0;
} output: 20
30
Example

#include<iostream>
using namespace std;

// global variable
int global = 5;

// main function
int main()
{
// local variable with same
// name as that of global variable

int global = 2;
cout << global << endl; output is 2
}
How to access a global variable when there is a local variable with same name?
- To solve this problem we will need to use the scope resolution operator.

#include<iostream>
using namespace std;

// Global x
int x = 0;

int main()
{
// Local x
int x = 10;
cout << "Value of global x is " << ::x;
cout<< "\nValue of local x is " << x; Output:
return 0; Value of global x is 0
Value of local x is 10
}
C++ Comments
 uses a single-line comment before a line of code:

Example
// This is a comment
cout << "Hello World!";

 uses a single-line comment at the end of a line of code:

Example
cout << "Hello World!"; // This is a comment
C++ Comments
 Multi-line comments start with /* and ends with */.
 Any text between /* and */ will be ignored by the compiler:

Example
/* The code below will print the words Hello World!
to the screen, and it is amazing */
cout << "Hello World!";

 we use // for short comments, and /* */ for longer.


Cont…
\n newline
\r carriage return
Escape codes \t Tabulation
\v vertical tabulation
\b Backspace
\f page feed
\a alert (beep)
\' single quotes (')
\" double quotes (")
\? question (?)
\\ inverted slash (\)
Cont…
Cont…
Cont…

SCIENCER
Cont…
Cont…
Cont…
Cont…
Introduction to Strings
example
#include<iostream>
using namespace std;
#include <string>
int main ()
{
string mystring = "This is a string";
cout << mystring;
return 0;
}
Cont…

Operators
 Arithmetic operators.

 Relational operators.

 Logical operators.

 Assignment operators.

 Increment / Decrement operators.

 Conditional operators.
Arithmetic operators.
example
Relational operators:
example
Logical operators
Example
#include<iostream>
using namespace std;
Truth table for AND and OR operations int main ()
{
op-1 op-2 op-1 && op-2 op-1 || op-2 if((5==5)&& (3>6))
cout<<"True";
else
T T T T cout<<"False";
T F F T
F T F T return 0;
F F F F }
Cont…
Example

#include <iostream>
using namespace std;
int main() {
int number;
cout << "Enter a number: ";
cin >> number;
if (number >= 10 && number <= 20) {
cout << "The number is between 10 and 20." << endl;
} else {
cout << "The number is not between 10 and 20." << endl;
}
return 0;
}
Assignment operators
Cont…

Auto increment / decrement (+ + / - - ): used to automatically increment


and decrement the value of a variable by 1. There are 2 types of incrementing or

decrementing.

Prefix auto increment and decrement --- Adds /subtracts 1 to the operand & result

is assigned to the variable on the left.


E.g a = 5; b=5;
b = ++ a; b = -- a;
Result a=b=6; a=b=4, ;
Cont…

Postfix auto increment and decrement --- This first assigns the value to the

variable on the left & then increments/decrements the operand.


E.g a = 5; b = 5;
b=a++; b=a--;
Result b=5, a=6 b=5, a=4;

Generally a=a+1 can be written as ++a, a++ or a+=1. Similarly a=a-1 can be written

as a--, --a or a -= 1.
Cont…

Conditional operator (ternary operator):

Conditional expressions are of the following form : exp1? exp2: exp3;

Example consider the following statements.

A=10; B=15;

x = (a>b)? A : b; In this example x will be assigned the value of b.


Example
#include<iostream>
using namespace std;
int main ()
{
int a=3, b=1, d;
d=(a>b)?a : b;
cout<<d;
return 0;
}
Cont…

Priority of operators
When making complex expressions with several operands, we may have some doubts
about which operand is evaluated first and which later.
For example, in this expression: a = 5 + 7 % 2. we may doubt if it really means:
 a = 5 + (7 % 2) with result 6, OR
 a = (5 + 7) % 2 with result 0
 The correct answer is the first of the two expressions, with a result of 6. There is
an established order with the priority of each operator, and not only the arithmetic
ones (those whose preference we may already know from mathematics) but for all
the operators which can appear in C++.
Cont…

•Also in the case that there are several operators of the same/equal priority level-
which one must be evaluated first, the rightmost one or the leftmost one is decided by
the Associativity of the operator.
•All these precedence levels for operators can be manipulated or become more legible
using parenthesis signs ( and ), as in this example: a = 5 + 7 % 2; might be written as: a = 5
+ (7 % 2); or a = (5 + 7) % 2;according to the operation that we wanted to perform.
Priority Operator Description Associativity
Cont…
1 :: Scope Left
2 () [ ] -> . sizeof Left
++ -- increment/decrement Right
Complement to one
~
3 (bitwise)
! unary NOT

Reference and
&*
Dereference (pointers)

(type) Type casting

4 */% arithmetical operations Left

5 +- arithmetical operations Left

6 << >> bit shifting (bitwise) Left


7 < <= > >= Relational operators Left
8 == != Relational operators Left
9 &^| Bitwise operators Left
10 && || Logic operators Left
11 ?: Conditional Right
= += -= *= /= %=
12 Assignation Right
>>= <<= &= ^= |=
13 , Comma, Separator Left
Cont… Sample program 1: Write a C++ program to calculate area of a circle for given diameter d, using
formula r2 where r=d/2.
#include<iostream>
using namespace std;
int main()
{
float A, pi=3.1415;
float d, r;
cout<<“Enter the diameter of the circle \n”;
cin>>d;
r=d / 2;
A= pi * r * r;
Cout<<area of circle =<<A;
return 0;
}
Cont…

Floating Point Numbers

For e.g.: 3.14159 // 3.14159

6.02e23 // 6.02 x 10^23

1.6e-19 // 1.6 x 10^-19

3.0 // 3.0
Cont…

Declared constants (const)

#define PI 3.14159

const int PI = 3.14159;


ND
e E
T h

You might also like