Tuesday, May 23, 2017

Get Started with C++ with these simple programs

[Programming in C++ ; Image source: edX.org ]

We'll  jump into C++ programming with this simple example code. Read this whole post to understand parts of the code and what it signifies.

WAP to enter any two numbers and print the sum
  #include <iostream.h>
    #inlcude <conio.h>
     
    void main(){
     clrscr();
     int number1, number2, sum;
     // to print sum of two numbers
     cout<<"Enter any two numbers"<<endl;
     cin>>number1;
     cin>>number2;
     sum = number1 + number2;
     cout<<"The sum is:"<<sum;
     getch();
    }
 


We'll now discuss parts of the code snippet, given above, by breaking down what each of the segments mean.

Header Files

 #include <iostream.h>
   #include <conio.h>
    
   void main(){
    clrscr();
    int number1, number2, sum;
    // to print sum of two numbers
    cout<<"Enter any two numbers"<<endl;
    cin>>number1;
    cin>>number2;
    sum = number1 + number2;
    cout<<"The sum is:"<<sum;
    getch();
   }
 
The highlighted segments, line-1 and line-2, in the snippet above are called the header files. They are also known by other names such as: Library files, Library information, header tags etc. These tags are identified in a snippet by the preceeding #include directive. #Include is a pre-processor directive in C++. This means, when this code block is run, the #include directive is asking the C++ compiler to process the files inside angular brackets(< and >) before any other part of the code. This is relevant and EXTREMELY important while programming in C++ because they define how the command works. Without them, the C++ compiler wouldn't have any idea how to execute a command. Say, for example,
 cin>>number2;
 
would not know how to take input without the header file iostream.h.

All header files are unique and they define what commands can be run. It is important to know the header file that each command is associated to, before you can begin programming in C++. For example, iostream.h is associated with all forms of input-output commands such as cout and cin and more. Similarly, conio.h defines how getch() should execute, to the compiler. In simple terms, you should understand that without header files, all of everything you write in your c++ code is useless because the C++ compiler won't know what to do with it. It'll have been undefined, and treated as text. The compiler will return a syntax-error when you try to run a code without the associated header.

Most probably, when you are using header files like this, you are using a header file that somebody has already written. Hence, the name 'Library Files'. You can also write your own header files that define you very own commands in C++. This is known as User Defined Header Files. All of these other header files, like iostream.h and conio.h have already been defined by someone else. If you are interested to know some more standard list of header files, >>>you can click here<<<.

So thats a very brief jumpstart on header files. You REALLY need to know them before you begin programming. For academic purposes, you'll have to know a few of them. Commonly used ones are: iostream.h, conio.h, string.h, stdlib.h.

Self-learning protip:Nomatter, what you see being used in your program, make a note of it for future references. Try to know which commands are dependent on those header files.


main() function

 #include <iostream.h>
   #include <conio.h>
    
   void main(){
    clrscr();
    int number1, number2, sum;
    // to print sum of two numbers
    cout<<"Enter any two numbers"<<endl;
    cin>>number1;
    cin>>number2;
    sum = number1 + number2;
    cout<<"The sum is:"<<sum;
    getch();
   }
    
 
The lines 4 and 14, highlighted above, denote a main function which is wrapped around some statements. In C++, functions are usually identified by the following syntax:
 datatype function_name(){
    //Some statements
   }
 
datatype , in this case, means the type of data that the function is dealing with. It can be of several types(generally those that you use for variable declaration). So, in the syntax above, you can replace datatype with int, char, String, double, float, etc. different kinds of data-types.

Specific datatypes, such as the ones mentioned earlier, are used when you want the function to return something - Maybe a value or a result. This is really important in object oriented languages, such as C++.

