Wednesday, 13 November 2013

C++ Program to calculate area of a triangle!

Nothing much to explain! Here we assume the user has any one of these two information:

  1. He knows all three sides, but doesn't know which side is base or which one is height.
  2. He knows the base and the height.
In the first case we use Heron's Formula :




And in the second, we use the familiar method : 


Here is the code:
#include<iostream.h>
#include<conio.h>
#include<math.h>
int Heron(int a, int b, int c);
int Normal(int b, int h);
int main()
{
    int choice;
    float first, second, third, base, height;
    cout<<"Select your choice : "<<endl;
    cout<<"1. You have three sides of the triangle, but are not sure which one is base or which one is height"<<endl;
    cout<<"2. You have two sides, one base and one height"<<endl;
    cin>>choice;
    switch(choice)
    {
       case 1:
          cout << "Enter the sides : " << endl;
          cin >> first >> second >> third;
          cout<<"\nArea is "<<Heron(first, second, third);
          break;
       case 2:
          cout<<"Enter the base : ";
          cin>>base;
          cout<<"Enter the height : ";
          cin>>height;
          cout<<"\nArea is "<<Normal(base, height);
          break;
       default:
          cout<<"\nInvalid choice!\n";

    }
    return 0;
}

int Heron(int a, int b, int c)
{
    float s = ((a + b + c) / 2);
    float area = sqrt( s * (s - a) * (s - b) * (s - c));
    cout << "Area is " << area << " Sq. Units";
    return area;
}

int Normal(int b, int h)
{
    float area = .5 * b * h;
    cout<<"Area is " << area << " Sq. Units"; 
    return area;
}


For newer IDEs, visit this page.

The special thing about this program is that we use the math library by including the header "math.h". Notice how we used the sqrt() function for the square root of the expression. 

Outputs on both options are :



That is all for today, folks!

Monday, 11 November 2013

How to repeat a program till the user wants to end it!

Here I am making a simple program-plug-in (as I call it) to execute the program more than once, if the user wants it. The task is to ask the user if he/she wants to execute the program again after one run. 

Suppose I have a program to find the factorial of a number. 
#include<iostream.h>
#include<conio.h>

long Factorial(long n)
{
     if(n==1){return 1;}
     else{return (n*Factorial(n-1));}
}

int main()
{
     long x;
     cout<<"Enter the number you want to find the factorial of : ";
     cin>>x;
     cout<<x<<"! = "<<Factorial(x)<<endl;
     return 0;
}

After one run, program automatically terminates and If I want to run it again, I will have to open it again. To solve this there are many methods. Im gonna show you two of them. 


  • Solution 1 - The viable one
                  We could use the old school 'GOTO' statement here. Just go ahead and include a label at the beginning of the program execution, and at the end of a run, ask if the user wants to run the program again, by a character choice,and if he says yes, just add a 'goto' statement there.
Syntax:                      label_name:
                                                        (program)
                                              
                                             goto label 


Here is the modified code after inclusion of goto:
#include<iostream.h>
#include<conio.h>

long Factorial(long n)
{
     if(n==1){return 1;}
     else{return (n*Factorial(n-1));}
}

int main()
{
     START:
     long x;
     char choice;
     cout<<"Enter the number you want to find the factorial of : ";
     cin>>x;
     cout<<x<<"! = "<<Factorial(x)<<endl;
     cout<<"Do you want to go again? [y/n] : ";
     cin>>choice;
     if (choice == 'y')
     {
         goto START;
     } 
 return 0;
}


This is a perfectly viable solution and no one cant say that it wont work. But, goto statement is considered harmful by many people since it breaks the beauty of structured programming. You can use it, of course, but there is also a generally preferred alternative for 'goto' statement - the iterators!

  • Solution 2 - The recommended one
                   The generally recommended alternative for using 'goto' is to use loops like do-while. In this case we are putting the whole program inside a giant do-while loop. We use it here because of its exit-controlled behavior. After each run, we keep asking the user if he/she wants to go again, and as long as the user says yes, the do-while loop keeps iterating again and again. 
