Monday, November 8, 2010


Contents

  1. Introduction
  2. Getting Started With C++
  3. Two Simple Problems
  4. Execution Control: if, but, and while
  5. Functions, Pointers and Arrays

Introduction

This tutorial has been designed to serve students and practising professionals in  science and engineering. The aim is to quickly enable the reader to write/read non trivial C++ applications without really bothering about the theoretical details of language and it's grammar. So we use a large number of examples as we proceed, in order to gently nail in the common features of the core language as well as the standard utility library. An Older Post

Getting Started With C++ 

Begin with what programmers usually call "Hello World " program

//Prog0: Simple yet interesting  !!  
//-------------------------------    

#include<iostream>
int main(){

std::cout<<"Hello World !"<<std::endl;
return 0;http://physicsatpu.blogspot.com/

}
This program is one of the smallest nontrivial  codes which can be written using C++ but inspite of being so it does tell a fortune's worth of language fundamentals. To gauge this, we begin with line by line dissection of the code,
  1. Code:
    //Prog0: Simple yet interesting  !!  
    //-------------------------------    

    The ('//') characters mark the beginning of a comment which extends till the end of line. Comments are ignored by the compiler but they are put in to the programs to ensure the readability and for the ease of debugging.

  2. Code:
    #include<iostream>  

    The C++ houses many of it's features in the standard library rather than making everything a part of what is called  core language. Core language features are always avaialable to the programs but one has to explicitly ask for chunks of standard library that one wants to use. The #include directive here asks for the standard library features
    from iostream. The iostream provide support for the sequential input -output and is enclosed in angular brackets since it referes to a part of standard library called standard header

  3. Code:
    int main()

    Every C++ program must contain exactly one function named main() which the implementation calls in order to run the program. A function is a piece of program that can be called from another part and  is characterised by a "name", "return type" and the "body". Name is for making a function call,
    body is the set of one or more statements enclosed in a set of curly braces ("{" and "}") containing the function implementation, and the return  type inform about the kind of value to be expected as a result of succesful call.

  4. Curly braces:
    {

    The curly braces whereever present in a C++ code tells implementation to treat the enclosed statements a a unit (compound statement). The left brace here marks the beginning of a compound statement which is the body of  main() function.

  5. Code
    std::cout<<"Hello World !"<<std::endl;

    The std::cout is the standard ouput stream used for ordinary output, and ("<<") is the output operator from standard library. The ouput operator here first writes Hello World ! and then std::endl; into the std::cout. The std::endl is another standard library object that ends the current line so that if the program sends some other output, it appears on the next line. The quotes ("") in "Hello World !" tells that this expression is a string literal (more later).

  6. Code
    return 0;
    The return statement wherever encountered, "returns" the value contained between itself and the concluding semi-colon back to the calling program and then ends the execution of the function where it( return statement ) appears. The value returned by a function must be consistent with what it says it will return. Here, int main() tells the implementation to expect a return value of type "int" (C++ keyword to flag the integer data),
    so return 0; returns a value 0, marks the succesfull running of the function, and ends the execution.

  7. Curly brace
    }
     
    Marks the end of the int main(), and thus that of the
    program execution.
Although the program we have written is very simple but already it helped us to walk a lot of the ground in the journery of becoming C++ experts. We learned about the basic program structure, core language and standard library, function definitions and ordinary input-output using string literals. Before we move further it is a good idea for the user to try wrting-compiling-running this program and also try following exercises.

    Exercise Set: 1

  • Write a program which has follwowing output:
    My name is Charlie, but I am not one of the Chaplins !!
  • Write a program to which has follwing formatted output:
             Johnny!! Johnny!!
         Yes, Papa,
         Eating Sugar ?
         No, Papa,
         Telling lie ?
         No, Papa,
         Open Mouth !!
         Ha, Ha, Haah !!!
Next we try to introduce simple calculations using C++. Just as we did in this section, we will follow an illustrated approach i.e  trying to understand the language while discussing the programs.

Two Simple Problems

An engineer or a scientist needs to program for much more than just printing outputs on the screen. So our second set of examples is more realistic. First we try hand at finding the roots of a quadratic equation, and then deal with the problem of finding the area of a circle. Begining with the quadratic equation,
ax2+bx+c=0
The solutions are well known and are given by,
x- = (-b+√(b2-4ac))/(2a) x+ = (-b+√(b2+4ac))/(2a)
Coming to the geometric problem of finding area of circle, it is given by:
Area = π(radius)2
We show the two very simple programs below to find the roots of quadratic equation and area of circle respectively.

//Prog1: A program to find roots of quadratic equation.
//-----------------------------------------------------


