C++ Program to split an array into two arrays [DEVCPP/GCC]


PROBLEM

We have to split an array into two arrays in an efficient way as described in the image below.


STEPS

1. Input the elements of an array C (which is to be biparted).

2. Initialize the index variable i and j with 0.

3. Assign the value at jth index of array C to ith index of array A and the value at (j+1)th index of array C to ith index of array B.

4. Increment i by 1 and j by 2.

5. Repeat step 3-4 until j<(size of the composite array), Here 8.

PROGRAM

//Program to split an array into two arrays (in an efficient way)

# include<iostream>

using namespace std;

int main()
{

int a[4],b[4],c[8],i,j;
cout<<"ENTER THE ELEMENTS OF COMPOSITE ARRAY:\n";
 
for(i=0; i<8 ;i++)            //Loop for input
{
cout<<"c["<<i<<"]=";
cin>>c[i];
}
cout<<endl;

for(i=0,j=0 ; j<8 ; i++,j+=2)
{
a[i]=c[j];
b[i]=c[j+1];
}

cout<<"\nPRINT THE ELEMENTS OF ARRAY1:\n";
for(i=0; i<4 ;i++)            //Loop for output
{
cout<<"b["<<i<<"]=";
cout<<b[i]<<endl;
}

cout<<"\nPRINT THE ELEMENTS OF ARRAY2:\n";
for(i=0; i<4 ;i++)            //Loop for output
{
cout<<"a["<<i<<"]=";
cout<<a[i]<<endl;
}

return 0;
}

OUTPUT

C++ Program to split an array into two arrays with output

C++ Program to implement Binary Search [DEVCPP/GCC]

BINARY SEARCH

Binary Search is a fast searching method and it requires the array elements to be sorted. It uses the principle of Divide and Conquer.

Consider that the sorted array is divided into three parts i.e. middle element, Subarray of elements smaller than middle element (Subarray 1) and Subarray of elements larger than the middle element (Subarray 2). The key element can be found either at the middle index or in any one of the subarrays. A recursive approach is applied to the chosen subarray.

C++ Program to implement Binary Search


EXAMPLE

Consider the heights of employee in ascending order ranging from 120-150 cm. We will try to find height 150 cm by applying Binary Search.
C++ Program to implement Binary Search
The index will range from 0-6, thus calculating middle index as (0+6)/2=3. The height at position 3 is 135 cm. Since 135 is not the required height, we will choose a subarray. Since 150 is greater than 135, we will choose subarray 2.

C++ Program to implement Binary Search

Again calculating mid as (4+6)/2=5. The height at position 5 is 145 cm. Since, 145 cm is not the required height, we will again choose a subarray. Since, 150 cm is greater than 145 cm thus again subarray 2 is chosen. 

C++ Program to implement Binary Search

Calculating mid as (6+6)/2=6 and height at index 6 is 150 cm which is the required height. This is how Binary Search works.

TIME COMPLEXITY

BEST CASE: Element found in the first attempt(Middle of the array).
COMPLEXITY: O(1)

AVERAGE CASE: Element found in any other location.
COMPLEXITY: O(log n)

WORST CASE: Element not found or found in the last attempt.
COMPLEXITY: O(log n)

STEPS

1. Input the array elements.

2. Input the key value.

3. Initialize variables with first and last index of array.

4. Calculate middle index.

5. The given key value is first matched with the middle element. If it matches then corresponding index is returned.
   If the key value does not match then the search is applied on one of the subarrays.

6. If the key value is greater than the middle element, then the subarray containing greater elements is selected else the subarray containing smaller elements is selected.

7. Repeat steps 4-6 until element is found or subarray converges into single element.

PROGRAM

//Program to implement Binary Search

#include <iostream>

using namespace std;

