0% found this document useful (0 votes)
110 views46 pages

Unit 2: Beginning With C++

This document provides an overview of basic C++ programming concepts including: - Basic program structure with main() function and use of cout and return - Data types like int and variable declarations - Input/output streams like cin and cout - Common operators for arithmetic, assignment, comparisons - Control structures like if/else, while loops, for loops - Functions and libraries - Structures for grouping related data

Uploaded by

Sayali Patil
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)
110 views46 pages

Unit 2: Beginning With C++

This document provides an overview of basic C++ programming concepts including: - Basic program structure with main() function and use of cout and return - Data types like int and variable declarations - Input/output streams like cin and cout - Common operators for arithmetic, assignment, comparisons - Control structures like if/else, while loops, for loops - Functions and libraries - Structures for grouping related data

Uploaded by

Sayali Patil
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/ 46

Unit 2

Beginning with C++


Basic Program Construction
Let’s look at a very simple C++ program. Extension of programs is CPP
(Test.cpp)

#include <iostream>
using namespace std;
int main()
{
cout << “Every age has a language of its own\n”;
return 0;
}
• The identifier cout (pronounced “C out”) is actually an object. It is
predefined in C++ to correspond to the standard output stream. A
stream is an abstraction that refers to a flow of data.

• The standard output stream normally flows to the screen display.


• The operator << is called the insertion or put to operator. It directs the
contents of the variable on its right to the object on its left.

<< as the left-shift bit-wise operator and wonder how it can also be
used to direct output. In C++, operators can be overloaded. Performing
different activities, depending on the context.
#include <iostream.h> : Pre-processor directive, directs compiler to include
header file iostream.h

The using Directive


• A C++ program can be divided into different namespaces. A namespace is
a part of the program in which certain names are recognized; outside of
the namespace they’re unknown.
• The directive using namespace std; says that all the program statements
that follow are within the std namespace.
• Various program components such as cout are declared within this
namespace. If we didn’t use the using directive, we would need to add the
std name to many program elements.

std::cout << “qwqwwq”;


Variable Int
• Integer variables exist in several sizes, but the most commonly used is
type int. The amount of memory occupied by the integer types is system
dependent. On a 32-bit system such as Windows, an int occupies 4
bytes (which is 32 bits) of memory.
• This allows an int to hold numbers in the range from –2,147,483,648 to
2,147,483,647.
• While type int occupies 4 bytes on current Windows computers, it
occupied only 2 bytes in MS-DOS and earlier versions of Windows.

You must declare a variable before using it. However, you can place
variable declarations anywhere in a program. It’s not necessary to
declare variables before the first executable statement
Declarations and Definitions
• A declaration introduces a variable’s name (such as var1) into a program
and specifies its type (such as int). However, if a declaration also sets aside
memory for the variable, it is also called a definition. The statements
• int var1;
• int var2;

are definitions, as well as declarations, because they set aside memory for
var1 and var2.
Variables are also called Identifiers.
Can use upper and lower-case letters, underscore ( _ ) and digits.

Keyword: is a predefined word with a special meaning.


for eg. int, class, if, and while
Input with cin and Output with cout
>> is the extraction or get from operator

#include <iostream>
using namespace std;
int main()
{
int ftemp; //for temperature in fahrenheit
cout << “Enter temperature in fahrenheit: “;
cin >> ftemp;
int ctemp = (ftemp-32) * 5 / 9;
cout << “Equivalent in Celsius is: “ << ctemp << ‘\n’;
return 0;
}
Output:
Enter temperature in fahrenheit: 212
Equivalent in Celsius is: 100
Arithmetic Operators

Basic arithmetic operators:


+, -, *, and / for addition, subtraction, multiplication, and division.
These operators work on all the data types, both integer and floating-
point.

The Remainder Operator: %