#include<iostream>
#include<cmath>
using namespace std;
int main(){

//Define variables to hold coefficients
  
  float a = 0;
  float b = 0;
  float c = 0;

//Ask for and then read the values of a, b and c
  std::cout<<"Enter the values of a, b and c:"<<std::endl;
  std::cin<<a<<b<<c<<std::endl;

//Calculate the discriminant
  
  float D= -1*b+std::sqrt(b*b-4*a*c);

//Calculate the solutions
  float xp = (-b+D)/2*a;
  float xm = (-b+D)/2*a;

//Spit out the solutions
  std::cout<<"x+: "<<xp<<std::endl;
  std::cout<<"x-: "<<xm<<std::endl;
}


// Prog2: A program to find the area of a circle.
// -----------------------------------------------


#include<iostream>
using namespace std;
int main(){

//define the variables.
float radius = 0;
float area = 0;

//Read the value for radius.
std::cout<<"Enter the value of radius: "<<std::endl;
std::cin>>radius;

//Calculate the area.
area = (3.14)*r*r;

//spit out the value

std::cout<<"Area of the circle is: "<<area<<std::endl;

}

Let us begin with the dissection of 'Prog1'. This program although not very robust, introduces many new things over the simple string spitters of last section.
  1. Sinppet:
    #include<iostream>

    This is so called preprocessor directive to tell the C++ compiler to include the definitions from iostream, which is a part of C++ standard library.

  2. Snippet:
    float a = 0;
    float b = 0;
    float c = 0;
    

    The lines in the snippet below define variables 'a','b' and 'c' of type 'float' which is the C++ type to store the numbers that include a decimal point, such as 0.5 (More about this in next chapter). Further these variables are then initialized to value 0 using the assignment (=).

  3. Snippet:
    std::cout<<"Enter the values of a, b and c: "<<std::endl;
    std::cin<<a<<b<<c<<std::endl;
    

    The program then uses the cout stream to send a message to output device calling for the values of the values a, b and c. Then it uses the cin stream to read the values supplied by user into the
    identifiers 'a', 'b' and 'c'. Both the cout and cin are defined inside the iostream, and the (::) is the "scope resolution" used to uniquely identify these objects.

  4. Snippet:
    float D= -1*b+std::sqrt(b*b-4*a*c);
    

    After reading the values of 'a', 'b' and 'c', we need to calculate the value of discriminant for the equation. Here the asterix ('*') is for the multiplication, ('-') for subtraction and ('+') stands for addition. The statement std::sqrt(b*b-4*a*c) is an example of 'call' for a function which is a reusable set of independent code defined outside the main(). In this case function definition resides in one of the header files and is made availalbe to our code by statement
    #include<cmath>

  5. Snippet:
    float xp = (-b+D)/2*a;
    float xm = (-b+D)/2*a;
    

    Now we use the standard formulae to calculate the values of positive and negative roots of the quadratic equation. Note the use of ('/') for division between two sets of expressions.

  6. Snippet:
    std::cout<<"x+: "<<xp<<std::endl;
    std::cout<<"x-: "<<xm<<std::endl;
    

    Finally use the cout stream to spit out the values of 'xp' and 'xm' on the screen.

Exercise Set: 2

We have made an impressive start at the basic functionality of the C++ language.Users of this tutorial should be able to write simple programs suggested in the exercises below.
  • Write a program to calculate the area, and diagonal of
    a square of side 10 cm.
  • Write a program to calculate the final position after 10 seconds of an object that starts with an inital speed 10 ms-1. (Use: Distance = Speed X Time)
  • Write a program to calculate the final position and velocity after 10 seconds of an object that starts with an inital speed 10 ms-1 and uniformly accelerate with 2 ms-1.
    (Use: s = u.t+(1/2)a.t2, v = u + a.t)

Execution Control: ifs, buts, and whiles .....

Albeit their academic significance, all the programs encountered till now are unrealistically simplified compared to most real world problems that one comes across in engineering and science. All these represent sequential (in the order of appearance), single execution of all the instructions in the code. But a real application may be require that a certain chunk of the code be executed( once , more than once or never), conditional to the satisfaction of certain logical constraints. The coding practice where we have several possible actions, one out of which is carried out depending on the outcome of some logical testing, is called branching, and when a protion of the program is executed again and again (a fixed number of times, or till some logical condition is met) it is called looping. We return to the quadratic equation problem of the last section where we calculated the discriminant D,
float D= -1*b+std::sqrt(b*b-4*a*c);
As any practitioner of science or engineering would realize that this expression becomes logicaly invalid when b2 < 4ac, since then the (b*b-4*a*c) is a negative number for which std::sqrt is not defined. Naturaly we would like to protect our program against the undefined behavior in such

  • Calculate (b*b-4*a*c)
  • If (b*b-4*a*c) < 0 : print: WARNING, EXIT
  • Else :Calculate float D= -1*b+std::sqrt(b*b-4*a*c);
  • Proceed as before
Implementation of this algorithm requires the program to make logical decisions and then execute the instruction that follow. The C++ proivde if functionality with following syntax,