int main()
{
int a[10],i,key,mid;
bool found=false;

for(i=0;i<10;i++)
{
cout<<"ENTER A["<<i<<"] ELEMENT: ";
cin>>a[i];
}

cout<<"ENTER ELEMENT TO BE SEARCHED :";
cin>>key;

int first=0,last=9;

while(first<=last)
{
mid= (first+last)/2;

if(a[mid]==key)
{
found=true;
break;
}
else if(a[mid]<key)
{
first=mid+1;        //Restricting to subarray containing Larger values
}
else
{
last= mid-1;        //Restricting to subarray containing Smaller values
}
}

if(found)
{
cout<<"ELEMENT FOUND AT INDEX: "<<mid;
}
else
{
cout<<"ELEMENT NOT FOUND";
}

return 0;
}

OUTPUT

C++ Program to implement Binary Search with output

C++ Program to check whether a number is perfect number or not [DEVCPP/GCC]


PERFECT NUMBER

A positive number is said to be perfect number if it is equal to the sum of its divisors.

For example,
The divisors of 6 are 1,2 and 3 and 1+2+3 = 6. Thus 6 is a perfect number.
The divisors of 28 are 1,2,4,7 and 14 and 1+2+4+7+14 = 28. Thus 28 is a perfect number.

STEPS

1. Initialize a variable sum with 0.

2. Input the number(num) from the user.

3. Initialize a counter (i) with 1.

4. Check the divisibility of num with i.

5. If it is divisible then add i to sum.

6. Increment counter(i).

7. Repeat steps 4-6 until i<=(num/2).

8. If sum is equal to num, then it is a perfect number else not.

PROGRAM

//  Program to check whether given number is perfect number or not.

#include <iostream>

using namespace std;

int main()
{
        int num ,sum=0 ,i;

        cout<<"ENTER A NUMBER: ";
        cin>>num;

        for(i=1;i<=(num/2);i++)
       {
                if(num % i==0)
               {
                        sum = sum + i;
               }
       }

       cout<<endl;

        if(sum==num)
       {
                cout<<num<<" IS A PERFECT NUMBER";
        }
        else
        {
               cout<<num<<" IS NOT A PERFECT NUMBER";
        }
        return 0;
}

OUTPUT

C++ Program to check whether a number is perfect number or not with output


C++ Program to implement Linear Search [DEVCPP/GCC]

LINEAR SEARCH

Linear search consists of an array and a key value (value to be searched). The key value is compared with each value of the array sequentially. If the value is found the corresponding index value is returned.

COMPLEXITY

BEST CASE:  Element found in the first position.
COMPLEXITY: O(1)

WORST CASE: Element not found.
COMPLEXITY: O(n)

AVERAGE CASE: Element found in any location except first.
COMPLEXITY: O(n)

STEPS

1. Initialize a boolean variable(flag) as false.

2. Input the elements of array using a loop.

3. Input key element from the user.

4. Compare the key value with the ith element of the array. (i=0 initially)

5. If the value is matched then set flag as true and break from the loop. If not, then increment i.

6. Repeat steps 4-5 until i <= length of the array.

7. If flag is true, then element is found at i+1th location else the element is not found.

PROGRAM

//Program to implement Linear Search

# include <iostream>

using namespace std;

int main()
 {
          int a[10],i,j,key;
          bool flag=false;

          cout<<"ENTER THE NUMBERS: \n";

          for(i=0;i<10;i++)
         {
                cin>>a[i];
         }
 
         cout<<"\nENTER THE ELEMENT TO BE SEARCHED: ";
         cin>>key;

         for(i=0;i<10;i++)
         {
                    if(a[i]==key)
                    {
                             flag=true;
                             break;
                    }
 
         }

         if(flag)
                cout<<"ELEMENT FOUND AT POSITION: "<<i+1<<endl;
         else
                cout<<"ELEMENT NOT FOUND"<<endl;
       
         return 0;
 }

OUTPUT

C++ Program to implement Linear Search with output

C++ Program to merge two arrays [DEVCPP/GCC]


//Program to merge two arrays (in an efficient way)

# include<iostream>

using namespace std;

