Aug 22, 2017

Check given String for Palindrome

Program: Find given string is palindrome or not

Palindrome: palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward, such as madam or racecar.

So in this program we take input string from user and return the result whether its palindrome or not.

#include <iostream>
using namespace std;

int main() {
char str[100]; // declare char variable of length 100 i.e. max 100 character string can be taken input
cin >> str; //take input
int strLength = 0; //initialize the length of string to zero
bool palindrome = true; //let assume given string is palindrome
for(int i=0;str[i]!='\0';i++,strLength++); 
/*
 to understand above statement first remember array of char ends with '\0'. '\0' represents null character. So we can determine the end of string '\0' to calculate the length of string. So here we first initialize the length by 0 then we begin the loop from i =0 and we check character at ith position for null character '\0', so we are increment string length with the value of i. So when we encounter '\0' it means end of string so length is calculate with the value of i. 
*/
for(int i=strLength-1,j=0;j<(strLength/2)+1;i--,j++){
 if(str[i] != str[j]){
  palindrome = false;
  break;
 }
}
/*
 Now to check palindrome we check starting half of string should be match with half from end. For even length it will divide perfect in two parts whereas for odd it will left with one character that we don't need to check as its in middle and common.
Now we declare two counter first denote the position of start of string and other end of string[Remember index start from 0 so here strLength is total length so last Index will be strLength -1 ]. So we run the loop upto half length of string length and we increment j(start counter) and decrement i(end counter).
In each loop pass we check character of ith position and jth position to be same. If they mismatch in any one of the case then we can says given string is not a palindrome. So by default we assume its palindrome if condition doesn't match mean its palindrome.
*/
if(palindrome){ //print the output
cout << "Given String is Palindrome";
}
else{
cout << "Given String is not a Palindrome";
}
return 0;
}





Dec 5, 2016

Program: Print first 10 Perfect Number

Program: Find or Print first 10 Perfect Number

Perfect number is a positive number which sum of all positive divisors excluding that number.
For example: 6 is perfect number as divisor of 6 are 1, 2, 3. Sum of it divisor is 1 + 2 + 3 = 6.

Simple way to do is find divisor of each element and check for perfect number. But it is slow as it take more time.
So there is general way to find perfect number as given in wikipedia, perfect number exist only for even number. It is given by 2p−1(2p − 1) where p is a prime number 
For example for p = 2 : 21(22 − 1) = 6,
similarly for p = 3 : 22(23 − 1) = 28 ...

So in this program we are printing up to 10 perfect number.

#include <iostream>
#include <cmath> //for pow function
using namespace std;

bool isPrime(int n) //check prime number 
{
//this snippet is taken from program: Check given number for Prime Number
 bool flag = true;
 if(n<2)
  flag = false;
 else if(n == 2)
  flag = true;

        else if(n%2 ==0)
              flag = false;
 else{
  for(int i=3;i<n;i+=2){
   if(n%i == 0)
   {
    flag = false;
     break;
   }
  }

 }
       return flag; //return boolean value
}

/*
using above formula we made function which return the perfect number according to given prime number.
*/
unsigned long long getPerfectNumber(int n){ 
    return (pow(2,n-1)*(pow(2,n)-1));
}


int main()
{
    //print for prime number = 2
    cout << getPerfectNumber(2)<<endl;
    for(int i =3,j=1;j<10;i+=2){
        if(isPrime(i)){ //check prime if found then will print perfect number
                cout << getPerfectNumber(i)<<endl;    
j++;
}
    }
  return 0; //https://cplspls.blogspot.com

}

OUTPUT:




For those who want to do by simple way by check each number for perfect number then here is program:-

#include <iostream>
using namespace std;

int main() {
unsigned long long sum;
        int n = 4; //number of perfect number to print
for(int i=2,j=0;j<n;i++){//we start from 2 and start checking each number 
sum = 0;
for(int j=1;j<i;j++){ //find divisor
if(i%j == 0)
sum+=j; //add divisor
}
if(sum == i){ //compare sum with number
cout << sum<<endl;
j++;
}
}
return 0;
}

Above program sure look small as compare to above one but time taken to print 10 elements will take a lot of time and memory while first code will give answer within few seconds.

Dec 1, 2016

Program: Print first n Prime Number

Program: Print first n Prime Number

We earlier done the program of how to check Prime Number, in that program we are checking whether the given number is prime or not.

In this program we are taking input n and printing first n prime number.


