function-in-cpp

Today we are going to learn some basic of c++ .
1. cin and cout
2. Manipulators in C++
3. Reference data types
4. Function
5. Structure and class difference(exam will ask objective on this)
6. C++ Structure

Basic Input Using std::cin and Output Using std::cout :


The cin object in C++ is an object of class istream. It is used to accept the input from the standard input device i.e. keyboard. It is associated with the standard C input stream stdin.

The “c” in cin refers to “character” and ‘in’ means “input”, hence cin means “character input”.

The cin object is used along with the extraction operator (>>) in order to receive a stream of characters. The general syntax is:

                cin >> varName;

        

The extraction operator can be used more than once to accept multiple inputs as see example below :

                cin >> var1 >> var2 >> … >> varN;
        


The cin object can also be used with other member functions such as getline(), read(), etc. Some of the commonly used member functions :
1. cin.get(char &ch): Reads an input character and store it in ch.

2. cin.read(char *buffer, int n): Reads n bytes (or until the end of the file) from the stream into the buffer.

3. cin.ignore(int n): Ignores the next n characters from the input stream.

Lets take simple coding example in C++ :

 

    #include <iostream>
    using namespace std;
    int main()
    {
        int x, y, z;
        
        /* For single input */
        cout << "Enter a number: ";
        cin >> x;
        
        /* For multiple inputs*/
        cout << "Enter 2 numbers: ";
        cin >> y >> z;
        
        cout << "Sum = " << (x+y+z);
        return 0;
    }
    

Output

                Enter a number: 1
                Enter 2 numbers: 2, 3
                Sum = 6
                So above program is just taking input from user using cin and storing 
                in variable and then doing sum of all 3 and 
                after that using cout priniting result on screen . 
        



C++ Manipulators :

Manipulators are operators used in C++ for formatting output. The data is manipulated by the programmer’s choice of display.

1. endl Manipulator:

This manipulator has the same functionality as the ‘n’ newline character.

cout << “Exforsys” << endl; endl used to print on new line .

2. setw Manipulator:

This manipulator sets the minimum field width on output.

setw(x)



3. setfill:


setfill character is used in output insertion operations to fill spaces when results have to be padded to the field width.

Lets take an simple example
 
                    #include <iostream.h>
                    #include <iomanip.h>
                    int main()
                    {
                        cout<<"USING setw() ..............\n";
                        cout<< setw(10) <<11<<"\n";
                        cout<< setw(10) <<2222<<"\n";
                        cout<< setw(10) <<33333<<"\n";
                        cout<< setw(10) <<4<<"\n";
                
                        cout<<"USING setw() & setfill() [type- I]...\n";
                        cout<< setfill('0');
                        cout<< setw(10) <<11<<"\n";
                        cout<< setw(10) <<2222<<"\n";
                        cout<< setw(10) <<33333<<"\n";
                        cout<< setw(10) <<4<<"\n";
                
                        cout<<"USING setw() & setfill() [type-II]...\n";
                        cout<< setfill('-')<< setw(10) <<11<<"\n";
                        cout<< setfill('*')<< setw(10) <<2222<<"\n";
                        cout<< setfill('@')<< setw(10) <<33333<<"\n";
                        cout<< setfill('#')<< setw(10) <<4<<"\n";
                        return 0;
                    }
                

Output :

                USING setw() ..............
                        11
                      2222
                     33333
                         4
                USING setw() & setfill() [type- I]...
                0000000011
                0000002222
                0000033333
                0000000004
                USING setw() & setfill() [type-II]...
                --------11
                ******2222
                @@@@@33333
                #########4
                

 

 

References in C++ :


References are like constant pointers that are automatically dereferenced. It is a new name given to an existing storage. So when you are accessing the reference, you are actually accessing that storage.

                        int main()
                        { 
                            int y=10;
                            int &r = y;  // r is a reference to int y
                            cout << r;
                        }
                

Difference between Reference and Ponters

ReferencesPointers
Reference must be initialized when it is created.Pointers can be initialized any time.
Once initialized, we cannot reinitialize a reference.Pointers can be reinitialized any number of time.
You can never have a NULL reference.Pointers can be NULL.
Reference is automatically dereferenced.* is used to dereference a pointer.



Const Reference:

