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

Unit 3 - C++ Basics

This document provides an overview of basic C++ programming concepts across 6 paragraphs. It introduces key topics like iostream library, namespaces, main function return type, insertion and extraction operators, and C++ tokens. Example code is included to demonstrate printing output, accepting user input, and basic operations like addition.

Uploaded by

Vansh Mehta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

Unit 3 - C++ Basics

This document provides an overview of basic C++ programming concepts across 6 paragraphs. It introduces key topics like iostream library, namespaces, main function return type, insertion and extraction operators, and C++ tokens. Example code is included to demonstrate printing output, accepting user input, and basic operations like addition.

Uploaded by

Vansh Mehta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

202000212

Object Oriented
Programming

Unit - 3
C++ Basics

A.Y. 2022-23 (Even) Semester: 2


(Branch - IoT)
(Course Code: 202000212)

Vinita Shah
Asst. Professor, IT Dept., GCET
A Simple C++ Program
#include <iostream> //include header file
using namespace std;
int main()
{
cout << "Hello World"; // C++ statement

}
I like C++ so much
return 0;

▪I iostream
will score good
is just like marks
we include stdio.hin
in c C++
program.
▪ It contains declarations for the identifier cout and the insertion
operator <<.
▪ iostream should be included at the beginning of all programs
that use input/output statements.

Unit - 3 C++ Basics 2


A Simple C++ Program (Cont…)
#include <iostream> //include header file
using namespace std;
int main()
{
cout << "Hello World"; // C++ statement
I like C++ so much
}
return 0;

▪I Awill score
namespace goodregion.
is a declarative marks in C++
▪ A namespace is a part of the program in which certain names are
recognized; outside of the namespace they’re unknown.
▪ namespace defines a scope for the identifies that are used in a
program.
▪ using and namespace are the keywords of C++.

Unit - 3 C++ Basics 3


A Simple C++ Program (Cont…)
#include <iostream> //include header file
using namespace std;
int main()
{
cout << "Hello World"; // C++ statement

}
I like C++ so much
return 0;

I will score good marks in C++


▪ std is the namespace where ANSI C++ standard class libraries are
defined.
▪ Various program components such as cout, cin, endl are
defined within std namespace.
▪ If we don’t use the using directive at top, we have to add the std
followed by :: in the program before identifier.
std::cout << “Hello World”;
Unit - 3 C++ Basics 4
A Simple C++ Program (Cont…)
#include <iostream> //include header file
using namespace std;
int main()
{
cout << "Hello World"; // C++ statement

}
I like C++ so much
return 0;

▪I In
will scorereturns
C++, main() good marks
an integer in C++
type value.
▪ Therefore, every main() in C++ should end with a return 0;
statement; otherwise error will occur.
▪ The return value from the main() function is used by the
runtime library as the exit code for the process.

Unit - 3 C++ Basics 5


Insertion Operator <<
cout << "Hello World";

▪ The operator << is called the


insertion operator.
▪ It inserts the contents of the
I like C++ so much
variable on its right to the object
on its left.
▪ The identifier cout is a predefined
I will score good marks in C++
object that represents standard
output stream in C++.
▪ Here, Screen represents the
output. We can also redirect the
output to other output devices. Output Using Insertion Operator
▪ The operator << is used as bitwise
left shift operator also.

Unit - 3 C++ Basics 6


Program: Basic C++ program
Write a C++ Program to print following

Name: GCET
City: V V Nagar
Country: India
I like C++ so much
I will score good marks in C++

Unit - 3 C++ Basics 7


Program: Basic C++ program
#include <iostream>
using namespace std;
int main()
{

I like C++ so much


cout << "Name: GCET";
cout << "City: V V Nagar";
I will score good marks in C++
cout << "Country: India";
return 0;
}

Output
Name: GCET City: V V Nagar Country: India
Unit - 3 C++ Basics 8
Program: Basic C++ program(Cont…)
#include <iostream> #include <iostream>
using namespace std; using namespace std;
int main() int main()
{ {
cout << "Name: GCET\n"; cout << "Name: GCET"<<endl;
cout << "City: V V Nagar\n"; cout << "City: V V Nagar"<<endl;
cout << "Country: India"<<endl;

}
I like C++ so much
cout << "Country: India";
return 0;
}
return 0;