Prime number is a number which is greater than one and can only divide by 1 or by its own number.

#include <iostream>
using namespace std;

//we already discuss about how to check prime number so we create a function
bool isPrime(int n) 
{
       //this snippet is taken from program: Check given number for Prime Number
bool flag = true;
if(n<2)
flag = false;
else if(n == 2)
flag = true;

        else if(n%2 ==0)
              flag = false;
else{
for(int i=3;i<n;i+=2){
if(n%i == 0)
{
flag = false;
 break;
}
}

}
       return flag; //return boolean value
}

int main()
{
  int n,i;
  cout << "Enter value of n : ";
  cin >> n; //input n
  if(n>1)
  {
   cout << "2 ";
   n--;
  }
/*
we print first prime number i.e. 2 earlier to increase the speed of program as i discussed earlier in my last program that 2 is only even prime number. Rest of prime number are odd. So we have to print 2 earlier to run loop with increment of two. This way it checks less number of number and increase its speed.
Now loop run till n value drop to zero that each value we print will decrement value of n. So we can print exactly n number only. 
In loop we pick number and check whether it is prime or not from function which return true or false. According to result we print the prime number or not.
*/
  for(i=2;n>0;i+=2)
  {
      if(isPrime(i))
      {
          cout << i << " ";
          n--;
      }
  }
  return 0; // https://cplspls.blogspot.com
}



OUTPUT:

Nov 30, 2016

Introduction to User Defined Functions

Introduction to User Defined Functions

A function is a group of statements that together perform a task. Every C++ program has at least one function, which is main(), and all the most trivial programs can define additional functions.

We have study about #define in previous lessons. Functions is similar to #define but less secure than functions as it doesn't have any return type or data type of parameters which provide certain level of data security.

Functions usually defined because a certain snippet of code are used again and again. So instead of writing again and again we create a Function which stores the required statement to execute and it may return result according to return type.

Functions are used to provide modularity to a program. Creating an application using function makes it easier to understand, edit, check errors etc.

A function is also known as method or a sub-routine or procedure etc.

Syntax of Function

return-type function-name (parameters){
   // function-body
}
A C++ function definition consists of a function header and a function body. Here are all the parts of a function:

  • Return-Type: The return-type is the data type of the value the function returns. return-type can be of any data type or user defined type also. It can be void when we don't have to return anything.
  • Function Name: The function-name is name of function through which we gonna call it. 
  • Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters. Parameters are also known as Function Signature.
  • Function Body: The function body contains a collection of statements that define what the function does.


Function Declaration includes 
return-type function-name (parameters);
Function declaration is similar to function defination just without function body. 

In C++ before calling function we must either define the function or declare the function. If we try to call function from main() and it is defined after the main() method then it will give compile error as compiler doesn't recognize the function as its not defined till now. So we need to tell compiler by declaring earlier or define the function.

Below example contain usage of both defining and declaring the function before main method.

 Example:

#include<iostream>
using namespace std;

void display(int x); //declaring the function 
//define the function
int calculate(int x,int y) //int = data type
//calculate = function-name
//int x, int y = function parameter or signature

   return x+y; //return integer type
}
int main()
{
  int x = calculate(2,5);
  display(x);
  return 0; // https://cplspls.blogspot.com
}
void display(int x) //definition of function which is declared above
{
  cout << x<<endl;
}

OUTPUT:

Program: Check given number for Prime Number

Program: Check given number for Prime Number

We know about prime number is a number which is greater than one and can only divide by 1 or by its own number. In this program we check the given number for prime number.

#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter Prime Number: ";
        cin >> n; //input number
//initialize flag for true assume given number is prime number
bool flag = true; 
//if number is less than 2 than its not a prime number according to def
if(n<2)
flag = false; 
else if(n == 2) // if n is 2 than its prime number
flag = true;
        else if(n%2 ==0)
              flag = false;
else{
/*
   Now we check n > 2 whether its prime or not. We check for 2 earlier because from now on we are gonna skip all even number as other than 2 there are no even prime number as all divisible by 2. So we start with 3 and check up to n with increment of two in one loop. So if any number less than n found divisible with n then set flag to false and break the loop.
*/
for(int i=3;i<n;i+=2){
if(n%i == 0)
{
flag = false;
 break;
}
}
}
//print output according to flag value
if(flag)
cout<<"It is a Prime Number";
else
cout<<"It is Not a Prime Number";
return 0;  //https://cplspls.blogspot.com
}

