Harsh Vardhan Pant, Assistant Professor Amrapali Group of ...

59
C++ Harsh Vardhan Pant, Assistant Professor Amrapali Group of Insitute, Haldwani

Transcript of Harsh Vardhan Pant, Assistant Professor Amrapali Group of ...

C++

Harsh Vardhan Pant,

Assistant Professor

Amrapali Group of Insitute, Haldwani

Loop

• A Loop executes thesequence of statementsmany times until thestated conditionbecomes false.

• A loop consists of twoparts, a body of a loopand a controlstatement.

While Loop

#include<stdio.h> #include<conio.h> int main() {

int num=1; //initializing the variable while(num<=10) //while loop with condition

{printf("%d\n",num); num++; //incrementing operation }

return 0; }

Out put

• 1 2 3 4 5 6 7 8 9 10

While

Do-While loop

• do {

statements

• } while (expression);

Do While Loop

Out put

• 2 4 6 8 10 12 14 16 18 20

For Loop

For LOOP

Output

• 1 2 3 4 5 6 7 8 9 10

Out put

Nested Loop

Out-put

Break Statement

Output:

• 5, 4

Continue Statement

Output

• 6

• 4

• 3

• 2

• 1

Array

An array is used to store a collection ofdata, but it is often more useful to think ofan array as a collection of variables of thesame type.

How to declare an array?

• An array is a variable that can store multiplevalues. For example, if you want to store 100integers, you can create an array for it.

• int data[100];

• dataType arrayName[arraySize];

• For example,

• float mark[5];

How to initialize an array?

• It is possible to initialize an array duringdeclaration. For example,

• int mark[5] = {19, 10, 8, 17, 9};You can alsoinitialize an array like this.

• int mark[] = {19, 10, 8, 17, 9};Here, we haven'tspecified the size. However, the compilerknows its size is 5 as we are initializing it with5 elements.

Size of Array

Input and Output Array Elements

• Here's how you can take input from the user and store it in an array element.

// take input and store it in the 3rd element

• scanf("%d", &mark[2]);

// take input and store it in the ith element

• scanf("%d", &mark[i-1]);

Here's how you can print an individual element of an array.

Example 1: Array Input/Output

Function

• Defining a Function

• The general form of a function definition in C programming language is as follows −

• return_type function_name( parameter list )

{ body of the function }

Void main()

{ printf(“Hello”);}

Finction

Function Program

About C ++

• C++ is a general-purpose programminglanguage created by Bjarne Stroustrup as anextension of the C programming language, or"C with Classes".

Real-World Applications Of C++

• Games

• GUI Based Applications like adobe systems, Win Amp Media Player

• Database Software, MYSQL Server

• Operating Systems, Apple OS X

• Microsoft Windows OS

• Browsers, Firefox, Google File System , Chrome browser

• Alias System, Alias System

Multiple features –

• C++ is an Object Oriented Programming Language (OOPL).

• C++ have huge Function Library• C++ can be used for developing System

Software viz., operating systems, compilers, editors and data bases.

• C++ is suitable for Development of Reusable Software. , thus reduces cost of software development.

• C++ is a Machine Independent Language.

Methodology

• a system of methods used in a particular area of study or activity.

Methodology Vs. Methods

OOPS Concept

// Program to illustrate the working of objects and class in C++ Programming

• #include <iostream>

• class Test