In the above code snippet, however, we can see the dataype void being used. Void is actually not a proper datatype. It is used, popularly, in cases when the function does not need to return anything after being executed. You will notice that some C++ compilers will support void while others will not. This is because there is a much more preferred method than using the void alternative. However, for academic purposes in school, the use of void is accepted.
If you would like to know the alternative method to using void, let me know in the comments or message :)


clrscr() and getch() statements

 #include <iostream.h>
   #include <conio.h>
    
   void main(){
    clrscr();
    int number1, number2, sum;
    // to print sum of two numbers
    cout<<"Enter any two numbers"<<endl;
    cin>>number1;
    cin>>number2;
    sum = number1 + number2;
    cout<<"The sum is:"<<sum;
    getch();
   }
 
Highlighted, in the code snippet above, are lines 5 and 13. On line-5, you'll see a statement:
 clrscr();
 
  • As the name implies, clrscr() is a statement that simply clears the screen.
    Lets look a little deeper into this statement on line-5. With the parenthesis, ( ) , after the name, we can easily identify that clrscr is a function.

    Now, dont get confused! If you remember, I mentioned earlier that functions were identified with the following syntax:
       datatype function_name(){
            //Some statements
           }
       
    That is true, in part. Functions are identified, exactly, by that syntax. The thing to note here, is that, the syntax given above is the function definition syntax. Thats how you define a function in C++. But that is not how you declare a function or use a function. Before we dive into function declaration, let me first tell you how they are used.

  • If I declare a function dollie like this:
       void dollie(){
            //Some statements
           }
            
       
    I would use the function dollie, in my program, in this way:
       void main(){
            dollie();
            //Some statements
           }
            
       
    Did you notice something? Its much like how clrscr() was used, right?
Similarly, On line-13, you'll see a statement:
 getch();
 
  • As you should already know by now, getch() is also a function. Each line of code that instructs the computer is known as a statement. By that definition, getch() is also a statement. When a function is written as a statement, you should know that the function is being used or declared (not defined). Only during function definition, functions are not written as statements. It is pretty confusing, I know. But bear with me, it helps to build a solid foundation to paint a clear picture of the code later on.
  • Now, you must be wondering why I specifically isolated, by highlighting, clrscr() and getch() in the code snippet above. How are clrscr() and getch() related at all? Simple. Both of these functions rely on conio.h header file. Here, take a moment to review on what we learnt about header files earlier.

    When you code in C++, or any programming language, you should keep in mind that functional definitions do not magically appear. Haven't you ever wondered how that clrscr() function actually clears the screen? or how that cout function actually makes text appear on the screen? Well, first of all, its not magic. Its function definition. Every function that you use while programming must be defined somewhere (Even the ones you'll write yourself, later on).

    Like I said earlier, #include is a pre-processor directive. If I were to translate the following code to pain English text, it'd be as follows:

    Code:
       #include <conio.h>
           void main(){
            //Some statements
           }
       
    Code in plain English text: When the IDE(The place where you write code; like Borland C++) speaks to the compiler:
       IDE says to Compiler, "Hey compiler, whats up! 
           Could you run this code for me?".
            
           "Sure", says the C++ Compiler.
            
           IDE says,"Oh yeah, before I forget, could you please
           process the header file conio.h first? I need you to 
           finish processing it before you do anything else"
            
           Compiler replies, "Sure thing, IDE. It'll be a pleasure"
            
            
       
    Okay, now, back to the real world. Why do you think this exchange takes place? Comments or Message :)
    Short Answer: Can you tell me the definition of all of the follwing words, without looking at the dictionary? [1] adumbrate, [2] ambivalent, [3] tenchant, [4] abstraction, [5] encapsulation. You could not, could you? Same is the case for the compiler. The header file is like a dictionary. Without it, the compiler will not know the meaning of the statements or functions inside main()
       //no header file
           void main(){
            /* without the header file,
             compiler will have no idea
             about what to do with the
             statements over here
             Your program will produce
             a syntax error, or an illegal
             definition error indicating
             that the header file is
             mising.
            */
           }
            
            
       


