Cseoo

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 23

Practical : 1

Programming exercises on control flow statements in C++

EX 1 -Write a program that checks if the angles given can make a triangle or not (their sum must be 180 degrees).

#include <iostream>

using namespace std;

int main()

int angle1,angle2,angle3,sum;

cout<<"Enter the three angles of triangle:";

cin>>angle1>>angle2>>angle3;

sum=angle1+angle2+angle3;

if (sum==180)

cout<< "It is a triangle";

else

cout << "This is not a triangle";

return 0;

EX 2 - Write a program that prints on the screen all the even numbers up to 10.

#include <iostream>

using namespace std;

int main()

for(int x=0;x<=10;x=x+2){
cout<< x;

cout << "\n";

return 0;

EX 3 - Write a program that tells you if a number is even or odd.

#include <iostream>

using namespace std;

int main()

{ int n;

cout<<"Enter the number:\n";

cin>>n;

if (n%2==0)

cout<<"EVEN";

else

cout<<"ODD";

return 0;

EX 4 – Create a calculator using switch statements.

// Program to build a simple calculator using switch Statement

#include <iostream>

using namespace std;

int main() {

char oper;

float num1, num2;

cout << "Enter an operator (+, -, *, /): ";

cin >> oper;

cout << "Enter two numbers: " << endl;

cin >> num1 >> num2;


switch (oper) {

case '+':

cout << num1 << " + " << num2 << " = " << num1 + num2;

break;

case '-':

cout << num1 << " - " << num2 << " = " << num1 - num2;

break;

case '*':

cout << num1 << " * " << num2 << " = " << num1 * num2;

break;

case '/':

cout << num1 << " / " << num2 << " = " << num1 / num2;

break;

default:

// operator is doesn't match any case constant (+, -, *, /)

cout << "Error! The operator is not correct";

break;

return 0;

}
PRACTICAL 2
Programming exercises on arrays, strings, function and pointers in C++

Array
EX 1 - Write a C++ program to find the largest element of a given array of integers.

#include<iostream>
using namespace std;
int find_largest(int nums[], int n) {
return *max_element(nums, nums + n);
}
int main() {
int nums[] = {
5,
4,
9,
12,
8
};
int n = sizeof(nums) / sizeof(nums[0]);
cout << "Original array:";
for (int i=0; i < n; i++)
cout << nums[i] <<" ";
cout << "\nLargest element of the said array: "<< find_largest(nums, n);
return 0;
}

OUTPUT :
Original array:5 4 9 12 8
Largest element of the said array: 12
String

EX 2 - C++ program to Find Length of String

#include<iostream>
#include<string.h>
using namespace std;

int main()
{
int i,count=0;
char ch[50];

cout<<"\nEnter any string :: ";


cin>>ch;

for(i=0;ch[i]!='\0';i++)
{
count++;
}
cout<<"\nLength of String [ "<<ch<<" ] is :: "<<count<<"\n";

return 0;
}

Functions

EX 3 - Write a program that calculates 6^5. Declare your own function to do this.

#include <iostream>
using namespace std;
int raiseToPower(int base, int exponent){
int result = 1;
for (int i = 0; i < exponent; i = i + 1){
result = result * base;
}
return result;
}
int main() {
int sixExpFive = raiseToPower(6, 5);
cout << "6^5 is " << sixExpFive << endl;
return 0;
}
Pointer

EX 4 - Write a program that asks the user to enter integers as inputs to be stored in the variables 'a' and 'b'
respectively. There are also two integer pointers named ptrA and ptrB. Assign the values of 'a' and 'b' to ptrA
and ptrB respectively, and display them.

#include <iostream>
using namespace std;
int main()
{
int a; int b;
cout << "Enter value of A: ";
cin >> a;
cout << "Enter value of B: ";
cin >> b;
int *ptrA=&a;
int *ptrB=&b;
cout << "Value of ptrA is " << *ptrA << " sored in address "<< ptrA<<"\n";
cout << "Value of ptrB is " << *ptrB <<" sored in address "<< ptrB<<"\n";
return 0;
}
PRACTICAL 3
Writing programs to construct classes and deriving objects

#include <bits/stdc++.h>
using namespace std;
class Geeks
{
// Access specifier
public:

// Data Members
string geekname;

// Member Functions()
void printname()
{
cout << "Geekname is: " << geekname;
}
};

int main() {

// Declare an object of class geeks


Geeks obj1;

// accessing data member


obj1.geekname = "Abhi";
// accessing member function
obj1.printname();
return 0;
}
OUTPUT :
Geek name is : Abhi
PRACTICAL 4
Write programs for constructors,destructors,using public and private access specifies.

Constructor

#include<iostream>
#include<conio.h>

using namespace std;

class Example {
// Variable Declaration
int a, b;
public:

//Constructor

Example() {
// Assign Values In Constructor
a = 10;
b = 20;
cout << "Im Constructor\n";
}

void Display() {
cout << "Values :" << a << "\t" << b;
}
};

int main() {
Example Object;
// Constructor invoked.
Object.Display();

// Wait For Output Screen


getch();
return 0;
}

OUTPUT :
Im Constructor
Values : 10 20
Deconstructor

#include<iostream>
#include<conio.h>

using namespace std;

class BaseClass // Class Name


{
public:
//Constructor of the BaseClass
BaseClass() {
cout << "Constructor of the BaseClass : Object Created"<<endl;
}

//Destructor of the BaseClass


~BaseClass() {
cout << "Destructor of the BaseClass : Object Destroyed"<<endl;
}
};

int main ()
{
// Object Declaration for BaseClass
BaseClass des;

// Wait For Output Screen


getch();

//Main Function return Statement


return 0;
}

OUTPUT :
Constructor of the BaseClass : Object Created
Destructor of the BaseClass : Object Destroyed
PROGRAMING FOR USING PUBLIC ACCESS

#include <iostream>
using namespace std;

class base
{
private:
int x;

protected:
int y;

public:
int z;

base() //constructor to initialize data members


{
x = 1;
y = 2;
z = 3;
}
};

class derive: public base


{
//y becomes protected and z becomes public members of class derive
public:
void showdata()
{
cout << "x is not accessible" << endl;
cout << "value of y is " << y << endl;
cout << "value of z is " << z << endl;
}
};
int main()
{
derive a; //object of derived class
a.showdata();
//a.x = 1; not valid : private member can't be accessed outside of class
//a.y = 2; not valid : y is now private member of derived class
//a.z = 3; not valid : z is also now a private member of derived class
return 0;
}

Output

x is not accessible
value of y is 2
value of z is 3
PROGRAMMING FOR USING PRIVATE ACCESS

#include <iostream>
using namespace std;

class base
{
private:
int x;

protected:
int y;

public:
int z;

base() //constructor to initialize data members


{
x = 1;
y = 2;
z = 3;
}
};

class derive: private base


{
//y and z becomes private members of class derive and x remains private
public:
void showdata()
{
cout << "x is not accessible" << endl;
cout << "value of y is " << y << endl;
cout << "value of z is " << z << endl;
}
};
int main()
{
derive a; //object of derived class
a.showdata();
//a.x = 1; not valid : private member can't be accessed outside of class
//a.y = 2; not valid : y is now private member of derived class
//a.z = 3; not valid : z is also now a private member of derived class
return 0;
} //end of program

Output

x is not accessible
value of y is 2
value of z is 3
PRACTICAL 5
Programming exercises on operator overloading

#include<iostream>
using namespace std;

class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i =0) {real = r; imag = i;}

// This is automatically called when '+' is used with


// between two Complex objects
Complex operator + (Complex const &obj) {
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print() { cout << real << " + i" << imag << endl; }
};

int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2; // An example call to "operator+"
c3.print();
}

Output:

12 + i9
PROGRAMMING ON TYPE CONVERSION

#include <iostream>

using namespace std;

int main ()

// assign the integer value

int num1 = 25;

// declare a float variable

float num2;

// convert int value into float variable using implicit conversion

num2 = num1;

cout << " The value of num1 is: " << num1 << endl;

cout << " The value of num2 is: " << num2 << endl;

return 0;

Output

The value of num1 is: 25


The value of num2 is: 25

PROGRAMMING FOR INHERITANCE

#include <iostream>
using namespace std;

// base class
class Animal {

public:
void eat() {
cout << "I can eat!" << endl;
} void sleep() {
cout << "I can sleep!" << endl;
}
};
class Dog : public Animal {

public:
void bark() {
cout << "I can bark! Woof woof!!" << endl;
}
};
int main() {
// Create object of the Dog class
Dog dog1;

// Calling members of the base class


dog1.eat();
dog1.sleep();
// Calling member of the derived class
dog1.bark();
return 0;
}

Output

I can eat!
I can sleep!
I can bark! Woof woof!!
PRACTICAL 6
Programming exercises on functional overloading

#include <iostream>

using namespace std;

class Cal {

public:

static int add(int a,int b){

return a + b;

static int add(int a, int b, int c)

return a + b + c;

};

int main(void) {

Cal C; // class object declaration.

cout<<C.add(10, 20)<<endl;

cout<<C.add(12, 20, 23);

return 0;

Output:

30
55
PRACTICAL -07

Program exercise on stream computation--

#include <iostream>
#include <fstream>
using namespace std;
int main () {
string srg;
ifstream filestream("testout.txt");
if (filestream.is_open())
{
while ( getline (filestream,srg) )
{
cout << srg <<endl;
}
filestream.close();
}
else {
cout << "File opening is fail."<<endl;
}
return 0;
}

Output-
Welcome to javaTpoint.
C++ Tutorial.
PRACTICAL -08

Implementation of a mini project

#include <iostream>
#include <fstream>
#include<string>
using namespace std;
/*
this function add student record to text file
Argument1: filename
Argument2: Pointer to studentCount
*/
void addStudent(string filename, int *studentCount, int *inStateFees, int *outStateFees){
cout<<endl<<"Press any key to add Students details";
getchar();
ofstream file(filename.c_str(), ios::app);
char name[50];
cout<<endl<<"\n Enter Name of Student : ";
gets(name);
file<<endl<<name;
int state=-1;
cout<<endl<<"\n Press 1 for In-State or 2 for Out-Of-State : ";
cin>>state;
if(state==1)
file<<" | In-State";
else if(state==2)
file<<" | Out-Of-State";
else
file<<" | NA";
int tutionFees;
cout<<endl<<"Enter Tution Fees : ";
cin>>tutionFees;
char choice;
cout<<endl<<"Do you want to enroll for Health Plan ? y/n : ";
cin>>choice;
int healthPlan = 0;
if(choice=='Y' || choice=='y'){
char plan;
cout<<endl<<" # Select Optional Health Plan #";
cout<<endl<<"E -> $40";
cout<<endl<<"S -> $160";
cout<<endl<<"C -> $120";
cout<<endl<<"F -> $200";

cout<<endl<<"Select any alphabet ( E, S, C, F ) : ";


cin>>plan;
switch(plan){
case 'E':
case 'e': healthPlan = 40; break;
case 'S':
case 's': healthPlan = 160; break;
case 'C':
case 'c': healthPlan = 120; break;
case 'F':
case 'f' : healthPlan = 200; break;
default: cout<<endl<<"Invalid Choice..";
}
if(healthPlan!=0)
file<<" | Health Plan : "<<plan;
else
file<<" | Health Plan : None"<<plan;
file<<" | "<<tutionFees;
if(state==1){
*inStateFees = *inStateFees + tutionFees + healthPlan;
}
else if(state==2){
*outStateFees = *outStateFees + tutionFees + healthPlan;
}
}
*studentCount = *studentCount + 1;
file.close();
}
/*
function generate the final report by adding total fees details
Argument1: filename
Argument2: Pointer to studnetCount
*/
void generateReport(const string filename, const int *studentCount, const int *inStateFees, const int
*outStateFees){
if(*studentCount==0){
cout<<endl<<"Error: There should be atleast one record to generate report.";
}
else{
ofstream file(filename.c_str(), ios::app);
file<<endl<<"Total Tuition Paid for all In-State Students : "<<*inStateFees;
file<<endl<<"Total Tuition Paid for all Out-of-State Students : "<<*outStateFees;
file.close();
cout<<endl<<"Success: "<<filename<<" generated ";
}
}
//program runs from this function
int main(int argc, char** argv) {
int choice = 0;
string fileName = "tuition_report.txt";
int studentCount =0;
int inStateFees = 0;
int outStateFees =0;
//empty file if it already exist
ofstream file(fileName.c_str(), ios::out);
file.close();
while(choice!=-1){
cout<<endl<<"## (College Student Tuition) ##"<<endl;
cout<<endl<<"1 Add Student Details";
cout<<endl<<"2 Generate Report";
cout<<endl<<"-1 Exit";
cout<<"\n\n Enter your choice : ";
cin>>choice;
switch(choice){
case 1: addStudent(fileName, &studentCount, &inStateFees, &outStateFees);
break;
case 2: generateReport(fileName, &studentCount, &inStateFees, &outStateFees);
break;
case -1: cout<<endl<<"thank you for useing softwer!!";
break;
default: cout<<endl<<"Invalid Choice.."; getchar();
}
}
return 0;
}
PRACTICAL -09
Introduction to ANSI C++ compiler and elaboration of short comings of Turbo C++
compiler—

The ISO / ANSI C++ include several new features to the original C++ specifications. Some of the new features
are added to provide better control in certain situations while others are included to provide convenience to C+
+ programmers. It is to be noted that it is technically possible to write a full C++ program without the use of any
new features. In this chapter, you will learn about some of the important C++ features which are newly
introduced with C++ language.
New features of c++
• • New Data type: o bool
• o wchat_t

• • Operator keywords
• • New Headers
• • Newly introduced operators o const_cast
• o static_cast
• o dynamic_cast
• o reinterpret_cast
• o typeid

• • Namespace scope
• • Class implementation o Explicit Constructors
• o Mutable members

Two new data types have been added to the ANSI C++ for enhancing the range of data type. These are:
bool
This data type has the capability to hold boolean values i.e. wither true or false. The values true and false
have been added to the set of C++ keywords. The bool type variable can be declared as follows:
bool g1;
g1=true;
bool ks = false;
wchar_t
This type of data type has been defined by ANSI C++ for holding 16-bit wide character. These are used to
represent a character set of languages that have
more than 255 characters. This concept is important if programmers write programs for international
distribution having different international languages. Wide_character literals begin with the character/letter L
and is written as:
L 'ab'
New Operators
You might have earlier used the typecast which is used to change the type of variable dynamically. It is used to
convert a value from one type to another. This concept is necessary in cases where the automatic conversion
is not possible within a program. We need to use these following forms of casting:
double y = double (m); // Type casing in C++
double g = (double)n; //Type casting in C
Although these casts still work, ANSI C++ has added new typecast operators. These are:
• • Static casts
• • Dynamic casts
• • Reinterpret casts
• • Constant casts

This new concept also added another operator known as typeid for verifying the type of unknown objects.
Class implementation in C++
New ANSI C++ has 2 unusual keywords, explicit and mutable, generally used with class members. The
explicit keyword is applied in C++ for declaring class constructors to be explicit constructors. As we know that
any constructor that is called with one argument performs the implicit conversion in which the type received by
the constructor is converted to an object of the class in which the constructor is defined.
Example:
class G
{
int x;
public:
explicit G(int i)
{
x=i;
}
........
};
In this case, the objects of G class can be created using only the following form:
G g_obj(100(;
The automatic conversion form:
G g_obj2 = 100;
The mutable keyword also plays a major role in C++. Class objects or member function may be declared as
const, thus making their member data not modifiable. But in programming, there may arise some situations
where programmers may want to create a constant object but would likely to modify particular data item. In
such situations, the data item may be declared as mutable.
Example:
mutable int s;
Although a function that contains k is declared const, the value of k may be modified. This is the special
characteristics of the mutable keyword.
Namespace Scope
Programmers can define their own namespace within a program. The syntax of defining a namespace is
similar to the syntax of defining class. The general form of the namespace is:
Syntax:
namespace namespace_name
{
//Declaration of variables, functions and classes
}

You might also like