Syntax:                   do{
                                                program_statements;

                                             }while(statement);

Here is the program code after the inclusion of do-while loop:
#include<iostream.h>
#include<conio.h>

long Factorial(long n)
{
    if(n==1){return 1;}
    else{return (n*Factorial(n-1));}
}

int main()
{
    char choice;
    long x;
    do
    {
       cout<<"Enter the number you want to find the factorial of : ";
       cin>>x;
       cout<<x<<"! = "<<Factorial(x)<<endl;
       cout<<"Do you want to go again? [y/n]"<<endl;
       cin>>choice; 
    }while ( choice!='n'&&choice=='y' && choice=='Y');
}
 

Keep in mind that the loop always comes inside the main() function whether or not the program has external classes or functions. Also remember that we may use any loop instead of do-while.


That's all for today, folks! Happy Coding!!!

Friday, 8 November 2013

Number of characters in a string - C++ Program Source Code!

This program is to count the number of spaces in an input string.

Here is the code:
#include<iostream.h>
#include<conio.h>

void main()
{

int spaces, i;
char str[100];
int spaces = 0;

cout<<"Enter the string!"<<endl;
cin.getline(str, 100);
cout<<"Entered string is \'"<<str<<"\'"<<endl;

for(i=0;i<=100;i++)
{
 if (str[i] == ' ')
 {
  spaces = spaces + 1;
 }
}
cout<<"There are "<<spaces<<" spaces in the given string!"<<endl;
}

For newer IDEs (like Dev C++):
#include<iostream>
using namespace std;
void main()
{
   int spaces, i;
   char str[100];
   int spaces = 0;
   cout<<"Enter the string!"<<endl;
   cin.getline(str, 100);
   cout<<"Entered string is \'"<<str<<"\'"<<endl;
   for(i=0;i<=100;i++)
   {
      if (str[i] == ' ')
      {
         spaces = spaces + 1;
      }
   }
   cout<<"There are "<<spaces<<" spaces in the given string!"<<endl;
   return 0;
}


Working:
Here we use the concept 'String, basically is an array!'. First we input the string str. Let spaces be the number of spaces in the string. Initially it is set to 0. We are going to loop through the string (array), and if any of the element in that array is found to be ' ', or a space, spaces is incremented by 1. By the end, the spaces is going to be the total number of spaces in the string. 

Wednesday, 6 November 2013

C++ Program to reverse a number!

In this post, I'm gonna share you the program, to reverse an input number. i.e., if the input is 1234, the output should be 4321.

Here is the code:
#include<iostream.h>
#include<conio.h>

void Reverse(int num)
{
   int temp, rev_num=0;
   while(num!=0)
   {
      temp = num%10;
      rev_num = (rev_num*10) + temp;
      num = num/10;
   }
   cout<<"Reversed number is "<<rev_num;
}

void main()
{
    int number;
    cout<<"Enter the number to be reversed : ";
    cin>>number;
    Reverse(number);
    getch();
}

For newer IDEs, visit this page.
Working

In this program, I have used a function just to reverse the number, with the number num to be reversed as the parameter. I have also initialized two variables, temp, a temporary variable, and rev_num, the reversed number. As you can see, reversed number is initially set to 0. Suppose the number input (from the main) is 321. 
  1. temporary variable is changed to num%10. So, temp = 321%10 = 1.
  2. Then reversed number is changed to rev_num = (rev_num*10) + temp. As we have set, rev_num is 0 at first. So, rev_num now becomes, (0*10) + 1 = 1. Now the program has found out the resultant first term i.e., 1.
  3. Now num is changed to num/10 = 321/10 = 32.1 . But num is an integer and cannot have a decimal value. So num is automatically converted by the compiler to an integer, i.e., 32 (it just removes the decimal number). 
  4. Since num != 0, the loop is again processed. On this iteration, temp becomes 2. rev_num becomes (rev_num*10) + temp = (1*10) + 2  = 12. So the second digit is 2. num has now become 3.
  5. Since num != 0, the loop is again processed. On this iteration, temp becomes 3. rev_num becomes (rev_num*10) + temp = (12*10) + 3  = 123. So the third digit is 2. 
  6. Now, num = num/10 = 3/10 = .3 . .3 is not an integer and hence it is converted to 0. Now that num has become 0, the loop is terminated. 
  7. Final result turns out to be 123, and the function outputs it.