OUTPUT:


Dec 12, 2015

Use of goto Statement

Using goto Statement

goto statement is used to jump on a particular location in a program defined by label. Label is a name given to a location. 
Label is defined by a <locationName> followed by a colon.
goto is use with goto <labelName>;

syntax of label & goto

statment 1;
label: //syntax of label
statment 2;
statment 3;
if(statement) //if condition true
{
goto label;
//jump to label i.e. after statement 1 and program will execute again statement 2 and 3
}


Let Check out Example for better understanding

Ex1: Print first 10 Natural Number
#include<iostream.h>
int main()
{
    int i=1; 
    print:
    cout << i <<endl; 
    if(i<10) 
    {
        i++; 
        goto print; //jump to print label as define above after initialization of i
    }
/*
In Above Program we are printing first 10 natural number using goto statment
in this example goto is used as loop to print 1 to 10
first we initialize the variable i to 1
then we define a checkpoint or label for using with goto
then we print value of variable i
we check if variable i is less than 10 if true then increment of variable i and jump to checkpoint or label we define earlier to print again this process continue till condition is false similar in a loop
*/
 return 0;
}

OUTPUT




Ex2: Divide Two Numbers [check this program using loop]
#include<iostream.h>
int main()
{
//Divide Two Numbers
    char ch;
    float a,b;
    tryAgain:
    cout << "Enter First Number : ";
    cin >> a; //Input First Number
    cout << "Enter Second Number : ";
    cin >> b; //Input Second Number
    if(b == 0) // Check for divisor for zero
    {
        cout << "Error: Number Cannot Divide by Zero"<<endl; //return error message
        goto tryAgain;
    }
    cout << "Answer = " << a/b<<endl;

    cout << "Try Again(y/n): ";
    if(cin >> ch && ch != 'n') 
        goto tryAgain;

  /*
In this example we are dividing two number and check for divisor not equal to zero
first we define label before taking input from user 
then we take input two numbers 
if (divisor(here b) = 0) then print error message and goto label; that jump back to a point where we have to take input again
now if divisor is not zero then we print answer and ask user for more
here you can see expression in if condition 
if(cin>> ch && ch != 'n')
above if statement has two conditions for check as there is AND(&&) between them means both must be true
check each conditions cin >> ch this will return true when it take input successfully 
and then it compare ch != 'n'
means here we are do two operation that first we take input and check for equality in one statement
second condition will run only when we get input from first statement
so if its true then it goto label; 
else <end of program>
*/
    return 0;
}

Output



Dec 11, 2015

Use of Continue Statement

Using Continue Statement

Continue statement is used to skip the current iteration and force to execute next iteration by skipping any code after continue statement inside a loop.
In simple term whenever you encounter continue statement in a loop it will skip the current pass execute next pass and also it skip the other statement below the continue statement inside a loop.

Let check the following examples for better understanding:

Ex1: Print Odd Number
#include<iostream.h>
int main()
{
//Print odd number
for(int i=1; i<=10;i++)
 {
    if(i%2==0)
    continue;
/*
 Above two lines first line check if i is even or not, If its even then i%2 return zero
means condition is true for even number of i then continue statement will execute.
As you can see in output we are printing only odd numbers so whenever continue statement runs it will skip all next line inside a loop and go to next iteration that increment of i
*/
    cout << i<<endl;
 }
return 0;
}

OUTPUT





Ex2: Divide Two Numbers
#include<iostream.h>
int main()
{
//Divide Two Numbers
char ch;
float a,b;
do //Using Do While Loop
 {
  cout << "Enter First Number : "; 
  cin >> a; //Input First Number
  cout << "Enter Second Number : ";
  cin >> b; //Input Second Number
  if(b == 0) // Check for divisor for zero
   {
    cout << "Error: Number Cannot Divide by Zero"<<endl; //return error message
    continue; 
/*
In this whenever we encounter with divisor = 0 then error message is display
and continue statement will execute. Whenever Continue statement runs it will skip all the code after that inside a loop and start from next iteration. As in this example we are using Do while loop which check condition at the end but we already skip the statements after continue so we will don't check the condition and we will start loop from begin. As you can seen in Output
*/
   }
  cout << "Answer = " << a/b<<endl;
  
  cout << "Try Again(y/n): ";
  cin >> ch; 
 }while(ch != 'n');

 return 0;
}

Output



Follow by Email