• works only with integer variables (types char, short, int, and long).
• It’s called the remainder operator, and is represented by the percent
symbol (%).
• Also called the modulus operator as it finds the remainder when one
number is divided by another.
#include <iostream>
using namespace std;
int main()
{
cout << 6 % 8 << endl // 6
<< 7 % 8 << endl // 7
<< 8 % 8 << endl // 0
<< 9 % 8 << endl // 1
<< 10 % 8 << endl; // 2
return 0;
}
Assignment Operators
total = total + item; // adds “item” to “total”
• Arithmetic assignment operator, which combines an arithmetic operator
and an assignment operator and eliminates the repeated operand.
total += item; // adds “item” to “total”

• There are arithmetic assignment operators corresponding to all the


arithmetic operations: +=, -=, *=, /=, and %=

count = count + 1; // adds 1 to “count”


count += 1;
++count;

?
Prefix
Increment
operator

Postfix
Increment
operator
Library Functions

These functions perform file access, mathematical computations,


and data conversion, among other things.
Eg., sqrt()
X=Sqrt(64);

Remember to #include <cmath>

Error: ‘sqrt’ unidentified identifier


Two Ways to Use #include

1. angle brackets < and > surrounding the filenames


• IOSTREAM and CMATH in the SQRT example indicate that the
compiler should begin searching for these files in the standard
INCLUDE directory. This directory, which is traditionally called
INCLUDE, holds the header files supplied by the compiler
manufacturer for the system.
2. quotation marks, “ and “ surrounding the filenames
• #include “myheader.h” Quotation marks instruct the compiler to begin
its search for the header file in the current directory; this is usually the
directory that contains the source file.

Use quotation marks for header files you write yourself


Relational Operators
A relational operator compares two values. The values can be
any built-in C++ data type, such as char, int, and float.

Operator Meaning

> Greater than (greater than)


< Less than
== Equal to
!= Not equal to
>= Greater than or equal to
<= Less than or equal to
Loops
• Loops cause a section of your program to be repeated a certain
number of times. The repetition continues while a condition is
true. When the condition becomes false, the loop ends and
control passes to the statements following the loop.
• There are three kinds of loops in C++: the for loop, the while
loop, and the do loop.
#include <iostream>
using namespace std;
int main()
{
int j; //define a loop variable
for(j=0; j<15; j++)
cout << j * j << “ “; Output
cout << endl; 0 1 4 9 16 25 36 49 64 81 100 121 144 169 196
return 0;
}
#include <iomanip>
using namespace std;
int main()
{
int numb; //define loop variable
for(numb=1; numb<=10; numb++) //loop from 1 to 10
{
cout << setw(4) << numb; //display 1st column
int cube = numb*numb*numb; //calculate cube
cout << setw(6) << cube << endl; //display 2nd column
}
return 0;
}
1 1
2 8
3 27
4 64
5 125
6 216
7 343
8 512
9 729
10 1000
Decisions
1. if...else statement, which chooses between two alternatives. This statement
can be used without the else, as a simple if statement.
2. switch, creates branches for multiple alternative sections of code, depending
on the value of a single variable.
3. Conditional operator

#include <iostream> #include <iostream>


using namespace std; using namespace std;
int main() int main()
{ {
int x; int x;
cout << “Enter a number: “; cout << “Enter a number: “;
cin >> x; cin >> x;
if( x > 100 ) while( x > 100 )
cout << “That number is greater cout << “That number is greater
than100”; than100”;
return 0; return 0;
} }
Operator Precedence
Tutorial 2
Q1. Describe all data type available in C++ language.
Make a table showing Keyword used || Numerical Range || Bytes
Q2. What is type conversion? How it happens in C++.
Q3. How and when to use type casting?
Q4. How is increment/decrement prefix and postfix operator applied?
Q5. Differentiate between header files and library files.
Q6. A library function, islower(), takes a single character (a letter) as an argument and returns a
nonzero integer if the letter is lowercase, or zero if it is uppercase. This function requires the
header file CTYPE.H. Write a program that allows the user to enter a letter, and then displays
either zero or nonzero, depending on whether a lowercase or uppercase letter was entered.
Q7. Write a temperature-conversion program that gives the user the option of converting
Fahrenheit to Celsius or Celsius to Fahrenheit. Then carry out the conversion. Use floating-point
numbers. Interaction with the program might look like this:
Type 1 to convert Fahrenheit to Celsius, 2 to convert Celsius to Fahrenheit
Q8. Write a program that repeatedly asks for a number and calculates its factorial, until the user
enters 0, at which point it terminates. You can enclose the relevant statements in FACTOR in a
while loop or a do loop to achieve this effect.
Structures
• A structure is a collection of simple variables. The variables in a
structure can be of different types: int, float, and so on.