This program has significance in many other programs. For example, it can be used in the program to check if an input number is palindrome or not (which I will be posting soon). 

That's all for now, folks.

Tuesday, 5 November 2013

Sum of n numbers in C++ using Classes!

"Find the sum of n numbers input by the user using classes in C++"
This is an important question which has high probability to be asked in CBSE/Other states Computer Science practical examinations. This question is also important because it uses most of the basic concepts of C++ like iteration, arrays, classes, etc; Hence I have decided to share this program with you. It is fairly simple if you have a little logic and also know about classes in C++.

Here is the code :
/*Support us by subscribing, commenting, and viewing 
the blog frequently! -GeekyCircle Admin :)*/
#include<iostream.h>
#include<conio.h>
class sumNumbers
{
    int counter,num_of_num,num_array[100], sum;
public:
    void input()
    {
       cout<<"How many numbers?    :     ";
       cin>>num_of_num;
       cout<<"\nEnter the numbers : "<<endl;
       //Part one
       for (counter = 0; counter < num_of_num; counter++)
       {
          cin>>num_array[counter];
       }
       cout<<"\nThe numbers given are : "<<endl;
       for (counter = 0; counter < num_of_num; counter++)
       {
          cout<<num_array[counter]<<"\t";
       }
    }
    void process()
    {
        //Part two - This is where the magic happens!
        sum = 0;
        for(counter = 0; counter < num_of_num; counter++)
        {
           sum = sum + num_array[counter];
        }
    }
    void output()
    {
        cout<<"\n\nRequired sum is "<<sum<<endl;
    }
};

void main()
{
      //Part Three
      sumNumbers object;
      object.input();
      object.process();
      object.output();
      getch();
}


For newer IDEs, visit this page.
Working

Let us assume that user wants the sum of seven numbers from 1 to 7 (1, 2, 3, 4, 5, 6, 7)
Remember that 1 does not have the position [1], but [0] as in any array.

Graphical representation of the example array

  1. Part One
  • First the number of numbers to be added is asked. It is identified by the variable 'num_of_num'
  • Now we ask to enter the numbers. These numbers are assigned to an array, in this case, 'num_array'
    This array is input using a for loop. The input numbers are showed to the user using another for loop.
  • The numbers, 1, 2, 3, 4, 5, 6, 7 are now in an array.
    2.  Part Two
  •  A variable 'sum' is initialized and is assigned a value 0. And counter is initially at 0.
  • num_array[0] is 1. Hence sum becomes sum + num_array[0] = 0 + 1 = 1
  • counter is incremented to 1. num_array[1] is 2. Hence sum becomes sum (which is now 1)  + num_array[1] = 1 + 2 = 3.
  • This process is continued till counter  since we have the expression counter <  n. The last step is :
    sum = sum + num_array[6]  = 21 + 7 = 28
  • loop is then terminated and the final value of sum is 28. So the program outputs 28.
   3.  Part Three
  • Nothing much here... Just the main function. An object of the class sumNumbers, is declared, with a name 'object'. 
  • All the member functions, input, process and output are called!

That's it for now guys... Please continue to support us. Later...


Fibonacci Series!

If you are a Math enthusiast, I'm sure that you have heard about the mighty and mysterious Fibonacci Series. It is as difficult as understanding it, to understand its implementation in a programming language. But the program is surprisingly simple! I'm not going to explain the working, because, it is complicated. But if you have a good logical quotient, you can understand it with ease. Such a program is one of a kind. So just keep at it to understand it!

Here is the code
/*Support us by subscribing, commenting, and viewing<br> the blog frequently! -GeekyCircle Admin :)*/