int main()
{
int a[4],b[4],c[8],i,j;

cout<<"ENTER THE ELEMENTS OF ARRAY1:\n";
 
          for(i=0 ; i<4 ; i++)             //Loop to input array a
{
cout<<"a["<<i<<"]=";
cin>>a[i];
}
 
cout<<"\nENTER THE ELEMENTS OF ARRAY2:\n";

for(i=0 ; i<4 ; i++)              //Loop to input array b
{
cout<<"b["<<i<<"]=";
cin>>b[i];
}

           for(i=0 , j=0 ; i<4 ; i++ , j=j+2)  //Loop for merging
{
c[j]=a[i];
c[j+1]=b[i];
}

cout<<"\nMERGED ARRAY:\n";

for(i=0 ; i<8 ; i++)
{
cout<<"c["<<i<<"]="<<c[i]<<endl;
}

return 0;
}

C++ Program to merge two arrays with output

C++ Program to check whether given number is prime or not [DEVCPP/GCC]


PRIME NUMBER

A natural number (>1) is said to be a prime number if it is completely divisible by 1 and itself only. A number which is not prime is called Composite number.

eg. 2,3,5,7,11,13 etc are Prime Numbers.

STEPS

In order to find given number is prime or not,

1. Initialize a counter(i) with 2 and a boolean variable (flag) as true.
                                          i = 2;
                                       flag = true;

2. Check the divisibility of the number with i.
                                       num % i==0

3. If the number is divisible by i, then it cannot be a prime number. So, set flag as false and break from loop.
                                        flag = false;
                                          break;

4. If the number is not divisible by i, then increment i and goto step 2 until i <=(num/2).
                                           i++;

5. If flag remains true throughout the above steps, it signifies that it is not divisible by any number between 2 and num/2 i.e. It is a prime number.
    If flag is false then the number is divisible by some number and is not a prime number.

PROGRAM

//Program to check whether given number is Prime or Not

#include <iostream>

using namespace std;

int main()
{
        int num , i;
        bool flag=true;

        cout<<"ENTER A NUMBER: ";
        cin>>num ;

        for( i=2 ; i<=(num/2) ; i++ )
       {
                if(num % i==0)
              {
              flag=false;          
                     break;                   //Exit from the Loop
              }
       }

        if(flag==true)
       {
                cout<<num<<" IS A PRIME NUMBER ";
       }
       else
       {
                cout<<num<<" IS A COMPOSITE NUMBER ";
       }

       return 0;
}

OUTPUT

C++ Program to check whether given number is Prime or Not with output

C++ Program to reverse a single dimensional array without using another array [DEVCPP/GCC]

PROGRAM

//Program to reverse a single dimensional array without using another array

# include <iostream>

using namespace std;

int main()
{
int a[5],i,sum=0;
 
           cout<<"INPUT THE ARRAY ELEMENTS:\n";
for(i=0;i<5;i++)
{
cout<<"a["<<i<<"]=";
cin>>a[i];
}

cout<<"REVERSED ARRAY:\n";
for(i=0;i<2;i++)
{
a[i]=a[i]+a[4-i];
a[4-i]=a[i]-a[4-i];
a[i]=a[i]-a[4-i];
}
 
             for(i=0;i<5;i++)
{
cout<<"a["<<i<<"]="<<a[i]<<endl;
}

return 0;
}

OUTPUT

C++ Program to reverse a single dimensional array without using another array with output

C++ Program to calculate factorial of a number using goto and Labels [DEVCPP/GCC]

STEPS

To calculate factorial of a number,

1. Initialize a variable (fact) with 1.
                     fact=1;

2. Multiply fact with given number(num).
                 fact = fact * num;

3. Decrement num by 1.
                      num--;

4. Repeat steps 2-3 until num>0.

PROGRAM

//Program to calculate factorial of a number using goto and Labels

#include <iostream>

using namespace std;

