Showing posts with label BASIC. Show all posts
Showing posts with label BASIC. Show all posts

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

PERNICIOUS NUMBER

pernicious number is a positive integer which has prime number of ones in its binary representation.

PROGRAM

// C++ Program to check given number is Pernicious or not

#include <iostream>
#include <bitset>
#include <cassert>

using namespace std;

bool isPrime(int num)
{
    if(num == 1)
        return false;
   
    for(int j=2 ; j<=(num/2) ; j++)
    {
        if(num % j == 0)
            return false;
    }
   
    return true;
}

int main()
{
    long num, count = 0;
   
    cout << "ENTER A NUMBER : ";
    cin>>num;
 
    assert(num > 0);
 
    string binary = bitset<8>(num).to_string();
   
    for(int i=0 ; i < binary.length(); i++)
    {
        if(binary[i] == '1')
            count++;
    }
   
    if(isPrime(count))
        cout<<endl<<num<<" IS A PERNICIOUS NUMBER";
    else
        cout<<endl<<num<<" IS NOT A PERNICIOUS NUMBER";
 
   return 0;
}

OUTPUT


C/C++ Program to check whether a string is palindrome or not using string functions [DEVCPP/GCC]

PROGRAM

//Program to check whether a string is palindrome or not using string functions.

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