#include<iostream.h>
#include<conio.h>
void main()
{
    long int first_no = 0, sec_no = 1, counter, next_term, no_of_terms;
    cout<<"Enter the number of terms you want : ";
    cin>>no_of_terms;
    cout<<"\nRequired series is : "<<endl;
    for(counter = 0; counter < no_of_terms; counter++)
    {
       if(counter<=1)
       {
          next_term = counter;
       }
       else
       {
          next_term = first_no + sec_no;
          first_no = sec_no;
          sec_no = next_term;
       }
       cout<<next_term<<"\t";
   }
getch();
}


For newer IDEs, visit this page.

Friday, 1 November 2013

Dates!

Q : Why do programmers always confuse between Halloween and Christmas?
A : Because Oct 31 == Dec 25 !

For those who didn't get : This joke is funny because value of 31 in Octal number system (base is 8) is equal to that of 25 in Decimal number system (base is 10). XD

Go To!

A programmer said "go to hell". The worst part of it was the "go to"!

For those who didn't get the joke : Go to is a control-transfer statement, which is often considered as a bad programming practice. I'll post an article on this soon... :)

Swapping Values of Two Variables - C++ Source Code

This is a very simple program to swap values of two numbers and output.

Code

/*Support us by subscribing, commenting, and viewing the 
blog frequently! - GeekyCircle Admin :)*/
#include<iostream.h>
#include<conio.h>

void main()
{
    int x,y,t;
    cout<<"Enter first number (x) : ";
    cin>>x;
    cout<<"\nEnter second number (y) : ";
    cin>>y;
   
    t = x;
    x = y;
    y = t;

    cout<<"Value of x now is "<<x<<endl;
    cout<<"Value of y now is "<<y<<endl;

    getch();
}


For newer IDEs, visit this page.
Working

After inputting the numbers, the value of x is assigned to a temporary variable t. Now value of x is assigned to y and value of y is replaced by the value of the temporary variable t. Effectively, value of y is transferred to x and x's value to y.
Graphical representation


Thursday, 31 October 2013

Program to find factorial of a number using Recursion

Recursion is one of the most awesome properties in the world of programming. It is used in many cases, but the most basic use of recursion is to find the factorial of a given number. There are many other ways to find the factorial, but the one which uses Recursion is the easiest. Recursion is the property in which a function calls itself inside its own body. This may be a hard to understand till you read the example.

Facorial : Consider an integer n. Factorial of n is denoted as n! and is found out by multiplying all numbers from 1 to n.
e.g.,
      1! = 1
      3! = 3 x 2 x 1  = 6
      5! = 5 x 4 x 3 x 2 x 1 = 120
    10! = 10 x 9 x 8 x 7 x 6 x 5 x 4 x 3 x 2 x 1 = 3628800

Here is the code :
#include<iostream.h>
long Factorial(long a)
{
   if(a>1)
   {
       return (a*Factorial(a-1));
   }
   else
   {
       return 1;
   }
}
int main()
{
   long number;
   cout<<"Enter the number : ";
   cin>>number;
   cout<<endl<<number<<"! = "<<Factorial(number)<<endl;
   return 0;
}

For newer IDEs, visit this page.
Working

  • Suppose the input number is 1. The program outputs 1! = 1 since we have written an else statement specifically when the input is 1. 
  • Suppose the input number is 4. Upon function calling, the variable in which 4 is stored, number, is changed to the variable we have in the function definition, i.e., a. Since 4>1, the if statement is activated.
    The function returns 4 x (Factorial(4-1)), which is equal to 4 x (Factorial (3)) which is equal to 4 x Factorial ( 3 x Factorial (2)) and so on. This continues till 4 becomes decremented to 1. So the final expression is 4 x 3 x 2 x 1. Hence the output is 4! = 24. Since the function Factorial is again called inside the function Factorial, the function is said to undergo Recursion.

FUN FACT : If you search 'Recursion' on Google, it will say
Did you mean: Recursion?
(Try it out for yourself!) If you understand the joke, Kudos, because, you have understood recursion!

