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


You might also like