Thursday, 11 September 2014

#1 : Bare Basics - Quick C++ Tutorial

How to use an IDE

You can use any IDE (if you are going to use one) out there. The one I prefer is Code::Blocks, which is a free IDE which can compile and run C/C++ programs. Later on, you may use a more sophisticated IDE like Microsoft Visual C++ or Eclipse. Open it up, create a new project, open up 'main.cpp' from the side panel, and get cracking!

First C++ Program

Copy (or type, which is much better) this code into the IDE.
#include <iostream>

int main()
{
    std::cout<<"Hello, world!"<<std::endl;
    return 0;
}

Now click Build -> Build and Run to compile and run the program. If you have copied/typed correctly, you will now see the output now, which will say, "Hello, World!". Congratulations on running your first C++ program.




Now let's break down what is happening.

  • #include <iostream> 'include's or gets the program access to all the things inside the 'library' iostream (which stands for input-output stream). You can think of iostream as a folder, inside which there are certain files that are required to do input/output operations. By 'include'ing the library in your program, the program can access these files.
  • int main() is a function. A function is simply an entity or a block of code that does something. main() function is the most fundamental block of code in your program. As the name indicates, it is the most important function in your program, without which, your program will not run. Since our aim is to output a message to the user, we do this inside the main function. int stands for integer. This is called a return type, indicates that the function which we are working on has something to do with numbers, As per the new standards, every main() function must have a return type int. We will learn to make other functions as per our needs later on. return 0; at the end of the code puts an end to the main function. 
  • std::cout<< is the used to output the message to the screen. Anything that comes after std::cout<< is put to the screen. In this case a string (which is enclosed by two double inverted commas) is output. std::endl puts anything that comes after it, on the next line. Since std::endl is not a string (it is not to be enclosed between two double inverted commas) it requires another <<.
  • As you cans see, most of the lines in this program ends with a semicolon (;). This is to let the compiler know the particular operation is over. Also the all the operations inside the main() function is enclosed by a pair of flower brackets. Everything inside one pair of flower braces is called one block of code. As the programs get more complex number of blocks in your program will increase.
A peek on namespaces

Include a line 'using namespace std;' just below the first line of code. Now you can write just cout<< instead of std::cout<< or just endl instead of std::endl<< in your codes. We will learn why this happens later in the course. Run the modified code given and you will see that the output is exactly the same as the first one

#include <iostream>
using namespace std;

int main()
{
    cout<<"Hello, world!"<<endl;
    return 0;
}

Exercises
  • Remove the semicolon in your code and try running the program. What do you see? 
  • Write your own message in the program.
  • Write the words 'hello' and 'world' in two separate lines using endl.

Saturday, 21 June 2014

C Program to Determine the Sum of Harmonic Series - Source Code

So, as you may know harmonic series implies:


In this program, we take the integer value of n from the user and display the sum of the series according to this value. I just used a for loop, although there are many other ways to do the same.

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