Wednesday, 30 October 2013

C++ Program to check whether an year is 'Leap Year or Not'


In this program we will check whether an input year is a leap year or not!

The basic rules a leap year should follow are:

  • A year is a leap year if it is divisible by 400.
    e.g., 1600, 2400 etc., ARE leap years while 1700 or 1100 ARE NOT!
  • If an year is neither divisible by 400 nor by 100, then it IS a leap year, iff it is divisible by 4.
    e.g., 2004, 2016, 1996 etc., ARE leap years while 2007 or 1999 ARE NOT!
Here is the code:
/*Support us by subscribing, commenting, and viewing the 
blog frequently! - GeekyCircle Admin :)*/
#include<iostream.h>
#include<conio.h>
void main()
{
    int year;
    cout<<"Enter the year you want to check : ";
    cin>>year;
    if(((year%4==0)&&(year%100!=0))||(year%400==0))
          cout<<"\nYes! It cerainly looks like a leap year!";
    else
          cout<<"\nMhmmm... Nah... I don't think it is a leap year.";
getch();
}
For newer IDEs (like Dev C++) :
/*Support us by subscribing, commenting, and viewing the 
blog frequently! - GeekyCircle Admin :)*/
#include<iostream>
using namespace std;
int main()
{
    int year;
    cout<<"Enter the year you want to check : ";
    cin>>year;
    if(((year%4==0)&&(year%100!=0))||(year%400==0))
        cout<<"\nYes! It cerainly looks like a leap year!";
    else
        cout<<"\nMhmmm... Nah... I don't think it is a leap year.";
 return 0;
 }
Working

This program is really simple. First we check whether the given year is divisible by 4 and not by 100. If it is, then we will output "it is a leap year". OR we check if it is divisible by 400, and if it is, we will output "it is a leap year. If both the above conditions are false, we output the "year is not a leap year".

Tuesday, 29 October 2013

C++ Program - Conversion from anything to anything!

Here is the source code for a program to convert anything to anything, like Dollar to Euros and viceversa, or maybe Kelvin temperature to Celsius temperature!
What you need is :

  • Correct formula to convert between quantities :
        e.g., To convert from Celsius to Fahrenheit, you must know that F = (9/5 * C) + 32
Here is the program source code :
/*Support us by subscribing, commenting, and viewing the 
blog frequently! - GeekyCircle Admin :)*/
please share our blog to your friends to support us */
#include<iostream.h>
#include<conio.h>

void main()
{
    int op_1,op_2,op_3,op_4;
    float lbs,kg,faren, cel, dol, eur;

    cout<<"Choose any :"<<endl;
    cout<<"1. Kilogram and pound"<<endl;
    cout<<"2. Farenheit and celcius"<<endl;
    cout<<"3. Dollars to Euros (Current exchange rates applicable)"<<endl;

    cin>>op_1;

    switch(op_1)
    {
        case 1:
           cout<<"Press 1 for Kilogram to pound and 2 for pound to kilogram"<<endl;
           cin>>op_2;
       switch(op_2)
       {
           case 1:
               cout<<"Enter the weight in kg"<<endl;
               cin>>kg;
               lbs = 2.204*kg;
               cout<<kg<<" kg = "<<lbs<<" pounds"<<endl;
               break;
           case 2:
               cout<<"Enter weight in pounds"<<endl;
               cin>>lbs;
               kg = .45*lbs;
               cout<<lbs<<" pounds = "<<kg<<" kg"<<endl;
               break;
        }
        break;
        case 2:
           cout<<"Press 1 for Farenheit to celsius and 2 for Celsius to farenheit"<<endl;
           cin>>op_3;
           break;
       switch(op_3)
       {
           case 1:
              cout<<"Enter the temperature in farenheit"<<endl;
              cin>>faren;
              cel = .5555*(faren - 32.0);
              cout<<faren<<" F = "<<cel<<" C"<<endl;
              break;
           case 2:
              cout<<"Enter the temperature in celcius"<<endl;
              cin>>cel;
              faren = ((1.8*cel) + 32.0);
              cout<<cel<<" C = "<<faren<<" F"<<endl;
              break;
       }
      break;
    case 3 :
       cout<<"Press 1 for Dollars to Euros and 2 for Euros to Dollars"<<endl;
       cin>>op_4;
      switch(op_4)
       {
        case 1:
            cout<<"Enter currency in Dollars"<<endl;
            cin>>dol;
            eur = .73 * dol;
            cout<<dol<<" USD = "<<eur<<" EUROS"<<endl;
            break;
        case 2:
            cout<<"Enter currency in Euros"<<endl;
            cin>>eur;
            dol= 1.38 * eur;
            cout<<eur<<" EUROS = "<<dol<<" USD"<<endl;
            break;
       }
      break;
    default :
        cout<<"Invalid choice! Try again!!!"<<endl;
    }
cout<<"Thanks for using the program!!!"<<endl;
}
For newer IDEs (like Dev C++):
/*Support us by subscribing, commenting, and viewing the 
blog frequently! - GeekyCircle Admin :)*/
please share our blog to your friends to support us */
#include<iostream>
using namespace std;
 