• {

• private:

• int data1;

• float data2;

• public:

• void get_data()

• {

• cout<<"Enter a Intergervalue"<<"\n";

• cin>>data1;

• cout<<"Enter a real value"<<"\n";

• cin>>data2

• }

• void Print_data()• {• cout<<"The Entered Interger

value is "<<data1;<<"\n";• cout<<"The Entered real value is

"<<data2;<<"\n";• }

• };

• int main()• {• Test ob1;• ob1.get_data();• ob1.Print_data();• return 0;• }

Object

• This is the basic unit of object orientedprogramming. That is both data and functionthat operate on data are bundled as a unitcalled as object.

Class

• A class is a blueprint for the object

• We can think of class as a sketch (prototype) of ahouse. It contains all the details about the floors,doors, windows etc. Based on these descriptionswe build the house. House is the object.

• As, many houses can be made from the samedescription, we can create many objects from aclass.

• .

So far we have defined following things,

•Class - Dogs

•Data members or objects- size, age, color, breed,

etc.

•Methods- eat, sleep, sit and run.

Now, for different values of data members (breed

size, age, and color) in C++ class, you will get

different dog objects.

You can design any program using this OOPs approach.

// Class Declaration

public class Dog {

// Instance Variables

String breed;

String size;

int age;

String color;

// method 1

public String getInfo() {

return ("Breed is: "+breed+" Size is:"+size+" Age

is:"+age+" color is: "+color); }

public static void main(String[] args) { Dog maltese =

new Dog(); maltese.breed="Maltese";

maltese.size="Small"; maltese.age=2;

maltese.color="white";

System.out.println(maltese.getInfo()); } }Output:Breed

is: Maltese Size is:Small Age is:2 color is: white

What is Data Abstraction?

Abstraction refers to the act of representing

essential feature without including the

background details. Since the class use the

concept of data abstraction they are known as

abstruct data type.

Example of Abstraction

• #include <iostream>• class Sum• {• private: int x, y, z; // private varia

bles• public:• void add()• {• cout<<"Enter two numbers: ";• cin>>x>>y;• z= x+y;• cout<<"Sum of two number is: "<

<z<<endl;• }• };

• int main()• {• Sum sm;• sm.add();• return 0;• }

Out-put

• Enter two numbers: 3 6 Sum of two number is: 9

Advantages Of Abstraction:

• Implementation details of the class are protected fromthe inadvertent user level errors.

• A programmer does not need to write the low levelcode.

• Data Abstraction avoids the code duplication, i.e.,programmer does not have to undergo the same tasksevery time to perform the similar operation.

• The main aim of the data abstraction is to reuse thecode and the proper partitioning of the code across theclasses.

• Internal implementation can be changed withoutaffecting the user level code.

Function Overloading

• Function Overloading is defined as the process ofhaving two or more function with the same name, butdifferent in parameters is known as functionoverloading in C++. In function overloading, thefunction is redefined by using either different types ofarguments or a different number of arguments. It isonly through these differences compiler candifferentiate between the functions.

• The advantage of Function overloading is that itincreases the readability of the program because youdon't need to use different names for the same action.

Constructors

• Constructors are special class functions whichperforms initialization of every object. TheCompiler calls the Constructor whenever anobject is created. Constructors initialize valuesto object members after storage is allocatedto the object.

Out Put

Void main()

{

int x=10; //initialize the value

cout<<x*x; //Print the value

}

out-put

100

Out Put

Void main()

{

int x;

cout<<x*x; //Print the value

}

out-put

?

Default Constructor

• Default constructor is the constructor which doesn't take any argument. It has no parameter.

• Syntax :

class_name ()

{

Constructor Definition

}

Example

class Cube

{

int side;

public:

Cube()

{

side=10;

}

};

int main()

{

Cube c;

cout << c.side;

}

Default Constructor

• In this case, as soon as the object is created theconstructor is called which initializes its datamembers.

• A default constructor is so important for initializationof object members, that even if we do not define aconstructor explicitly, the compiler will provide adefault constructor implicitly.

Parameterized Constructor

• These are the constructors with parameter. Usingthis Constructor you can provide different values todata members of different objects, by passing theappropriate values as argument.

Example

class Cube

{

int side;

public:

Cube(int x)

{

side=x;

}

};

int main()

{

Cube c1(10);

Cube c2(20);

Cube c3(30);

cout << c1.side;

cout << c2.side;

cout << c3.side;

}

Function Overloading

• class Cal {• public:• int add(int a,int b){• return a + b;• }• 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;• }

Out-Put

• 30 55

Inheritance

• In C++, inheritance is a process in which oneobject acquires all the properties andbehaviors of its parent object automatically. Insuch way, you can reuse, extend or modify theattributes and behaviors which are defined inother class.

Where,derived_class_name: It is the name of the derived class.visibility mode: The visibility mode specifies whether the features of the baseclass are publicly inherited or privately inherited. It can be public or private.base_class_name: It is the name of the base class.When the base class is privately inherited by the derived class, public membersof the base class becomes the private members of the derived class. Therefore,the public members of the base class are not accessible by the objects of thederived class only by the member functions of the derived class.When the base class is publicly inherited by the derived class, public membersof the base class also become the public members of the derived class.Therefore, the public members of the base class are accessible by the objectsof the derived class as well as by the member functions of the base class.

#include <iostream>

class Animal {

public:

void eat() {

cout<<"Eating..."<<endl;

} };

class Dog: public Animal

{

public:

void bark(){

cout<<"Barking..."; }

};

int main(void) {

Dog d1;

d1.eat();

d1.bark();

return 0;

}