int main()
{
char str1[10],str2[10],c;

do
{
cout<<"\nENTER A STRING: ";
cin>>str1;

strcpy(str2,str1);                        //copies the content of str1 to str2

strrev(str1);                                //reverses str1 

if(strcmp(str1,str2)==0)            //compares str1 and str2
cout<<"GIVEN STRING IS PALINDROME";
else
cout<<"GIVEN STRING IS NOT PALINDROME";

cout<<"\n\nDO YOU WISH TO CONTINUE (Y/N)? ";
cin>>c;

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

return 0;
}

OUTPUT

C++ Program to check whether a string is palindrome or not using string functions

C++ Program to illustrate function overloading [DEVCPP/GCC]


FUNCTION OVERLOADING

C++ allows specification of more than one function under the same name in the same scope. These functions must have different signatures and are called overloaded functions. Overloading of functions allow programmer to define different semantics for a function, depending upon number and type of arguments.

For instance, in order to find maximum number, the function max() can be overloaded as:

int max (int num1, int num2);
int max (int num1, int num2, int num3);

Although functions can be distinguished on the basis of return type, they cannot be overloaded on this basis. 

PROGRAM

/* Program to calculate area of square, rectangle and circle using overloaded function area */

#include <iostream>

using namespace std;

float area( int length, int breadth )
{
        return (length * breadth);
}

float area( int side )
{
        return (side * side);
}

float area( float radius )
{
        return (3.14 * radius * radius);
}

int main()
{
        char ch='y';
        int s,c,l,b;
        float r;

        do
        {
              cout<<"\n\n\t***AREA CALCULATOR***";
              cout<<"\n 1. SQUARE";
              cout<<"\n 2. RECTANGLE";
              cout<<"\n 3. CIRCLE";
              cout<<"\n 4. EXIT";
              cout<<"\nENTER YOUR CHOICE(1-4): ";
              cin>>c;

              switch(c)
              {
                      case 1:
                      {
                              cout<<"\nENTER SIDE: ";
                              cin>>s;

                              cout<<"AREA OF SQUARE: "<<area(s);
                              break;
                    }

                    case 2:
                      {
                              cout<<"\nENTER LENGTH: ";
                              cin>>l;
                              cout<<"ENTER BREADTH: ";
                              cin>>b;

                              cout<<"AREA OF RECTANGLE: "<<area(l,b);
                              break;
                      }

                      case 3:
                      {
                               cout<<"\nENTER RADIUS: ";
                               cin>>r;

                               cout<<"AREA OF CIRCLE: "<<area(r);
                               break;
                       }

                       case 4:
                       {
                                exit(0);
                        }

                        default:
                        {
                                 cout<<"YOU ENTERED WRONG CHOICE!";
                        }
             }

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

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

OUTPUT


C++ Program to illustrate function overloading


C++ Program to illustrate the difference between call by value and call by reference [DEVCPP/GCC]

CALL BY VALUE

In call by value, a copy of actual parameter is passed to the calling function. The passed value to the function is locally stored by the function parameter in stack memory. Here both formal parameters and actual parameters share different address apace. Thus any changes in formal parameters is not reflected back in actual parameters.

CALL BY REFERENCE

In call by reference, reference(address) of the actual parameters is passed to the calling function (See Reference Variables). It results in creation of alias for the actual parameters and both actual parameters and formal parameters refers to the same memory location. Thus any changes in formal parameters is reflected back in actual parameters.

PROGRAM

// Program to illustrate the difference between call by value and call by reference

#include <iostream>

using namespace std;

void callByValue(int n)
{
        n=n*n;
        cout<<"\nNUM IN FUNCTION: "<<n;
}

void callByReference(int &n)
{
        n=n*n;
        cout<<"\nNUM IN FUNCTION: "<<n;
}

int main()
{
        int num;

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

        cout<<"\n\nCALLING BY VALUE!\n";
        callByValue(num);

        cout<<"\nNUM IN MAIN: "<<num;

        cout<<"\n\nCALLING BY REFERENCE!\n";
        callByReference(num);

         cout<<"\nNUM IN MAIN: "<<num;
 return 0;
}

OUTPUT

C++ Program to illustrate the difference between call by value and call by reference with output

C++ Program to generate random number [DEVCPP/GCC]

RAND FUNCTION

It is a pseudo random generator which generates a random number between 0 and RAND_MAX. In order to generate random number in user defined range, this function can be used with modulus operator.

// Generates random number between 0 to 99      
int r1 = rand() % 100;                          

// Generates random number between 1 to 100     

int r2 = rand() % 100 + 1;                      

PROGRAM

/* Program to make user guess a number and comparing it with randomly generated number */

#include <iostream>
#include <stdlib.h>

using namespace std;

int main()
{
        int count=0,rno,num;

        rno = rand()%10 + 1;

        do
        {

                cout<<"\nENTER A NUMBER BETWEEN 1 TO 10: ";
                cin>>num;

                if(num==rno)
                {
                          cout<<"\nBINGO!";
                }
                else if(num<rno)
                {
                          cout<<"\nRAISE YOUR NUMBER!";
                }
                else
                {
                          cout<<"\nLOW YOUR NUMBER!";
                }

                count++;

         } while(num!=rno);

          cout<<"\nYOUR SCORE IS "<<count;

           return 0;
}

OUTPUT

C++ Program to generate random number with output

C++ Program to sum elements passed through Command Line Arguments [DEVCPP/GCC]

COMMAND LINE ARGUMENTS

Command Line Arguments are optional string type arguments which can be passed to the program by the Operating System when it is launched.

The full declaration of main is

int main( int argc, char *argv[])

Here, argc refers to Argument Count which contains the number of arguments passed to the main function including a parameter as path of the program. argv is an array of character pointers which contains the arguments. The first argument argv[0] contains the path of program.

To pass Command Line Arguments in DevC++, you need to do the following:

C++ Program to sum elements passed through Command Line Arguments
                         

                           C++ Program to sum elements passed through Command Line Arguments

PROGRAM

//Program to sum elements passed through Command Line Arguments

#include <iostream>
#include <stdlib.h>

using namespace std;

int main(int argc, char *argv[])
{
        int i,sum=0;

        cout<<"\nARGUMENT COUNT: "<<argc;
        cout<<"\nARGUMENT VALUES: ";

        for(i=0;i<argc;i++)
        {
                cout<<" "<<argv[i];
                if(i!=0)
                {
                           sum=sum+atoi(argv[i]);
                }
        }

        cout<<"\nSUM OF THE ELEMENTS: "<<sum;

        return 0;
}

OUTPUT

C++ Program to sum elements passed through Command Line Arguments with output

C++ Program to illustrate reference variable [DEVCPP/GCC]


REFERENCE VARIABLE

C++ allows to create a reference to an existing variable. It provides a new name to an existing variable. Once a reference is created for a variable, either the variable name or reference name can be used to refer the variable.

The reference variable internally works as an constant pointer i.e. Once a reference is created for a variable, then it can't be changed. It is dereferenced internally without the use of dereferencing operator(*).

PROGRAM

// Program to illustrate reference variable

#include <iostream>

using namespace std;

int main()
{
       int num;

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

int &RefToNum = num;

// RefToNum is a reference variable referring to num

       cout<<"\nVALUE OF NUM: "<<num;
       cout<<"\nVALUE OF REFERENCE TO NUM: "<<RefToNum;

       cout<<"\n\nSQUARING NUM...";

       num = num*num;

       cout<<"\n\nVALUE OF NUM: "<<num;
       cout<<"\nVALUE OF REFERENCE TO NUM: "<<RefToNum;

/* Both variable results in the same value as
they are operating on the same memory location */

       return 0;
}

OUTPUT

C++ Program to illustrate reference variable with output

C++ Program to illustrate reference variable


C++ Program to calculate factorial of a given number [DEVCPP/GCC]

STEPS

1. Initialize variable fact with 1.
                  fact = 1;

2. Multiply fact with the given number.
                 fact = fact * num;

3. Decrement number by 1.
                    num-- ;

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

PROGRAM

//Program to calculate factorial of a given number

#include <iostream>

using namespace std;

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

        cout<<"ENTER THE NUMBER: ";
        cin>>n;

        while(n!=0)
        {
                fact=fact*n;
                n--;
        }

        cout<<"FACTORIAL IS: "<<fact;
        return 0;
}

OUTPUT

C++ Program to calculate factorial of a given number with output

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

STRONG NUMBER

A number is said to be a strong number if the sum of factorial of its individual digits is equal to the number itself.

eg. 145 = 1! + 4! + 5!
             = 1 + 24 + 120
             = 145

PROGRAM

//Program to check whether given number is Strong number or not

#include <iostream>

using namespace std;

int factorial(int n)
{
         int fact=1;

         while(n>0)
        {
                fact=fact*n;
                n--;
         }

         return fact;
}

int main()
{
        int num,numc,digit,sum=0;

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

        numc=num;

        while(numc>0)
        {
                digit=numc%10;
                sum=sum+factorial(digit);
                numc=numc/10;
        }

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

         return 0;
}

OUTPUT

C++ Program to check whether given number is Strong number or not with output

C++ Program to calculate and print the roots of a quadratic equation [DEVCPP/GCC]

PROGRAM

//Program to calculate and print the roots of a quadratic equation!

#include<iostream>
#include<math.h>

using namespace std;

int main()
{
float a,b,c, delta,root1,root2;

cout<<"ENTER three numbers a, b and c of ax^2+bx+c:\n";
cin>>a>>b>>c;

if(!a)
cout<<"VALUE CANNOT BE ZERO"<<"\nABORTING!!!...\n";
else
{
delta= (b*b) - (4 * a * c);

if(delta>0)
{
root1= (-b + sqrt(delta))/(2*a);
root2= (-b - sqrt(delta))/(2*a);
cout<<"ROOTS ARE REAL AND UNEQUAL:\n";
cout<<"Root1="<<root1;
cout<<"\nRoot2="<<root2;
}
else if(delta==0)
{
root1= -b/(2*a);
cout<<"ROOTS ARE REAL AND EQUAL:\n";
cout<<"Root1="<<root1;
cout<<"Root2="<<root1;
}
else
{
cout<<"ROOTS ARE COMPLEX AND IMAGINARY \n";
}
}
return 0;
}

OUTPUT

C++ Program to calculate and print the roots of a quadratic equation with output

FIND US ON FACEBOOK!