int main()
{
    int op_1,op_2,op_3,op_4;
    float lbs,kg,faren, cel, dol, eur;
 
    cout<<"Choose any :"<<endl;
    cout<<"1. Kilogram and pound"<<endl;
    cout<<"2. Farenheit and celcius"<<endl;
    cout<<"3. Dollars to Euros (Current exchange rates applicable)"<<endl;
 
    cin>>op_1;
 
    switch(op_1)
       {
      case 1 :
         cout<<"Press 1 for Kilogram to pound and 2 for pound to kilogram"<<endl;
         cin>>op_2;
     switch(op_2)
       {
         case 1:
            cout<<"Enter the weight in kg"<<endl;
            cin>>kg;
            lbs = 2.204*kg;
            cout<<kg<<" kg = "<<lbs<<" pounds"<<endl;
            break;
         case 2:
            cout<<"Enter weight in pounds"<<endl;
            cin>>lbs;
            kg = .45*lbs;
            cout<<lbs<<" pounds = "<<kg<<" kg"<<endl;
            break;
       }
       break;
    case 2 :
       cout<<"Press 1 for Farenheit to celsius and 2 for Celsius to farenheit"<<endl;
       cin>>op_3;
      switch(op_3)
       {
        case 1:
            cout<<"Enter the temperature in farenheit"<<endl;
            cin>>faren;
            cel = .5555*(faren - 32.0);
            cout<<faren<<" F = "<<cel<<" C"<<endl;
            break;
        case 2:
            cout<<"Enter the temperature in celcius"<<endl;
            cin>>cel;
            faren = ((1.8*cel) + 32.0);
            cout<<cel<<" C = "<<faren<<" F"<<endl;
            break;
       }
       break;
    case 3 :
        cout<<"Press 1 for Dollars to Euros and 2 for Euros to Dollars"<<endl;
        cin>>op_4;
      switch(op_4)
       {
        case 1:
            cout<<"Enter currency in Dollars"<<endl;
            cin>>dol;
            eur = .73 * dol;
            cout<<dol<<" USD = "<<eur<<" EUROS"<<endl;
            break;
        case 2:
            cout<<"Enter currency in Euros"<<endl;
            cin>>eur;
            dol= 1.38 * eur;
            cout<<eur<<" EUROS = "<<dol<<" USD"<<endl;
            break;
       }
       break;
    default :
       cout<<"Invalid choice! Try again!!!"<<endl;
   }
   cout<<"Thanks for using the program!!!"<<endl;
 return 0;
}
Working

There ain't much to say about the working of this program. It looks huge and confusing, but it really is not! The program is a little bit large since I used nested switch statements (i.e., switch inside body of another switch). But if you look carefully, you will understand that the program is really simple and if I had used, if-else-if statements, the program would have become more complex.


P.S : You may add as many conversions as you want to this program! :)