int main()
{
        int num ,n ;
        long long fact=1;

        cout<<"ENTER NUMBER: ";
        cin>>num;

        n=num;

        Top:                        //Label Top

                  if(num>0)
                 {
                        fact = fact * num ;
                        num--;
                        goto Top;            // Switches control to Label Top
                 }

        cout<<"FACTORIAL OF "<<n<<" IS "<<fact;

        return 0;
}

OUTPUT

C++ Program to calculate factorial of a number using goto and Labels with output

C++ Program to reverse a single dimensional array using another array [DEVCPP/GCC]

PROGRAM

//Program to reverse a single dimensional array using another array.

# include <iostream>

using namespace std;

int main()
{
int a[5],b[5],i,sum=0;

cout<<"INPUT THE ARRAY ELEMENTS:\n";
for(i=0;i<5;i++)
{
cout<<"a["<<i<<"]=";
cin>>a[i];
}

cout<<"\nREVERSED ARRAY:\n";
for(i=0;i<5;i++)
{
b[i]=a[4-i];
cout<<"b["<<i<<"]="<<b[i]<<endl;
}
 
            return 0;
}

OUTPUT

C++ Program to reverse a single dimensional array using another array with output

C++ Program to perform the addition of elements of an array [DEVCPP/GCC]

PROGRAM

//A simple program to perform the addition of elements of an array

# include <iostream>

using namespace std;

int main()
{
int a[5] , i , sum=0 ;

cout<<"INPUT THE ARRAY ELEMENTS:\n";
for(i=0;i<5;i++)
{
cout<<"a["<<i<<"]=";
cin>>a[i];
}

for(i=0;i<5;i++)           //Loop for addition
{
sum=sum+a[i];
}

cout<<"SUM IS:"<<sum;
return 0;
}

OUTPUT

C++ Program to perform the addition of elements of an array with output
 

C++ Program to obtain the sum of digits of given number [DEVCPP/GCC]

STEPS

In order to calculate the sum of digits of a given number,

1. Obtain the last digit of given number using modulus (% ) operator.
                                    123 % 10 = 3

2. Add the obtained digit in a variable (sum) which is initialized by 0.
                                       0 + 3 = 3

3. Divide the number by 10 in order to remove the last digit from given number.
                                      123/10 = 12

4. Repeat the above steps 1-3 until number is not zero.                              

PROGRAM

//Program to obtain the sum of digits of given number

#include <iostream>

using namespace std;

int main()
{
        int num,sum=0,last;

        cout<<"ENTER NUMBER: ";
        cin>>num;

        while(num>0)
        {
                last = num % 10;          // Obtain Last Digit Of Number
                sum = sum + last;        // Add Obtained Digit to Number
                num = num /10;          // Remove Last Digit From Number
        }

        cout<<"\nSUM OF DIGITS IS "<<sum;
        return 0;
}

OUTPUT

C++ Program to obtain the sum of digits of given number

C++ ARRAYS


ARRAY

An array is a collection of elements(variables) of similar types that are referenced by a common name.

All the elements in an array are stored sequentially (contiguous memory locations), and each element of array behaves like a normal variable.

Square brackets ([]) are used to index array values.

NEED OF ARRAY

Ordinary variables store one value at a time, whereas arrays are used for storing more than one values at a time under a single variable name.

Arrays are useful in case where we need to store multiple values having the same datatype. For instance, to store marks of 50 students.

ARRAY DECLARATION 

                               Datatype array_name [size];
                     
                                     int  marks [50];

TYPES OF ARRAY

1. One dimensional array
2. Multidimensional array

PROGRAM

//Program to demonstrate how to input the elements of an array

# include <iostream>

using namespace std;

int main()
{
int a[10],i;

cout<<"ENTER THE ELEMENTS OF ARRAY:\n";

for(i=0;i<10;i++)            //Loop For Input
{
cout<<"a["<<i<<"]=";
cin>>a[i];
}
cout<<endl;

      for(i=0;i<10;i++)           //Loop For Output
{
cout<<"a["<<i<<"]=";
cout<<a[i]<<endl;
}
 
return 0;
}

OUTPUT