I will score▪ good


Output The endlmarks inandC++
manipulator \n has same
Name: GCET effect. Both inserts new line to output.
City: V V Nagar
Country: India
▪ But, difference is endl immediate flush to the
output while \n do not.

Unit - 3 C++ Basics 9


Extraction Operator >>
cin >> number1;
▪ The operator >> is called the
extraction operator.
▪ It extracts (or takes) the value Object Extraction Operator
from keyboard and assigns it to
cin number1
I like C++ so much
>>
the variable on its right.
▪ The identifier cin is a predefined Variable

I object
will score good marks in C++
that represents standard
input stream in C++.
▪ Here, standard input stream KeyBoard
represents the Keyboard.
▪ The operator >> is used as
bitwise right shift operator also.

Unit - 3 C++ Basics 10


Program: Basic C++ Addition
#include<iostream>
using namespace std;
int main()
{
int number1,number2;

cout<<"Enter First Number: ";


I like C++ so much
cin>>number1; //accept first number

I will score good marks in C++


cout<<"Enter Second Number: ";
cin>>number2; //accept first number

cout<<"Addition : ";
cout<<number1+number2; //Display Addition
return 0;
}

Unit - 3 C++ Basics 11


C++ Tokens
C++ Tokens
▪ The smallest individual unit of a program is known as token.
▪ C++ has the following tokens:
− Keywords
#include <iostream>
− Identifiers using namespace std;
I like C++ so much
− Constants int main()
{
I will score good marks in C++
− Strings cout << "Hello World";
return 0;
− Special Symbols
}
− Operators

Unit - 3 C++ Basics 13


Keywords and Identifier
▪ C++ reserves a set of 84 words for its own use.
▪ These words are called keywords (or reserved words), and each of
these keywords has a special meaning within the C++ language.
▪ Identifiers are names that are given to various user defined
I like C++ so much
program elements, such as variable, function and arrays.
▪ Some of Predefined identifiers are cout, cin, main
I will score good marks in C++
❑ We cannot use Keyword as user defined identifier.

Unit - 3 C++ Basics 14


Keywords in C++
asm double new switch
auto else operator template
break enum private this
case extern protected throw
I like C++ so much
catch float public try
char for register typeof
Iclass
will score good marks
friend return in C++
union
const goto short unsigned
continue if signed virtual
default inline sizeof void
delete int static volatile
do long struct while
Unit - 3 C++ Basics 15
Rules for naming identifiers in C++
1. First Character must be an alphabet or underscore.
2. It can contain only letters(a..z A..Z), digits(0 to 9) or
underscore(_).
3. Identifier name cannot be keyword.
I like C++ so much
4. C++ does not restrict the length of identifier

I will score good marks in C++

Unit - 3 C++ Basics 16


Valid, Invalid Identifiers
1) GCET Valid 12) xyz123 Valid
2) A Valid 13) part#2 Invalid
3) Age Valid 14) "char" Invalid
4) void Reserved word 15) #include Invalid
I like C++ so much16) This_is_a_ Valid
5) MAX-ENTRIES Invalid
Reserved word Valid
I7) time
will score
6) double
Valid
good marks
17) _xyz
18) 9xyz
in C++
Invalid
8) G Valid 19) main Standard identifier
9) Sue's Invalid 20) EC Reserved word
10) return Reserved word 21) double Reserved word
11) cout Standard identifier 22) max?out Invalid
Unit - 3 C++ Basics 17
Constants / Literals
▪ Constants in C++ refer to fixed values that do not change during
execution of program.

CONSTANTS

I like C++ so much


CHARACTER
NUMERIC
I will score
CONSTANTS good marks in C++
CONSTANTS