Variable declaration

 #include <iostream.h>
   #include <conio.h>
    
   void main(){
    clrscr();
    int number1, number2, sum;
    // to print sum of two numbers
    cout<<"Enter any two numbers"<<endl;
    cin>>number1;
    cin>>number2;
    sum = number1 + number2;
    cout<<"The sum is:"<<sum;
    getch();
   }
    
 
On line-6, you'll notice that the keyword int is followed by three words after a space, and each separated by comma(,) delimiter, and terminated by semi-colon(;)delimiter. Like the function declaration, that we briefly, talked about earlier, this is a variable declaration.

C++ programming uses an explicit-declaration scheme. This means, if you are programming in C++, you should know what variables you will be using, before you even begin programming. Hence, it is important to make a habit of thinking of the general code in your mind before you begin programming, to estimate the number of variables that will be used. This is a good practice that'll make programming super easy for you. For me, it has always been like writing an essay. It just comes naturally. Following proper practices will allow you to share the same benefit. Programming is not hard; it just needs practice.

  • Lets take the code, above, as an example. We are required to enter any two numbers and then find a sum. To store two numbers, we need two variables. A third variable is then needed to store the result of these two numbers. Hence, on line-6, we've declared 3 variables that we'll be using, like so:
       int number1, number2, sum;
       
    Line-6 tells the compiler that our program needs 3 variables. This allows the compiler to reserve the necessary memory(via physical memory allocation) so that the program can execute properly.

    As you can see by now, programming is all about defining things in proper order, in proper place and then instructing the compiler with lines of statements. Its quite simple. In that light, missing any of these steps will produce error. So when you're writing for an exam, think about how the compiler would see your code. Would it find everything it needs? Thats the key to write 100% correct code every-single-time in examinations. Think like a compiler.


Comments

 #include <iostream.h>
   #include <conio.h>
    
   void main(){
    clrscr();
    int number1, number2, sum;
    // to print sum of two numbers
    cout<<"Enter any two numbers"<<endl;
    cin>>number1;
    cin>>number2;
    sum = number1 + number2;
    cout<<"The sum is:"<<sum;
    getch();
   }
    
 
On line-7, you will see plain English text that seems to be out of place amongst all that code surrounding it. Those are comments. Comments essentially tell the compiler to ignore it while compiling. So when the compiler reaches line-7 during compilation of our code, it will simply disregard it if it finds out that it is a comment. Comments are indicated by a preceeding // symbol or /* ... */ in C++

Example: You can identify comments in the following way:
  • Single Line Comments:
       #include <conio.h>
            
           void main(){
            //single line comments are written like this
           }
       
  • Multiple Line Comments:
       #include <conio.h>
            
           void main(){
            /* multi-line comments are
             written this way
            */
           }
       
    Imagine you have thousands of lines of code. In that case, you would not have to comment each line with //, you could simply use the multi-line comment approach to comment any number of lines by just wrapping the statements in /* ... */
  • Why are comments important?
    When you are programming in the real world, you'll not be the ONLY one writing code for a program. There can be thousands and millions lines of code across many team-members. To effectively communicate what a piece of code does, comments can be helpful. Comments are also helpful if you want to look back at your own code after many years. It'll be like a note to yourself.
    Example:
        #include <conio.h>
              
             void main(){
              /* the function below 
               will display the age 
               of siddhant if you pass 
               his year of birth
              */
              siddhant(1995);
             }
              
              
        


cout keyword

 #include <iostream.h>
   #include <conio.h>
    
   void main(){
    clrscr();
    int number1, number2, sum;
    // to print sum of two numbers
    cout<<"Enter any two numbers"<<endl;
    cin>>number1;
    cin>>number2;
    sum = number1 + number2;
    cout<<"The sum is:"<<sum;
    getch();
   }
    
 