C++ Program to convert a String into Title Case [DEVCPP/GCC]


TITLE CASE

A sentence is said to be in Title Case if all of its constituent words begins with an Uppercase Letter.

                eg:   Input:    vijay dinanath chouhan
                       Output:  Vijay Dinanath Chouhan

PROGRAM

//Program to convert a string into Title case

# include <iostream>

using namespace std;

int main()
{
int i;
char a[30];
cin.getline(a,30);   //To Input a String
a[0]=a[0]-32;        //For First Letter

for(i=0;a[i]!='\0';i++)
{
if(a[i]==' ')
{
a[i+1] = a[i+1]-32;
}
}

cout<<a;
return 0;
}

OUTPUT

C++ Program to convert a String into Title Case with output

C++ Program to check whether user has entered integer data or not [DEVCPP/GCC]


STREAM RELATED FUNCTIONS

fail()


This function returns true whenever an error occurs in input operation.

clear()

This function overwrites the stream error state flags.

ignore()

It is used to discard characters from input stream.

PROGRAM

// Program to check whether user has entered integer data or not

#include <iostream>

using namespace std;

int main()
{
        int num ;
        char ch;

        do
{

cout<<"\n\nENTER NUMBER: ";
cin>>num ;

if(cin.fail())                                    // Checks For Undesired Input
{
cout<<"PLEASE ENTER A NUMBER !";
cin.clear();                                //  Overwrites the Error Flags
cin.ignore(INT_MAX , '\n');    //  Clears Input Stream
}
else
{
cout<<"YOU ENTERED "<<num;
}

cout<<"\nDO YOU WISH TO CONTINUE(Y/N): ";
cin>>ch;

}while(ch=='y'||ch=='Y');

return 0;
}

OUTPUT

C++ Program to check whether user has entered integer data or not with output

C++ Program to find the largest even number and largest odd number [DEVCPP/GCC]

PROGRAM

// Program to find the largest even number and largest odd number, from the list of numbers entered    by user, list terminates as the user enters zero

# include <iostream>

using namespace std;

int main()
{
int num, meven=0, modd=1;

cout<<"ENTER NUMBER (0 TO TERMINATE):\n";

do
{
cin>>num;
 
               if(num%2==0)
{
if(num>meven)
meven=num;
}
else
{
if(num>modd)
modd=num;
}

}while(num);

cout<<"LARGEST EVEN NUMBER IS:"<<meven<<endl;
cout<<"LARGEST ODD NUMBER IS:"<<modd<<endl;

return 0;
}

OUTPUT

C++ Program to find the largest even number and largest odd number

C++ Program for Mini Calculator [DEVCPP/GCC]

PROGRAM

//A simple program for Mini Calculator using do-while loop and conditional statements.

# include <iostream>

using namespace std;

int main()
{
int op1,op2,res=0;
char ch,con;

do
{

cout<<"\nENTER TWO NUMBERS:\n";
cin>>op1>>op2;

cout<<"ENTER OPERATOR(+,-,*,/,%):\n";
cin>>ch;

switch(ch)
{
case '+':
res=op1+op2;
break;

case '-':
res=op1-op2;
break;

case '*':
res=op1*op2;
break;

case '/':
 
                           if(!op2)                // True when op2 is zero
cout<<"DIVIDE BY ZERO ERROR!!!\n";
else
res=op1/op2;
 
  break;

case '%':
 
                           if(!op2)               // True when op2 is zero
cout<<"DIVIDE BY ZERO ERROR!!!\n";
else
{
                                  int q,r;
q=op1/op2;
r=op1-(op2*q);
res=r;
}

break;

default :
cout<<"WRONG OPERATOR\n";
}

cout<<"THE CALCULATED RESULT IS:"<<res<<"\n\n";

cout<<"DO YOU WISH TO CONTINUE:";
cin>>con;
 
}while(con=='Y'|| con=='y');

return 0;
}

OUTPUT

C++ Program for Mini Calculator with output

FIND US ON FACEBOOK!