Const reference is used in function arguments to prevent the function from changing the argument.


                        void f(const int& x)
                        { 
                            x++; 
                        }   // ERROR
                        
                        int main()
                        {
                            int i=10;
                            f(i);
                        }
                


We cannot change the argument in the function because it is passed as const reference.

C++ Functions :


Depending on whether a function is predefined or created by programmer; there are two types of function:

Library Function
User-defined Function

Library Function

Library functions are the built-in function in C++ programming.

Programmer can use library function by invoking function directly; they don’t need to write it themselves.

Lets take as simple example to understand :

                     #include <iostream>
                    #include <cmath>
                    using namespace std;
                    int main()
                    {
                        double number, squareRoot;
                        cout << "Enter a number: ";
                        cin >> number;
                        // sqrt() is a library function to calculate square root
                        squareRoot = sqrt(number);
                        cout << "Square root of " << number << " = " << squareRoot;
                        return 0;
                    }
                

Output :

                        Enter a number: 36
                        Square root of 36 = 6
                



In the example above, sqrt() library function is invoked to calculate the square root of a number.

Notice code #include <cmath> in the above program. Here, cmath is a header file. The function definition of sqrt()(body of that function) is present in the cmath header file.

You can use all functions defined in cmath when you include the content of file cmath in this program using #include .

User-defined Function :

C++ allows programmer to define their own function called as user defined functions.

A user-defined function groups code to perform a specific task and that group of code is given a name(identifier).

When the function is invoked from any part of program, it all executes the codes defined in the body of function.

So as you know human can understand onlt after giving examples so lets do :

Write c++ program with user defined function to add two numbers ?

 

                    #include <iostream>
                    using namespace std;
                    // Function prototype (declaration)
                    int add(int, int);  // function declaration
                    int main()
                    {
                        int num1, num2, sum;
                        cout<<"Enters two numbers to add: ";
                        cin >> num1 >> num2;
                        // Function call
                        sum = add(num1, num2);  // calling our add function 
                        cout << "Sum = " << sum;   
                        return 0;
                    }
                    // Function definition  
                    int add(int a, int b)
                    {
                        int add;
                        add = a + b;
                        // Return statement
                        return add;  // return sum of two numbers
                    }
                

 

Output :
                        Enters two integers: 80
                        2
                        Sum = 82
                

 

Function prototype (declaration) :

If a user-defined function is defined after main() function, compiler will show error. It is because compiler is unaware of user-defined function, types of argument passed to function and return type.

In C++, function prototype is a declaration of function without its body to give compiler information about user-defined function. Function prototype in the above example is:

                        int add(int, int);
                


so this is called function declaration please remember declaration and definition is both different
we are declaring means just giving name of the function with args .

Function Definition :

Function definition means we have full body of function means we writing our own code within {} brackets .

                        int add(int a,int b)
                        {
                            int add;
                            add = a + b;
                            return add;
                        }
                        This is called definition of function also called define function  .
                



When the function is called, control is transferred to the first statement of the function body.

Then, other statements in function body are executed sequentially.

When all codes inside function definition is executed, control of program moves to the calling program.

Function Call :

When we make function call then control is transferred to our function first .
In the above program, add(num1,num2); inside main() function calls the user-defined function.

The function returns an integer which is stored in variable add.

Passing Arguments to Function :

See our above program :
In programming, argument (parameter) refers to the data which is passed to a function (function definition) while calling it.

In the above example, two variables, num1 and num2 are passed to function during function call. These arguments are known as actual arguments.

The value of num1 and num2 are initialized to variables a and b respectively. These arguments a and b are called formal arguments.

Difference between Class and Structure :

 

Class :

Class is a reference type and its object is created on Heap memory.

Class can inherit the another class.

Class can have constructor and destructor of all types.

The member variable can be initialized directly.

Class object cannot be created without using the new keyword, it means we have to use it. Eg: Demo obj=new Demo();


Structure :

Structure is a value type that is why its object is created on Stack memory.

Structure does not support the inheritance and cannot inherit another class.

Structure can only have the parametrized constructor. it means a structure can not have the non-parametrized constructor,

default constructor and destructor also.

The member variable cannot be initialized directly.

Structure object can be created without using the new keyword.(optional). Eg: Demo obj;

 

C++ Classes/Objects