if(condition)
   statement
or
if(condition)
  statement1
else
  statement2
Here the "condition" is an expression that yields a truth value which if true cause immediate next statement to be executed. In the second form if the truth value is false, the statement following else get executed. Here is the updated program,

//Prog1: A program to find roots of quadratic equation.
//Prog3: Demonstrate the use of if-else structure
//-----------------------------------------------------


#include<iostream>
#include<cmath>
using namespace std;
int main(){

//Define variables to hold coefficients
  
  float a = 0;
  float b = 0;
  float c = 0;

//Ask for and then read the values of a, b and c
  std::cout<<"Enter the values of a, b and c:"<<std::endl;
  std::cin<<a<<b<<c<<std::endl;

//Calculate (b*b-4*a*c)

  float arg = (b*b-4*a*c);

//Use if-else structure
 
  if(arg<0){
    std::cout<<"Warning: No real roots.\n Exiting"<<std::endl;
    return 1;
   }
  else{
    if(arg==0)
     std::cout<<"Both the roots are equal"<<std::endl;
    else 
     std::cout<<"Both the roots are real and distinct"<<std::endl;
  
   //Calculate the discriminant
  
    float D= -1*b+std::sqrt(b*b-4*a*c);

   //Calculate the solutions
    float xp = (-b+D)/2*a;
    float xm = (-b+D)/2*a;

   //Spit out the solutions
    std::cout<<"x+: "<<xp<<std::endl;
    std::cout<<"x-: "<<xm<<std::endl;
    return 0;
   }
}

We will now dissect this program to have a closer look at the newly introduced features.
  1. Code:
    float arg = (b*b-4*a*c);
    

    This declares a variable named 'arg' and initialize it
    to the value (b*b-4*a*c).


  2. Code:
    if(arg<0){
        std::cout<<"Warning: No real roots.\n Exiting"<<std::endl;
        return 1;
       }

    The arg<0 is a logical expression which can evaluate
    either to zero or one. If 'arg' is less than 0, this
    expression evaluates to 1, and cause the compound statement
    (chunk of code in curly brackets) following 'if' to execute.
    The code inside the brackets: the first line prints a warning
    on the screen i.e "Warning: No real roots" and second line
    cause the execution of main() function to stop and return
    a value 1.
  3. Code:
    else{
        if(arg==0)
         std::cout<<"Both the roots are equal"<<std::endl;
        else 
         std::cout<<"Both the roots are real and distinct"<<std::endl;
      
       //Calculate the discriminant
      
        float D= -1*b+std::sqrt(b*b-4*a*c);
    
        -----------------------------------
        -----------------------------------
        -----------------------------------
    
        }

    If (arg<0) described in the point 2 evaluates to false i.e arg
    IS NOT less than 0, the compound statement following 'else'
    would be executed. Once inside this block, implementation once
    again use "if(arg==0)" to check if 'arg' was equal to zero and if
    it is, the first statement is executed otherwise the second one is.
    Rest of the code has already been explained in the earlier examples.
  4. Some general observations, we have seen the use of
    "<" and "==" for comparison of the floating point
    variable to some value. They can be used to compare
    two variables as well (use: if(arg1<arg2))
    as long as both of them are of 'similar' type. Both of these
    belong to C++'s set of 'logical operators
    (<, >, ==, !, <=, >=)'
    for comparing the variables which can be used to
    implement "decision taking" while the execution.
Before we close this subsection, let us perform an elementary arithmetic drill. What shall we do if we wish to print all the natural numbers upto 200 on the screen ? Now is the time to introduce the "loop" constructs.A loop is a group of the statements that are repeated till a terminating condition is met. One of the possible looping facilities in C++ is "while", which has following syntax:

while(condition) statement

//Prog4: Program To print all natural numbers less than 200
//------------------------------------------------------------


#include<iostream>

int main(){

 //declare variable and Initialize it.
  int counter = 1;

 //Start a while statement.
  while(counter<=200){
    
   counter=counter+1;
   std::cout<<counter<<std::endl;  
  }
  return 0;  
}

//Prg5: Program To print all even numbers less than 200
//------------------------------------------------------------

#include<iostream>

int main(){

 //declare a variable and Initialize it.
  int counter = 1;

 //Start a while statement.
  while(counter<=200){
    
   counter=counter+1;
    
 //Modulo operator: gives remainder 
    //for "counter divided by two"
    double remainder =(counter%2);

 //If remainder is zero: current 
    //value of counter is even->print it.
    if(remainder == 0)
     std::cout<<counter<<std::endl;  
  }
  return 0;  
}
Keep tuned in for the next post where we introduce the notion of functions and data structures in C++ program.

DONT FORGET TO WRITE DOWN YOUR COMMENTS, IT HELPS US TO IMPROVE THE QUALITY