Sunday, 27 October 2013

Program to print out whether a number given is prime or not

This might be a little difficult to understand, so just be with me...
Let us revise some basic math first.

  • A Prime Number is a number which has no divisors other than 1 and that number itself. e.g.,  2, 5,7, 97 etc.
  • A Composite Number is just opposite to a prime number, which has one or more divisors other than 1 and that number itself. e.g., 4, 8, 9, 27.
In this program we are going to input a number from the user and show whether the number is prime or not prime. Here is the code:

/*Support us by subscribing, commenting, and viewing the 
blog frequently! - GeekyCircle Admin :)*/ #include<iostream.h> #include<conio.h> void main() { int num, i, counter=0; cout<<"Enter the number to be processed : "<<endl; cin>>num; for(i=2;i<=num/2;i++) { if(num%i==0) { counter=counter+1; //Or 'counter++;' break; } } if(counter==0) { cout<<"The number is a prime number"<<endl; } else { cout<<"The number is not a prime number"<<endl; } getch(); }

For newer IDEs (like Dev C++) :
/*Support us by subscribing, commenting, and viewing the 
blog frequently! - GeekyCircle Admin :)*/
#include<iostream>
using namespace std;
int main()
{
    int num, i, counter=0;
    cout<<"Enter the number to be processed : "<<endl;
    cin>>num;
    for(i=2;i<=num/2;i++)
    {
       if(num%i==0)
       {
           counter=counter+1; //Or 'counter++;'
           break;
       }
    }
    if(counter==0)
    {
        cout<<"The number is a prime number"<<endl;
    }
    else
    {
        cout<<"The number is not a prime number"<<endl;
    }
 return 0;
}
Working of the program

So basically what happens in the loop is :

  1.  i is initially 2. The loop checks if the remainder of the division num/i is 0. If it is 0, then a counter set at 0 becomes 1. i is incremented one be one to num/2. This is because, we need not check if, any number greater than the half of the input number is the factor of the input number (from basic math). 
  2. If the counter is more than 1 (i.e., at some point, i becomes a perfect divisor of the input number i.e., number is not prime), we output "The number is not prime" and the loop breaks. If the counter is 0 at the end of the loop(i.e., There is no umber that is the perfect divisor of the input number i.e., the number is prime) we output "The number is prime"
Let us consider two examples:

Suppose input number is 8.
  • Initially i is 2. 8%2 is 0. counter is incremented from 0 to 1 and the loop breaks since 8%2 is 0
  • Since counter is 1, output is "The number is prime".
Suppose the input number is 7. 
  • Initially i is at 2. First 7%2 is found out. 7%2 = 1. Loop continues since remainder is not 0.
  • i is incremented by 1. i is now 3. 7%3 is also 1. Loop breaks here since the next integer after 3 is 4 which is greater than half of 7. 
  • At the end counter is still 0. So the output is "The number is prime".

Odd or Even - C++ Program Sourcecode!

Here is the C++ program to find out whether a give number is odd or even :

/*Please support me by commenting and subscribing and viewing 
my blog frequently! - GeekyCircle Admin */
#include<iostream.h>
#include<conio.h>
void main()
{
    int num; cout<<"Enter the number to be processed : "<<endl;
    cin>>num;
    if(num%2==0)
    {
       cout<<"The number is even!";
    }
    else if(num%2==1)
    {
       cout<<"The number is odd!";
    }
getch();
}
For newer IDEs (like Dev C++) :
/*Please support me by commenting and subscribing and viewing 
my blog frequently! - GeekyCircle Admin */
#include<iostream>
using namespace std;
int main()
{
   int num; cout<<"Enter the number to be processed : "<<endl;
   cin>>num;
   if(num%2==0)
   {
       cout<<"The number is even!";
   }
   else if(num%2==1)
   {
       cout<<"The number is odd!";
   }
return 0;
}
Here is the video tutorial of this program :

The program works on the simple logic that the remainder of an even number when divided by 2 is 0 and that of an odd number is 1. 




You might also like