Everything in C++ is associated with classes and objects, along with its attributes and methods. For example: in real life, a car is an object. The car has attributes, such as weight and color, and methods, such as drive and brake.

Attributes and methods are basically variables and functions that belongs to the class. These are often referred to as “class members”.

A class is a user-defined data type that we can use in our program, and it works as an object constructor, or a “blueprint” for creating objects.

How to define a class in C++? :


A class is defined in C++ using keyword class followed by the name of class.

The body of class is defined inside the curly brackets and terminated by a semicolon at the end.

                        lass className
                        {
                        // some data
                        // some functions
                        };
                


Lets take an real programming example :

                   class some
                   {
                       private:
                           int data1;
                           float data2;  
                       public:  
                           void function1()
                           {   data1 = 2;  } 
                           float function2()
                           { 
                               data2 = 3.5;
                               return data2;
                           }
                    };
                



So we have defined our class with name some

data1 and data2 and the data members of some class

function1() and function2() are the member functions of some class .

What is Private and Public here ? :

The private keyword makes data and functions private. Private data and functions can be accessed only from inside the same class.

The public keyword makes data and functions public. Public data and functions can be accessed out of the class.

Here, data1 and data2 are private members where as function1() and function2() are public members.

If you try to access private data from outside of the class, compiler throws error. This feature in OOP is known as data hiding.

That means you cant access data members outside class if they are declard as private .

C++ Objects :

When class is defined, only the specification for the object is defined; no memory or storage is allocated.(Remember this may be your objective question)

To use the data and access functions defined in the class, you need to create objects.

            class Test
            {
                private:
                    int data1;
                    float data2;  
                public:  
                    void function1()
                    {   data1 = 2;  } 
                    float function2()
                    { 
                        data2 = 3.5;
                        return data2;
                    }
               };
            int main()
            {
                Test o1, o2;
            }
        



Here ,two objects o1 and o2 of Test class are created.

How to access data member and member function in C++?

Now we have created o1,o2 as our objects so by using this objects we can call or access functions .

                o2.function1(); 
                // This will call function1
        



Similarly, the data member can be accessed as:

                o1.data2 = 5.5; // here we are assign 5.5 value to above data2 variable using object . 



It is important to note that, the private members can be accessed only from inside the class.

So, you can use o2.function1(); from any function or class in the above example. However, the code o1.data2 = 5.5; should always be inside the class Test.

Lets take an simple coding example to understand :

                // Program to illustrate the working of objects and class in C++ Programming
                #include <iostream>
                using namespace std;
                class Test
                {
                    private:
                        int data1;
                        float data2;
                    public:
                       
                       void insertIntegerData(int d)
                       {
                          data1 = d;
                          cout << "Number: " << data1;
                        }
                       float insertFloatData()
                       {
                           cout << "\nEnter data: ";
                           cin >> data2;
                           return data2;
                        }
                };
                 int main()
                 {
                      Test o1, o2;
                      float secondDataOfObject2;
                      o1.insertIntegerData(12);
                      secondDataOfObject2 = o2.insertFloatData();
                      cout << "You entered " << secondDataOfObject2;
                      return 0;
                 }
        



Output :

                Number: 12
                Enter data: 23.3
                You entered 23.3
        



In the above program, two data members data1 and data2 and two member functions insertIntegerData() and insertFloatData() are defined under Test class.

Two objects o1 and o2 of the same class are declared.

The insertIntegerData() function is called for the o1 object using:

Then, the insertFloatData() function for object o2 is called and the return value from the function is stored in variable secondDataOfObject2

So remember one point we can create multiple objects for same class and use for different purpose .

Lets do some Assignments :

 

1. Write a program in C++ to swap two numbers ? create swap function and call it from main function
2. Write a program in C++ to print the following pattern ?
                xxxxx                                                                                                        
                x     x       x        x                                                                                      
                x             x        x                                                                                      
                x          xxxxxxx  xxxxxxx                                                                                   
                x             x        x                                                                                      
                x     x       x        x                                                                                      
                xxxxx  
        
3. Write a C++ program to generate fibonacci series .
4. Write C++ program to create class to get and print details of a student .
            Output like  :
            Enter name: Abhijeet
            Enter roll number: 1
            Enter total marks outof 500: 456
            Student details:
            Name:Abhijeet,Roll Number:1,Total:456,Percentage:91.2