SINGLE
INTEGER REAL STRING
CHARACTER
CONSTANTS CONSTANTS CONSTANTS
CONSTANTS
i.e. i.e. i.e.
i.e.
123,-321, 6543 0.0083, -0.75 “Hello”, “197”
‘5’, ‘X’, ‘;’
Unit - 3 C++ Basics 18
C++ Operators
C++ Operators
▪ All C language operators are valid in C++.
1. Arithmetic operators (+, - , *, /, %)
2. Relational operators (<, <=, >, >=, ==, !=)
3. Logical operators (&&, ||, !)
I like C++ so much
4. Assignment operators (+=, -=, *=, /=)
5. Increment and decrement operators (++, --)
I will score good marks in C++
6. Conditional operators (?:)
7. Bitwise operators (&, |, ^, <<, >>)
8. Special operators ()

Unit - 3 C++ Basics 20


Arithmetic Operators

Operator example Meaning


+ a+b Addition

I like C++ so much


- Subtraction
a–b
* Multiplication
a*b
I will score goodDivision
/
marks in C++
a/b
% a%b Modulo division- remainder

Unit - 3 C++ Basics 21


Relational Operators

Operator Meaning
< Is less than
<= Is less than or equal to
I like C++ so>
much
Is greater than
I will score>= good marks
Is greater than orin C++
equal to
== Equal to
!= Not equal to

Unit - 3 C++ Basics 22


Logical Operators
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT

I like aC++ sobmucha && b a || b


true true true true
I willtruescore false
good marks
false intrueC++
false true false true
false false false false

❑ a && b : returns false if any of the expression is false


❑ a || b : returns true if any of the expression is true

Unit - 3 C++ Basics 23


Assignment operator
▪ We assign a value to a variable using the basic assignment
operator (=).
▪ Assignment operator stores a value in memory.
▪ The syntax is
I like C++leftSide
so much= rightSide ;

I will score good marks in C++


It is either a literal |
Always it is a
a variable identifier |
variable identifier.
an expression.

Literal: ex. i = 1;
Variable identifier: ex. start = i;
Expression: ex. sum = first + second;
Unit - 3 C++ Basics 24
Assignment Operators (Shorthand)
Syntax:
leftSide Op= rightSide ;

It is an arithmetic
operator.
IEx:like C++ so much
Simple assignment
Shorthand operator
x=x+3; operator
I willx+=3;score good marks
a = a+1
in C++a += 1
a = a-1 a -= 1
a = a * (m+n) a *= m+n
a = a / (m+n) a /= m+n
a = a % b a %= b
Unit - 3 C++ Basics 25
Increment and Decrement Operators
▪ Increment ++
The ++ operator used to increase the value of the variable by one
▪ Decrement ─ ─
The ─ ─ operator used to decrease the value of the variable by one
Example:
I like x=100;
C++
x++;
so much
I will
After scorethegood
the execution value of x marks
will be 101. in C++
Example:
x=100;
x--;
After the execution the value of x will be 99.

Unit - 3 C++ Basics 26


Pre & Post Increment operator
Operator Description
Pre increment operator (++x) value of x is incremented before assigning
it to the variable on the left

x = 10 ; After execution

I like C++ so much


p = ++x;
First increment value of
x by one
x will be 11
p will be 11

I will score goodDescription


Operator marks in C++
Post increment operator (x++) value of x is incremented after assigning it
to the variable on the left

x = 10 ; After execution
p = x++; x will be 11
p will be 10
First assign value of x

Unit - 3 C++ Basics 27


What is the output of this program?
#include <iostream>
using namespace std;
int main ()
{
int x, y;
x = 5;
y = ++x * ++x;
cout << x << y;
I like C++ so much
x = 5;
y = x++ * ++x;
I will score good marks in C++
}
cout << x << y;

(A) 749735
(B) 736749
(C) 367497
(D) none of the mentioned

Unit - 3 C++ Basics 28


Conditional Operator
Syntax:
exp1 ? exp2 : exp3
Working of the ? Operator:
▪ exp1 is evaluated first
I like C++ so much
• if exp1 is true(nonzero) then
- exp2 is evaluated and its value becomes the value of the expression
• If exp1 is false(zero) then
I will score good marks in C++
- exp3 is evaluated and its value becomes the value of the expression
Ex: Ex:
m=2; m=2;
n=3; n=3;
r=(m>n) ? m : n; r=(m<n) ? m : n;
Value of r will be 3 Value of r will be 2
Unit - 3 C++ Basics 29
Bitwise Operator
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
I like C++ so much << Shift left
>> Shift right
I will score good marks in C++