• The data items in a structure are called the members of the structure.
struct student
{
int rollno;
char name[20];
int phno;
};
student s1,s2;
s1.rollno=200101;
Structures Within Structures
struct Distance //Englis
{
int feet;
float inches;
};
struct Room
{
Distance length;
Distance width;
};

Room dining;
dining.length.feet=10;
dining.length.inches=2.5;
dining.width.feet=5;
dining.width.inches=1.5;

//compute area- first convert inches to feet


float l= dining.length.feet + dining.length.inches/12;
float w= dining.width.feet + dining.width.inches/12;
Area= l * w;
Functions

A function groups a number of


program statements into a unit
and gives it a name.

• Structured programming
• Reduce program size
• Function code is stored in only
one place in memory
Passing Arguments to Functions
• An argument is a piece of data (an int value, for example) passed from a program to the
function.
• Arguments allow a function to operate with different values, or even to do different
things, depending on the requirements of the program calling it.
• In the next program, TableArg, includes a function. In this program, arguments are
used to pass the character to be printed and the number of times to print it.

Reference Arguments
• A reference provides an alias—a different name—for a variable.
• When arguments are passed by value, the called function creates a new variable of the
same type as the argument and copies the argument’s value into it.
• The function cannot access the original variable in the calling program, only the copy it
created. Passing arguments by value is useful when the function does not need to
modify the original variable in the calling program.
• Passing arguments by reference uses a different mechanism. Instead of a value being
passed to the function, a reference to the original variable, in the calling program, is
passed.
• In this case, the memory address of the variable is passed.
//Program TableArg
// function definition
void repchar(char ch, int n) //function
#include <iostream> declarator
using namespace std; {
void repchar(char, int); //function declaration for(int j=0; j<n; j++) //function body
int main() cout << ch;
{ cout << endl;
repchar(‘-’, 43); //call to function }
cout << “Data type Range” << endl;
repchar(‘=’, 23); //call to function -------------------------------------------
Data type Range
cout << “char -128 to 127” << endl =======================
<< “short -32,768 to 32,767” << endl char -128 to 127
<< “int System dependent” << endl short -32,768 to 32,767
<< “long -2,147,483,648 to int System dependent
2,147,483,647” << endl; long -2,147,483,648 to 2,147,483,647
-------------------------------------------
repchar(‘-’, 43); //call to function
return 0;
}
// demonstrates variable arguments :VarArg.cpp
#include <iostream> Enter a character: +
using namespace std; Enter number of times to repeat it: 20
void repchar(char, int); //function declaration ++++++++++++++++++++
int main()
{ The data types of variables used as
char chin; arguments must match those specified in
int nin; the function declaration and definition.
cout << “Enter a character: “;
cin >> chin; In VarArg.cpp the particular values
cout << “Enter number of times to repeat
possessed by chin and nin when the
it: “;
function call is executed will be passed to
cin >> nin;
the function. The function gives these new
repchar(chin, nin);
return 0; variables the names and data types of the
} parameters specified in the declarator:
// function definition ch of type char and n of type int.
void repchar(char ch, int n) //function declarator
{ It initializes these parameters to the values
for(int j=0; j<n; j++) //function body passed.
cout << ch; They are then accessed like other variables
cout << endl; by statements in the function body.
}
#include <iostream> // display structure of type Distance in feet & inches
using namespace std; void disp( Distance dd ) //parameter of type Distance
struct Distance {
{ cout << dd.feet << “\’-” << dd.inches << “\””;
int feet; }
float inches;
};
void disp( Distance ); //declaration
int main()
{ Output:
Distance d1, d2; //define two lengths
//get length d1 from user Enter feet: 6
cout << “Enter feet: “; cin >> d1.feet; Enter inches: 4
cout << “Enter inches: “; cin >> d1.inches; Enter feet: 5
//get length d2 from user Enter inches: 4.25
cout << “\nEnter feet: “; cin >> d2.feet; d1 = 6’-4”
cout << “Enter inches: “; cin >> d2.inches; d2 = 5’-4.25”
cout << “\nd1 = “;
disp(d1); //display length 1
cout << “\nd2 = “;
disp(d2); //display length 2
cout << endl;
return 0;
}
#include <iostream> // display structure of type Distance in feet & inches
using namespace std; void disp( Distance dd ) //parameter of type Distance
struct Distance {
{ dd. Feet=2;
int feet; dd.inches=3.25;
float inches; cout<<"\n in function:";
}; cout << dd.feet << “\’-” << dd.inches << “\””;
void disp( Distance ); //declaration }
int main()
{ Output:
Distance d1, d2; //define two lengths
//get length d1 from user Enter feet: 6
cout << “Enter feet: “; cin >> d1.feet; Enter inches: 4
cout << “Enter inches: “; cin >> d1.inches; Enter feet: 5
//get length d2 from user Enter inches: 4.25
cout << “\nEnter feet: “; cin >> d2.feet; d1= 6’-4”
cout << “Enter inches: “; cin >> d2.inches; In function: 2’-3.25”
cout << “\nd1 = “;
disp(d1); //display length 1 d2 =
cout << “\nd2 = “; In function: 2’-3.25”
disp(d2); //display length 2
cout << endl;
return 0;
}
Pass by Reference
#include <iostream> //orders two numbers

using namespace std; void order(int& numb1, int& numb2)


int main() {
if(numb1 > numb2) //if 1st > 2nd,
{ {
void order(int&, int&); //prototype int temp = numb1; //swap them
numb1 = numb2;
int n1=99, n2=11; //this pair not ordered
numb2 = temp;
int n3=22, n4=88; //this pair ordered }
order(n1, n2); //order each pair of numbers }

order(n3, n4);
cout << “n1=” << n1 << endl; //print all nos Output:
cout << “n2=” << n2 << endl;
n1=11
cout << “n3=” << n3 << endl; n2=99
cout << “n4=” << n4 << endl; n3=22
return 0; n4=88
}
Defining Class
Private and Public

Data hiding

• Data is concealed
into a class,
• Doesn’t allow access
by outside functions
• Private Data and
functions are hidden
from other classes or
parts of the program
Using class
Creating object/ Instantiating object/ Instance variables

Define Class Define Object & call member functions


Class Student main( )
{ {
Private: // define two objects of class Student
int rollno; Student s1,s2;
Public: s1.read_data(10); //message
void read_data(int r) s1.put_data();
{ s2.read_data(20);
rollno=r; s2.put_data();
} }
void put_data()
{ Object s1 Object s2
cout<<“\n Rollno is:” <<rollno; rollno:10 rollno:20
}
}
C++ Objects as Data Types
#include <iostream> //distanceclass.cpp int main()
using namespace std; {
class Distance //Distance class Distance dist1, dist2;//define lengths
{ dist1.setdist(11, 6.25); //set dist1
private: dist2.getdist(); //get dist2 from user
int feet; //display lengths
float inches; cout << “\ndist1 = “; dist1.showdist();
public: cout << “\ndist2 = “; dist2.showdist();
void setdist(int ft, float in) //set Distance to args cout << endl;
{ return 0;
feet = ft; inches = in; }
}
void getdist() //get length from user
{
cout << “\nEnter feet: “; cin >> feet; Output:
cout << “Enter inches: “; cin >> inches;
} Enter feet: 10
void showdist() //display distance Enter inches: 4.75
{ dist1 = 11’-6.25” ←provided by arguments
cout << feet << “\’-” << inches << ‘\”’; dist2 = 10’-4.75” ←input by the user
}
};
Class can be defined inside a function ?
#include<iostream>
using namespace std;
void fun()
{
class Test // local to fun
{
public: // method is defined inside the local class
void method()
{
cout << "Local Class method() called";
}
};
Test t;
t.method();
}
int main()
{
fun();
return 0;
}
Access Specifiers or Modifiers
• Used to implement data hiding.
• Access modifiers or Access Specifiers in a class are used to set the
accessibility of the class members.
• It sets some restrictions on the class members not to get directly accessed
by the outside functions.

There are 3 types of access modifiers available in C++:


• Public
• Private
• Protected

• If we do not specify any access modifiers for the members inside the class
then by default the access modifier for the members will be Private.
Access Specifiers or Modifiers : Public
Public:
• All the class members declared under public will be available to everyone.
• The data members and member functions declared public can be accessed by other classes
too.
• The public members of a class can be accessed from anywhere in the program using the
direct member access operator (.) with the object of that class.

#include<iostream> int main()


using namespace std; {
// class definition Circle obj;
class Circle // accessing public datamember outside class
{ obj.radius = 5.5;
public: cout << "Radius is:" << obj.radius << "\n";
double radius; cout << "Area is:" << obj.compute_area();
double compute_area() return 0;
{ }
return 3.14*radius*radius;
} Radius is:5.5
}; Area is:94.985
Access Specifiers or Modifiers: Private
Private:
• The class members declared as private can be accessed only by the functions inside the
class.
• They are not allowed to be accessed directly by any object or function outside the class.
• Only the member functions or the friend functions are allowed to access the private data
members of a class.

using namespace std; int main()


class Circle {
{ // creating object of the class
private: Circle obj;
double radius; // private data member // trying to access private data member
// public member function // directly outside the class
public: obj.radius = 1.5;
double compute_area()
cout << "Area is:" << obj.compute_area();
{ // member function can access private
// data member radius
return 0;
return 3.14*radius*radius; }
}
};
Access Specifiers or Modifiers: Private

using namespace std;


class Circle
{
private: int main()
double radius; // private data member {
// public member function // creating object of the class
public:
Circle obj;
double compute_area()
{ // member function can access private
// trying to access private data member
// data member radius // directly outside the class
return 3.14*radius*radius; obj.radius = 1.5; //compile error
} cout << "Area is:" << obj.compute_area();
}; return 0;
}
#include<iostream>
int main()
using namespace std;
{
class Circle
// creating object of the class
{
Circle obj;
// private data member
private:
obj.compute_area(1.5);
double radius;
// public member function
public:
return 0;
void compute_area(double r)
}
{ // member function can access private
// data member radius
radius = r; Output:

double area = 3.14*radius*radius;

cout << "Radius is:" << radius << endl;


cout << "Area is: " << area;
}

};
Array
1-D Array

2-D Array
Linear Search
#include <iostream>
int main()
using namespace std;
{
class Rectangle
Rectangle rt1, rt2;
{
rt1. Set_Data(7, 4);
private:
rt2. Set_Data(4, 5);
int length, breadth;
cout << "Area 1st rect:" << rt1.printArea() << endl;
public:
cout << "Area 2nd rect:" << rt2.printArea() << endl;
void Set_Data( int l, int b )
return 0;
{
}
length = l;
breadth = b;
}
int printArea() Output:
{ Area of 1st rect:28
return length * breadth; Area of 2nd rect:20
}
};
• Suppose we have 50 students in a class and we have to
input the name and marks of all the 50 students.

• Creating 50 different objects and then inputting the name


and marks of all those 50 students is a good option. ?

• Alternative is create an array of objects.


#include <iostream> int main()
using namespace std; {
class Student Student st[5]; //Array of objects
{ for( int i=0; i<5; i++ )
{
char name[20];
cout << "Student " << i + 1 << endl;
int marks; cout << "Enter name" << endl;
public: st[i].getName();
void getName() cout << "Enter marks" << endl;
{ st[i].getMarks();
cin>> name; }
}
void getMarks() for( int i=0; i<5; i++ )
{ {
cin >> marks; cout << "Student " << i + 1 << endl;
st[i].displayInfo();
}
}
void displayInfo() return 0;
{ }
cout << "Name: " << name << endl;
cout << "Marks: " << marks << endl;
}
};

You might also like