cout keyword allows the program to print something on thr screen in C++. A keyword is, a word, something that the compiler reserves for special operations or something that has been defined in the header file included during pre-processing. In this case, the cout keyword is associated with the header file iostream.h This means that iostream.h contains all defintions about cout and how it should be used.
  • cout popularly uses 3 delimiters: ( < ) , ( " ) & ( ; ).
  • endl is another keyword that is used in conjunction with cout. It means 'End of line', and it indicates that the position is the end of the line(like a fullstop in English. endl is only used with cout so, don't use it anywhere else.)

    If you do not use the endl keyword, the next statement will print in the same line, on the screen.

    Example:
       //some statements
            cout<<"Line-1";
            cout<<"Line-2"<<endl;
           //some statements
            
        
    would output, without breaking a line, as:
    Line-1Line-2

    Similarly,
       //some statements
            cout<<"Line-1"<<endl;
            cout<<"Line-2"<<endl;
           //some statements
            
        
    would output, breaking a line, as:
    Line-1
    Line-2


cout keyword

 #include <iostream.h>
   #include <conio.h>
    
   void main(){
    clrscr();
    int number1, number2, sum;
    // to print sum of two numbers
    cout<<"Enter any two numbers"<<endl;
    cin>>number1;
    cin>>number2;
    sum = number1 + number2;
    cout<<"The sum is:"<<sum;
    getch();
   }
    
 
Similar to the cout keyword, the cin keyword is also associated with header file iostream.h. It used to perform the input operation. It is important to note that the double greater-than angular bracket(>>) is used for cin while double less-than angular bracket(<<) is used for cout. Imagine the << as a loudspeaker being used by cout, so that you never get confused.

cin is a single line statement. This means, regardless of endl or not, it will always occupy a line. This is why you can only input once per line in a cin statement.


cout keyword

 #include <iostream.h>
   #include <conio.h>
    
   void main(){
    clrscr();
    int number1, number2, sum;
    // to print sum of two numbers
    cout<<"Enter any two numbers"<<endl;
    cin>>number1;
    cin>>number2;
    sum = number1 + number2;
    cout<<"The sum is:"<<sum;
    getch();
   }
    
 
On Line-11, we have finally reached a statement in the code that does not actually need a header file. The C++ compiler supports initiation by default. Initiation is the process of setting a value to a variable for the first time. This can also be done during variable declaration.

In this particular case, of line-11, we can observe an initiation by arithmetic operation. The addition operator (+) is being used to find the sum of two numbers: number1 and number2 that we declared earlier, during variable declaration. The result of the arithmetic operation is then stored in the third variable, sum. If you recall properly, sum was also declared earlier, in the variable declaration process. Declaration is necessary to perform initiation.

Ending with the getch() keyword

 #include <iostream.h>
   #include <conio.h>
    
   void main(){
    clrscr();
    int number1, number2, sum;
    // to print sum of two numbers
    cout<<"Enter any two numbers"<<endl;
    cin>>number1;
    cin>>number2;
    sum = number1 + number2;
    cout<<"The sum is:"<<sum;
    getch();
   }
    
 
This tutorial is coming back to the getch() statement, even though we discussed it earlier, because of is important nature in school level programming. In most schools, the choice of IDE(the place where you write your code in the computer) will be Borland C++. Borland C++ has a standby output console. This means that as soon as the proram is executed, the output screen will disappear. To avoid this, the getch() statement is used. It has no other special function in the code. In the code, it is simply serving to 'pause' the program so that the output screen can be seen.
  • THIS IS NOT NECESSARY IN OTHER COMPILERS
  • This is necessary, however, to write code in examinations. Many school boards still follow the old practice. Better safe than sorry. getch() doesn't affect the code, overall, at all.
Any specific questions?
Don't hesitate to ask. Comment your queries below. Or message me.

>>>Click here to CONTINUE this tutorial with more example code.<<<

0 comments

Post a Comment