int main()
{
     int n,i;
     float inverse;
     double sum=0.0;
     //Preliminary
     printf(\"Program to find:\\n\");
     printf(\"\\n   1    1    1    1          1\\n\");
     printf(\"  __ + __ + __ + __ + ... + __\\n\");
     printf(\"\\n   1    2    3    4          n\\n\");

     //Prompting for the value for 'n'

     printf(\"\\n\\nEnter the value of n: \");
     scanf(\"%d\", &n);

     //Iterating and summing

     for(i=1; i<=n; i++)
     {
         inverse = (1.0/i);
         sum += inverse;
     }
 
     //Displaying the answer

     printf(\"\\nRequired sum is %f\", sum);
 
     getch();
     return 0; 
}

Here is the output:

Happy Coding!
:)

Wednesday, 4 June 2014

Collatz Conjecture - Implementation in Java

Let's begin with a short intro to Collatz Conjecture*. It's also known in the names (3n+1) conjecture, Hasse's Algorithm, Syracuse problem, and a ton of others I really have a hard time remembering. The problem can be represented as a mathematical function as given below, which is iterated until the value of variable is reduced to 1.


The proposal of Collatz conjecture, is that, no matter what number you start with, you will eventually, at some point, reach 1. We all know that computers are especially good at repeating stuff! For this reason, many mathematicians, and computer scientists rely upon algorithms and computers to test these kind of problems. There is a lot of underlying math to this problem, some of which you can see at Wikipedia, and Wolfram Alpha. I'm not going into the math. Here is the code:


/* Implementation of Collatz Conjecture/ Hasse's Algorithm/ Syracuse Problem in Java using Recursion */
import java.util.Scanner;

public class CollatzConjecture {
    public static void Collatz(int x) {
        System.out.print(x + ", ");
        if (x == 1) {
           return; 
           // If x is 1, then the function is terminated
        } 
        else if (x % 2 == 0) {
           Collatz(x / 2);       
           // If x is even, then function is called with the argument x/2
        } 
        else if (x % 2 != 0) {
           Collatz((3 * x) + 1); 
           // If x is odd, then function is called with the argument 3x+1
        }
    }

    public static void main(String[] args) {
       System.out.print("Collatz Conjecture");
       System.out.print("\nEnter the starting number: ");
       Scanner in = new Scanner(System.in);
       int n = in.nextInt();
       Collatz(n);
       in.close();
   }
}

I have used recursion to carry out the iteration, you may also use any loop of your choice.
Here is a sample output. As you can see, even a number as small as 27 takes 111 steps to reach unity, and it touches a number as large as 9232 on its way!

27 reaches unity, taking 111 steps, touching the maximum 9232 on its way!


Don't jump into conclusions though. Specific numbers, as large as 1024, takes only 10 steps to reach 1. This is because 1024 is the tenth power of 2.

1024 reaches unity faster, because it is a power of 2


From these examples, it is safe to say that the number of steps taken is purely depended upon the nature of the number. Some numbers tend to reach 1 faster, and some takes a larger amount of time. This is the magic of Mathematics!

*Conjecture - An unproved proposition
Happy Coding!
:)

Friday, 30 May 2014

Project Euler : Problem #2 - C++ Solution

This time, the problem is:
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
I'm using a do-while loop here. Here is the code:
#include <iostream>
using namespace std;

int main()
{
    int a = 0, b = 1;
    int c, answer = 0;
    do{
        c = a + b;
        a = b;
        b = c;
        if(b%2==0){answer = answer + b;}
    }while(b<=4000000);
    cout<<"Answer is "<<answer;
    return 0;
}

Thursday, 1 May 2014

Project Euler : Problem #1 - C++ Solution


I was recently wandering around the internet, and I found out this awesome website, with some great mathematical problems which has to be solved using any programming language. You can easily get into the website by searching for "Project Euler" on Google. It has a great set of problems, to sharpen your problem solving skills in any programming languages. Here I'm posting the solution to the first problem. I will try to continue to give more solutions to more problems.

The problem is :

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
First go ahead an try to solve it on your own, and then refer the solution.
The solution to the problem is given below:


#include<iostream>
#include "conio.h";
using namespace std;
int main()
{
    int i;
    int result = 0;
    for(i=0;i<1000;i++)
    {
          if( i%3==0 || i%5==0 )
          {
                result = result + i;
          }    
    }
    cout<<"The answer is "<<result;
    getch();
    return 0;
}

Here is the output:

 :)

Tuesday, 11 March 2014

Signing off... (for a while)

Heyyyyy! Just staying away from the computer for a while (exams...).. Will be back in some days!

Code the world away guys!!!
 :)

Monday, 10 March 2014

Date Calc - Software Free Download!

Here is the software, the source code of which I had posted recently on this blog (here).

You can download the file from these links:

  • As .exe file  -   from here
  • As .rar file   -   from here

    Please give us your feedback by commenting below to keep us motivated!

You might also like