Unit - 3 C++ Basics 30


Bitwise Operator Examples
8 = 1000 (In Binary)
6 = 0110 (In Binary)
Bitwise & (AND) Bitwise | (OR)
int a=8,b=6,c; int a=8,b=6,c;
c = a & b; c = a | b;
I like C++ so much
cout<<"Output ="<< c; cout<<"Output ="<< c;
Output = 0 Output = 14
I will
Bitwise score
<< (Shift Left) good marks in Right)
Bitwise >> (Shift C++
int a=8,b=6,c; int a=8,b=6,c;
c = a << 1; c = a >> 1;
cout<<"Output ="<< c; cout<<"Output ="<< c;
Output = 16 Output = 4
left shifting is the equivalent of right shifting is the equivalent
multiplying a by a power of two of dividing a by a power of two

Unit - 3 C++ Basics 31


New Operators in C++
It allows to access to the global
version of variable
:: Scope Resolution Declares a pointer to a member of
a class
::* Pointer-to-member declarator
->* Pointer-to-member operator To access pointer to class members

I .*likePointer-to-member
C++ so much operator To access pointer to data members
of class
Inew
willMemory
score good
allocation operatormarks in C++
Allocates memory at run time
delete Memory release operator
endl Line feed operator Deallocates memory at run time

setw Field width operator It is a manipulator causes a linefeed


to be inserted
It is a manipulator specifies a field
width for printing value
Unit - 3 C++ Basics 32
Scope Resolution Operator
If the global variable name is same as local variable
name, the scope resolution operator will be used to
call the global variable.
Scope Resolution Operator(::)
....
....
Declaration of x in inner block hides
{ declaration of same variable declared in an
int x=10; outer block.
....
.... Therefore, in this code both variable x
refers to different data.
I like C++ so much
{
int x=1; Block-1
.... Block-2
I will score good
}
.... marks
▪ In C language, valuein
of xC++
declared in Block-1
is not accessible in Block-2.
....
▪ In C++, using scope resolution operator (::),
}
value of x declared in Block-1 can be
accessed in Block-2.

Unit - 3 C++ Basics 34


#include <iostream>
Scope resolution example
using namespace std;
char a = 'm';
static int b = 50;

int main() {
char a = 's';

cout << "The static variable : "<< ::b;


cout << "\nThe local variable : " << a;
cout << "\nThe global variable : " << ::a;

return 0;
}

Output:
The static variable : 50
The local variable : s
The global variable : m
C++ Data Types
Basic Data types
C++ Datatypes

User-defined Built-in Derived


I like C++ so much
structure
union
array
function
I will score good marks in C++
class
enumeration
pointer
reference

Integral Void Floating

int char float double

Unit - 3 C++ Basics 38


Built in Data types
Data Type Size (bytes) Range
char 1 -128 to 127
unsigned char 1 0 to 255
short or int 2 -32,768 to 32,767
I like C++ so much
unsigned int 2 0 to 65535
I will score good
long 4 marks
-2147483648in C++
to 2147483647
unsigned long 4 0 to 4294967295
float 4 3.4e-38 to 3.4e+308
double 8 1.7e-308 to 1.7e+308
long double 10 3.4e-4932 to 1.1e+4932

Unit - 3 C++ Basics 39


Type Conversion
Type Conversion
▪ Type Conversion is the process of converting one predefined data
type into another data type.

Type Conversion
I like C++ so much
I will score good
Implicit
marks in
Explicit
C++
(Automatically converts (Forcefully converts one
one datatype to another datatype to another
datatype) datatype)

▪ Explicit type conversion is also known as type casting.

Unit - 3 C++ Basics 41


Type Conversion(Cont…)
int a;
double b=2.55;
a = b; // implicit type conversion

Icout
like<< C++ so much
a << endl; // this will print 2
a = int(b); //explicit type conversion
Icout
will<< score good marks in C++
a << endl; // this will print 2

Unit - 3 C++ Basics 42


Implicit type conversion hierarchy

long
I like C++ so much float double double

long int
I will score intgood marks in C++
unsigned
int
char

Unit - 3 C++ Basics 43


Implicit Type Conversion
#include <iostream>
using namespace std;
ans = count * avg
int main()
{ 5 10.01
int count = 5;
I like C++ so much
float avg = 10.01;
double ans;
double int float

I will score good


ans = count * avg;
marks
5.0 in C++ *
float
50.05
cout<<"Answer=:"<<ans; 50.05
return 0; float
double
}
Output:
Answer = 50.05
Unit - 3 C++ Basics 44
Type Casting
▪ In C++ explicit type conversion is called type casting
▪ Syntax
type-name (expression) //C++ notation
▪ Example
I like average
C++ so much i; //C notation
= sum/(float)

I will average
score= good marks in C++
sum/float (i); //C++ notation

Unit - 3 C++ Basics 45


#include <iostream>
using namespace std;
int main()
Type Casting Example
{
int a, b, c;
a = 19.99 + 11.99; //adds the values as float
// then converts the result to int
b = (int) 19.99 + (int) 11.99; // old C syntax
c = int (19.99) + int (11.99); // new C++ syntax

cout << "a = " << a << ", b = " << b;


cout << ", c = " << c << endl;

char ch = 'Z';
cout << "The code for " << ch << " is "; //print as char
cout << int(ch) << endl; //print as int
return 0;
}
Output:
a = 31, b = 30, c = 30
The code for Z is 90
Enumeration
Enumeration (A user defined Data Type)
▪ An enumeration is set of named integer constants.
▪ Enumerations are defined much like structures.

enum days{Sun,Mon,Tues,Wed,Thur,Fri,Sat};
0 1 2 3 4 5 6
I like C++
Keyword
Tag
so much
I will name
score Integer
good marks in C++
Values for symbolic constants

▪ Above statement creates days the name of datatype.


▪ By default, enumerators are assigned integer values starting with 0.
▪ It establishes Sun, Mon… and so on as symbolic constants for
the integer values 0-6.

Unit - 3 C++ Basics 48


Enumeration Behaviour(Cont…)
enum coin { penny, nickel, dime, quarter=100,
half_dollar, dollar};

The values of these symbols are


penny 0
I like C++ so much nickel
dime
1
2
I will score good marks in C++
quarter
half_dollar 101
100

dollar 102

Unit - 3 C++ Basics 49


Enumeration Behaviour
enum days{ sun, mon, tue, wed, thu, fri, sat };
days today; variable today declared of type days

today = tue; Valid, because tue is an enumerator. Value 2 will


be assigned in today
today = 6; Invalid, because 6 is not an enumerator

today++; Invalid, today is of type days. We can not apply


++ to structure variable also
today = mon + fri; Invalid
Valid, days data type converted to int,
int num = sat;
value 6 will be assigned to num
num = 5 + mon; Valid, mon converted to int with value 1
Enumeration - Example 1
#include <iostream>
using namespace std;

enum week { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };

int main()
{
I like C++ so much
week today;
today = Wednesday;
cout << "Day " << today+1;
I will score good marks in C++
}
return 0;

Output:
Day 4

Unit - 3 C++ Basics 51


Enumeration - Example 2
#include <iostream>
using namespace std;

enum seasons { spring = 34, summer = 10, autumn = 9, winter = 32};

int main()

I like C++ so much


{
seasons s;

I will score good marks in C++


s = summer;
cout << "Summer = " << s << endl;

return 0;

Output:
Summer = 10
Unit - 3 C++ Basics 52
Control Structures
Control Structures
▪ The if statement:
• Simple if statement
• if…else statement
• else…if ladder
I like C++nested
• if…else so much
I will score good marks in C++
▪ The switch statement :
▪ The do-while statement: An exit controlled loop
▪ The while Statement: An entry controlled loop
▪ The for statement: An entry controlled loop

Unit - 3 C++ Basics 54


Thank You

You might also like