Tuesday, 24 September 2013

C++ - Assignment No. 1

Question 1 :- 1.     Fibonacci Series where upper & lower bound will be user defined.

      #include<iostream>

using namespace std;

int Fibonacci (int);                                     //Function prototype declaration

int main(void)
{
int m,n,i;

cout<<"\nEnter the lower bound : ";
cin>>m;

cout<<"\nEnter the upper bound : ";
cin>>n;
       
        if(m>=n)  
cout<<"\nInvalid Range! Check your boundary values. ";  //Checking range validity

else
for(i=m; i<=n; i++)
cout<<Fibonacci(i)<<"  ";     //Calling the Fibonacci function
cout<<"\n";
return 0;
}

int Fibonacci (int number)
{
if (number==0)                                         //First number is 0
return 0;
if (number==1)                                        //Second number is 1
return 1;
else
return Fibonacci(number-1) + Fibonacci(number-2);  //Formula for number >=2
}

Question 2 :- Write a Program to find GCD, LCM of two numbers using recursion.

#include<iostream>
using namespace std;
int gcd(int, int);
int lcm(int, int);
int main()
{
int x, y;
cout<<"\n Enter the first number : ";
cin>>x;
cout<<"\n Enter the second number : ";
cin>>y;
cout<<"\n The GCD of "<<x<<" and "<<y<<" is : "<<gcd(x,y);
cout<<"\n The LCM of "<<x<<" and "<<y<<" is : "<<lcm(x,y);
cout<<"\n ";
return 0;
}
int gcd(int x, int y)
{
    while (x !=y)
    {
        if (x > y)
        {
            return gcd(x-y, y);
        }
        else
        {
            return gcd(x, y-x);
        }
    }
    return x;
}
int lcm (int x, int y)
{
int result;
result = (x*y)/gcd(x,y);           //Since x*y=lcm*gcd
return result;
}

Question 3 :- Find the smallest and largest no in an array.

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

    int values[ 20 ];
    int i,n,small,big; 

    cout<<"\nEnter the number of elements in the array: ";
cin>>n;
    for (i = 0; i < n; i++ ) 
    {
        cout << "\nEnter the value no." << i << ": ";
        cin >> values[i];
    }
     
big=small=values[0];
    for (i = 0; i < n; i++)
    {
        if(values[i]>big) 
        {
            big=values[i];
        }
    }

    for (i = 0; i < n; i++)
    {
        if(values[i]<small) 
        {
            small=values[i];
        }
    }

    cout << "\nThe biggest number is " << big; 
    cout << "\nThe smallest number is " << small ; 
    cout<<"\n";
    return 0;
}

#     
 

Monday, 19 August 2013

Generating Fibonacci Series with user defined lower and upper limits in C++

#include<iostream>

using namespace std;

int Fibonacci (int);                                     //Function prototype declaration

int main(void)
{
int m,n,i;

cout<<"\nEnter the lower bound : ";
cin>>m;

cout<<"\nEnter the upper bound : ";
cin>>n;
       
        if(m>=n)  
cout<<"\nInvalid Range! Check your boundary values. ";  //Checking range validity

else
for(i=m; i<=n; i++)
cout<<Fibonacci(i)<<"  ";     //Calling the Fibonacci function
cout<<"\n";
return 0;
}

int Fibonacci (int number)
{
if (number==0)                                         //First number is 0
return 0;
if (number==1)                                        //Second number is 1
return 1;
else
return Fibonacci(number-1) + Fibonacci(number-2);  //Formula for number >=2
}

Wednesday, 14 August 2013

TCS CodeVita 2013


TCS CodeVita 2013 Round 1 held on 13-14th August 2013

Problem No. 1  :- Pagination

Pagination is the process of dividing content into discrete pages. Pagination is common in Web-based applications, and is used for limiting the result set and displaying a limited number of records on the web page.
E.g.:
Consider the Department-Employee scenario. If the search operation is performed on the basis of Department Id, and there are 100,000 employees per department, then it does not make sense to display the details of 100,000 employees in single page. So, pagination allows to display limited results e.g. 20 records per page. "Previous" and "Next" links or the Page numbers are usually provided on the user interface so that users can navigate to other pages.
Q. Write a program for selecting the records that need to be displayed on user interface. Records should be filtered as per the input parameters, and should be sorted by Employee Name. Requirement is to ensure faster initial page load.
Your program should extract the records from this file on the basis of input parameters. For example, if the input is (Department ID-10, Page Size-20, and Page Number -1), then the program should retrieve first set of 20 records for Department ID-10 sorted by employee name. If the input is (Department ID-10, Page Size-20, and Page Number -2), then the program should retrieve second set of 20 records. As the data for a given department will be sorted by employee name, there will be no overlapping between first page and second page.
Asumptions:
->Input file data may or may not be sorted by Department and Employee ID
->Expected Volumes: Department Data File may have approx. 100,000 records per department ID. Page Size is expected to be less than 100 records.

Problem No. 2 :- Isotope


Scientist recently found a new element X, which can have different isotopes upto an atomic value of 199. Speciality of element X is that when two atoms fuse they produce energy multiple of their atomic value and forms an atom with atomic value of their multiple modulus 199.
For Eg:
If atom1 with value 56 and atom2 with value 61 fuse.
They produce energy of 3416 KJ (56 * 61)
Resulting atom will have atomic value (56*61) mod 199 = 33
Scientists created a nuclear reactor to create energy by this method. Everyday they get several atoms of X from supplier in a particular sequence. Since this element highly radioactive they cant risk by changing its sequence. So each atom can fuse only with another atom nearby. Nevertheless scientists can choose order of fusion thereby maximizing total energy produced.
Now, for given sequence of atomic values, output maximum energy that can be produced.
For Eg:
If sequence of atoms are
56,61 & 2
Then they can produce 3416KJ by fusing 56&61 which results in an atom of value 33. Then they can fuse 33 and 2 to get energy of 66KJ. So total energy generated is 3482.

But if they cleverly choose to fuse atoms 61 & 2 first then they generate 122 KJ with a resulting atom of value 122. Then if they fuse 122 and 56, they can generate 6832 KJ. So total energy is 6954.
Hence Maximum energy that can be generated from this sequence is 6954.
Input Format
Input starts with a number specifying number of inputs(n) followed by n space separated integers specifying atomic values of n atoms.
Line 1
N,where N is the number of atoms in the sequence to be fused.
Line 2
a1 a2 a3 .... an
where ai -> Atomic value of i th atom.
and two atoms are space delimited
Constraints:\0 < ai < 199
1 < n < 1000

Problem No. 3 – Fun with Primes


A prime number (or a prime) is a natural number greater than 1 that can only be divided by 1 and itself.
Ex-First few Prime number are-
2, 3, 5, 7, 11, 13, 17, 19,...
A digit prime is a prime number whose sum of digits is also prime.
For example the prime number 23 is a digit prime because 2+3=5 and 5 is a prime number. 17 is not a digit prime because 1+7 = 8, and 8 is not a prime number. Write a program to find out the number of digit primes within a certain range less than 1000000.and also print the Mth digit prime number between the range.
Input:
Input line contains three positive integers (T1 T2 M) separated by space where lower limit is T1 and upper limit is T2 and M is the position of the required digit prime number.
Line 1
T1 T2 M, where T1 is upper limit, T2 is lower limit and M is the position of the required digit prime number.
Constraints:
0 < T1 <= T2 < 1000000
0 < M
Output:
Print Mth digit prime number between T1 and T2(inclusive).

Problem No. 4 – Play with Alphabets


Byteland country is very famous for it's own variety of rules and customs. People from the normal world only knows 26 alphabets but the scientists in the Byteland country always try to invent new alphabets. Let N be the number of alphabets invented by the Byteland country scientists. Alice is living in Byteland country and one of her friends gifted her a new pet on her Birthday. In the Byteland country each pet must contain a name as suggested by the astronomer. After consulting an astronomer Alice came to know that length of the pet name must be of L letters and among L letters she need to keep X number of letter prefix as suggested by the astronomer.
Now Alice has decided to form the names by following the astronomer's suggestion, as Alice is weak in mathematics can you please help her to find out the number of valid names that she can form. As the combinations can be too high so mod the result by 1000000007.

Input Format:
Input contains three integers N, L, X in each line.
Given a file with certain records, find records that start with or end with a particular pattern.

Problem No. 5 :- Company Problem


Information:
Each record in a file consists of 3 distinct parts
Name of the company
Company Information Number (CIN)
Region code (where the company is based out of)
File Format
File consists of records. Records are delimited by a new-line character. Within a record, the 3 distinct parts are delimited by a string #@%#. For e.g consider the following lines

GERMAN CHEMICALS PRIVATE LIMITED#@%#U99999MH2000PTC123825#@%#RC201
GERMAN EXPRESS SHIPPING AGENCY (INDIA) PVT.LTD.#@%#U61100MH1993PTC071596#@%#RC202
GERMAN FABS PRIVATE LIMITED#@%#U17110MH1995PTC089052#@%#RC203
Here GERMAN CHEMICALS PRIVATE LIMITED is the name of the company, U99999MH2000PTC123825 is the CIN and RC201 is Region Code.
Similarly, GERMAN EXPRESS SHIPPING AGENCY (INDIA) PVT.LTD. is the name of the company, U61100MH1993PTC071596 is the CIN and RC202 is Region Code.
And, GERMAN FABS PRIVATE LIMITED is the name of the company, U17110MH1995PTC089052 is the CIN and RC203 is Region Code.
Constraints:
Company Name can be alphanumeric, can include white-space and special characters. Length of Company Name can vary.
CIN can be alphanumeric, and cannot include white-space or special characters. Length of CIN can vary.
Region Code can be alphanumeric, and cannot include white-space or special characters. Length of Region Code can vary.

Problem No. 6 :- Sculptor


Rama is a talented painter. A less known fact is that Rama also dabbles in modern sculptor. Recently, he has taken a fancy to protecting the environment, recycling junk etc. Since then, he has been using only recycled material in his sculptores.
The construction work at the site for the new campus for the Green Society of India has generated its own pile of junk. Among this junk are a large number of steel rods of varying lengths. Rama plans to use some of these in his new sculptor to be placed at the entrance, which will consist of a sequence of steel rods placed upright in a line. However, he wants the rods to be arranged in increasing order of height and, further, demands that the difference in height between each pair of adjacent rods be the same. Your task is to help him identify the largest set of rods that can be used in his sculptor.
For example, if there are 5 rods of lengths 2, 3, 6, 7 and 11 then the desired set consists of the three rods of lengths 3, 7 and 11.

Input Format:

The first line of the input consists of a single integer N indicating the number of rods. This is followed by a single line consisting of N integers indicating the lengths of the N rods.
Line 1 :- N,where N is the number of rods
Line 2
a1 a2 a3 .... an,where ai -> the lengths of the rods
and two length of rods are space delimited


Output Format:
The first line of the output consists of a single integer M indicating the maximum number of rods from this collection that may be used in Rama's sculptor. This is followed by a single line containing M integers indicating the lengths of the rods in a sculptor with M rods, in ascending order. If a group of rods with increasing order of height could not be found then you can identify the largest group of rods with difference in height between each pair of adjacent rods as zero. If there is more than one such solution then it suffices to print out one which have maximum value of length. The program should print Invalid Input when the input values do not lie within the specified boundary.
Line 1   
For Valid Input,print
M,where M is Integer stating maximum number of rods that can be used
For Invalid Input,print
Invalid Input
Line 2   
Containing M integers indicating the lengths of the rods in a sculptor with M rods, in ascending order
Two length of rods are space delimited
Constraints:
1 <= N <= 2000

M > 0

Friday, 26 July 2013

Write a C++ Program for Calculating Simple Interest

#include<iostream>

using namespace std;

int main()
{
int p;
float r, t, amount, interest;

cout<<"\n\n******Program to Calculate Simple Interest*******\n\n";
 
cout<<"\n              1.Enter the Principal Amount : ";
cin>>p;

cout<<"\n              2.Enter the Time Period : ";
cin>>t;

cout<<"\n              3.Enter the Rate of Interest : ";
cin>>r;

interest = (p*r*t)/100;

amount = p + interest;

cout<<"\n              4.The simple interest is : "<<interest;

cout<<"\n\n           5.The Amount is : "<<amount;

cout<<"\n\n ";

return 0;
}

Thursday, 4 July 2013

Classes Part - I

Classes - Part -I

The most important feature of C++ is the "Class". Its significance can be highlighted from the fact the Stroustrup initially gave it the name "C with classes". A class can be seen as an extension of the idea of structure which is used extensively in C. It is a new way of creating and implementing a user defined data type. Today we will discuss the concept of class by reviewing the traditional structures found in C and then the ways in which classes can be designed, implemented and applied.

Revisiting Structure from C

One of the unique features of C language is structures. They provide a method for packing together data of different types. A structure is a convenient tool for handling a group of logically related data items. It is a user defined data type with a template that serves to define its data properties. Once the structure type has been defined, we can create variables of that type using declarations that are similar to the built in type declarations, For example, in the following declaration :

struct student
{
      char name[20];
      int roll_number;
      float total_marks;
};

The keyword Struct declares student as a new data type that can hold three fields of different data types. These fields are known as structure members or elements. The identifier student, which is referred to as a structure name or structure tag, can be used to create variables of type student.

Structures can have arrays, pointers or structures as members.

Limitations of C Structure

The C language does not allow the struct data type to be treated like a built in data type. For example consider the following structure 

struct complex
{
       float x;
       float y;
}'
struct complex c1, c2, c3;

The complex numbers c1, c2 and c3 can be easily assigned values using the dot operand but we cannot add two complex numbers or subtract one from the other. For example :-

c1 = c2 + c3 ; is illegal in C.

Another important limitation of C structure is that they do not permit data hiding. Structure members can be directly accessed by the structure variables by any function anywhere in their scope. In other words, the structure members are public members.

Structures Extended in C++

C++ supports all the features of structures as present in C. But as is expected C++ has expanded the capabilities of structures further to suit its Object Oriented Programming philosophy. It brings the user defined types as close as possible to the built in data types, and also provide a facility to hide the data which is one of the main principles of OOP. Inheritance, a mechanism by which one data type can inherit characteristics from other data types is also supported by C++.

Some of the important features of Structures in C++
  • A structure can have both variables and functions as data members. 
  • Some of the data members can be declared as private which makes it impossible for external functions to access the data.
  • The keyword struct is not compulsory.
C++ incorporates all these changes in structures as a new user defined type known as Class. There is very little syntactical difference between structures and classes.

Generally in C++ we use structure for functions only holding data and use classes when we need to hold both data and functions. 

Note :- The only major difference between a structure and a class in C++ is that by default the members of a class are private, while in structure it is public by default.

We will learn more about classes in the next post. Keep visiting!

Sunday, 30 June 2013

Write a C++ Program to demonstrate function Overloading

//Program demonstrating the concept of function overloading//

//Author- Ashish Mishra//

//Date - 30/06//2013//

#include<iostream>

using namespace std;

//Prototype declarations

int volume (int);
double volume (double, int);
long volume (long, int, int);

int main()
{
cout<<volume(10)<<"\n";
cout<<volume(2.5,8)<<"\n";
cout<<volume(100L, 75,15)<<"\n";

return 0;
}

//Function definitions

int volume (int s)                //volume of a cube
{
return (s*s*s);
}

double volume ( double r, int h) //volume of a cylinder
{
return (3.14159 *r*r*h);
}

long volume ( long l, int b, int h)  //volume of rectangle
{
return (l*b*h);
}

The output of this program will be

1000
157.08
112500

Write a C++ Program to demonstrate default argument

//Program demonstrating the use of default argument//

//Author :- Ashish Mishra//

//Date :- 30/06/2013//

#include<iostream>

using namespace std;

int main()
{
float amount;

float value (float p, float n, float r = 0.15);     //Prototype declaration

        amount = value (5000.00 , 5);                //Default for the 3rd argument
  
cout<<"\n Final Value = "<<amount<<"\n";

return 0;

}

float value (float p, float n, float r)
{
int year = 1;
float sum = p;

while ( year <=n)
{
sum = sum*(1+r);
year= year + 1;

}

return (sum);
}

The output of the program is "Final Value = 10056.80"


Tuesday, 25 June 2013

Functions - III

Inline Functions

The main objective of using functions in a program is to save memory space, which becomes appreciable when a function is likely to be called many times. However, every time a function is called it takes a lot of extra time in executing a series of instructions for tasks such as jumping to the function, saving registers, pushing arguments into the stack and return to the calling function. when a function is small, a substantial percentage of execution time maybe spent in such overheads.

One solution to this problem is to use a macro definition, as you would be aware it to be macros from C. Pre-processor macros are used in C. The major drawback with macros is that they are not really functions and hence any error would go unchecked as error checking is not done during compilation. 

C++ has a feature which presents the perfect solution to his problem. To eliminate the cost of calls to small function C++ has a new feature called the Inline Function. An inline function is a function that is expanded in line when it is invoked. That is, the compiler replaces the function call with the corresponding function code (Which you might consider similar to macro expansion). The inline functions are defined as follows :-

inline function-header
{
         function body
}

Example

inline double cube (double a)
{
     return (a*a*a);
}

The above inline function can be invoked by statements like 

c = cube (3.0);

d = cube (2.5+1.5);

On the execution of these statements, the values of c and d will be 27 and 64 respectively. If the arguments are expressions like 2.5+1.5, the function passes the value of the expression , 4 in this case. This makes the inline feature far superior to macros.

It is easy to make a function inline. All we need is to do is to prefix a keyword inline to the function definition. All the functions must be defined before they are called.

*NOTE
We should be extremely careful before making a function inline. The speed benefits of inline functions diminish as the function grows in size. At some point the overhead of the function call becomes small compared to the execution of the function, and the benefits of inline functions will be lost. In such cases, the use of normal functions will be more meaningful. Usually, functions are made inline when they are small enough to be defined in one or two lines.

Limitations

The inline keyword merely sends a request and not a command to the compiler. The compiler may ignore the request if the function definition is too long or too complicated and might compile the function as a normal function.

Some of the limitations where inline functions do not work :-

  • For functions returning values, if a loop, a switch, or a goto statement exists.
  • For functions not returning values, if a return statement exists.
  • If function contains a static variable.
  • If inline functions are recursive.
A program to illustrate the use of inline function

#include<iostream>

using namespace std;

inline float mul (float x, float y)
{
     return (x*y);
}

inline double div (double p, double q)
{
      return (p/q);
}

int main()
{
       float a = 12.965;
       float b = 9.810;

       cout<<mul (a,b)<<"\n";
       cout<<div (a,b)<<"\n";
     
       return 0;
}


The output of the program is 
127.187
1.32161

Default Argument

C++ gives the provision to call a function without specifying all its arguments. In such cases, the function assigns a default value to the parameter which does not have a matching argument in the function call. Default values are specified when the function is declared. The compiler looks at the prototype to see how many arguments a function uses and alerts the program for possible default values. 

Here is an example of a prototype of a function declaration with default values :-

float amount (float principal, int period, float rate =0.15);

The default value is specified in a manner syntactically similar to a variable initialization. The above prototype declared a default value of 0.15 to the argument rate. A subsequent function call like

value = amount (5000, 7);        //Argument for rate is missing

passes the value of 5000 to the principal and 7 to the period and then lets the function use default value of 0.15 for rate.

The call

value = amount (5000, 5, 0.12)  //No argument missing

passes an explicit value of 0.12 to rate.

A default argument is checked for type at the time of declaration and evaluated at the time of call. One important point to note is that only the trailing arguments can have default values and therefore we must add defaults from right to left. We cannot provide a default value to a particular argument in the middle of an argument list. 

Note :- Default arguments are useful in situations where some arguments always have the same value. For instance, bank interest may remain same for all the customers taking a particular type of loan for a particular period. It also provides a greater flexibility to the programmers. A function can be written with more parameters than are required for its most common application. Using default arguments, a programmer can use only those arguments that are meaningful to a particular situation.

Advantages of Default Arguments :-

  • We can use default arguments to add new parameters to the existing functions.
  • Default arguments can be used to combine similar functions into one.

Constant Argument

In C++, an argument to a function can be declared as const  as shown below :-

int strlen ( const char *p);
int length (const string &s);

The qualifier const tells the compiler that the function should not modify the argument. The compiler will generate an error when this condition is violated. This type of declaration is significant only when we pass arguments by reference or pointers.

Function Overloading

As we know overloading means the use of the same thing for different purposes. C++ also permits overloading of functions.This means that we can use the same function name to create functions that perform a variety of different tasks. This is known as function polymorphism in OOP concept.

Using the concept of function overloading we can design a family of functions with one function name but with different argument lists. The function would perform different operations depending on the argument list in the function call. The correct function to be invoked is determined by checking the number and type of the arguments but not on the function type. For example, an overloading add() function handles different types of data as shown below :-

//declarations

int add (int a, int b)                                    //prototype 1
int add (int a, int b, int c)                            //prototype 2
double add (double a, double b)                   //prototype 3
double add (double p, int q)                        //prototype 4
double add (int x, double y)                        //prototype 5

//Function calls

cout<<add (5,10);                       //uses prototype 1
cout<<add (5,10.50,8);                //uses prototype 2
cout<<add (12.5,10.9);                //uses prototype 3
cout<<add (5.78,10);                   //uses prototype 4
cout<<add (5,10.98);                   //uses prototype 5

A function call first matches the prototype having the same number and type of arguments and then calls the appropriate function for execution. A best match must  be unique. The function selection involves the following steps.
  • The compiler firsts tries to find an exact match in which the types of actual arguments are the same and uses that function.
  • If an exact match is not found, the compiler uses the integral promotions to the actual arguments, such as,  
       char to int
       float to double
      to find a match
  • When either of the  fails, the compiler tries to use the built n conversions to the actual arguments and then uses the function whose match is unique. If the conversion is possible to have multiple matches then the compiler will generate an error message. Suppose we use the following two functions 
       long square (long n)
       double square (double x)

       A function call such as square (10)
     
       will cause an error because int argument can be converted to either long        
       or double thereby creating an ambiguous situation as to which version of 
       square() should be used.
  • If all of the steps fail, then the compiler will try the user-defined conversions in the combination with integral promotions and built in conversions to fund a unique match. User defined conversions are often used in handling class objects. 
Note :- Overloading of functions should be done with caution. We should not overload unrelated functions and should reserve function overloading for functions that perform closely related tasks. Sometimes, the default arguments may be used instead of overloading. This may reduce the number of functions to be defined.

Thats all of functions that we need to know as of now.

Tasks :-

Q. Write a C++ program that will illustrate Default argument and function overloading features.

Saturday, 22 June 2013

Functions II


In the previous post I had talked about main functions and function prototyping. In this post I would like to continue on functions and cover all the areas around them.

Call By Reference

Limitations of Call by Value

In C language a function call passes arguments by value. The Called function creates a new set of variables and copies the values of arguments into them. The function does not have access to the actual variables in the calling program and can only work on the copies of the actual values. This mechanism works fine until the function does not need to alter the values of the original variables in the calling program. 

But such demanding situations might arise where we need to change the values of the variables in a calling function. Such as in the case of Bubble sort problem where we need to compare two adjacent elements in the list and interchange their values according the the comparison results if needed. If a function is used for creating a Bubble sort algorithm then it should have the capability to alter the values of variables in the calling functions, which is not possible by call by value method.

Call By Reference

In C++ we use reference variables which enable us to pass parameters to the functions by reference. When we pass an argument by reference, the formal arguments in the called function becomes aliases to the actual arguments in the calling functions. This means that when the function is working with its own arguments it is actually working on the original data. 

An example would make things appear easier, 

void swap ( int &a , int &b )        //a and b are reference variables 
{
         int t = a;
         a=b;
         b=t;
}

Now if m and n are two integer variables, then the function call 

swap (m,n);

will exchange the values of m and n using the aliases a and b.

In C languages this is accomplished by using pointers and indirections.

Return By Reference

A function can also return a reference. Consider the following function :

int & max (int &a, int &b)
{
         if (a>b)
                 
            return a;
         else
           
            return b;
}

Since the return type of max() is int&, the function returns references to a or b. Then a function call such as max (x,y) would yield a reference to either x or y depending on their values. This means that this function call can appear on the left hand side of an assignment statement. That is, the statement

max (x,y) = -1;
is legal and assigns -1 to x if it is larger otherwise -1 is assigned to y.

In the next post I would stress on inline functions, default arguments and function overloading.









Thursday, 20 June 2013

Functions in C++

The Main Function


C language does not specify any return type for the main () function which is the starting point in the execution of the program. The main() definition looks something like this in C -

main()
{

       // main program statements and instructions

}

This is perfectly valid in C as main() is C doesnt return any value.

In contrast C++ has a return value of type int for the main () to the Operating System. The main function in C++ is, therfore defined as follows :-

int main ()
{

 //program statements

return 0;
}

Note :- Since the return type of functions is int by default, the keyword int in the main is optional.

Many Operating systems test the return value to determine if there is any problem. The normal convention is that an exit value of zero means that the program ran successfully, while a nonzero value means there was a problem. The explicit use of a return 0 statement will indicate that the program was successfully executed.

Function Prototyping

Function prototyping is one of the major improvements added to C++ functions from C functions. The prototype describes the function interface to the computer by giving details such as the number and type of arguments and the type of the return value. With function prototyping , a template is always used when declaring and defining a function. When a function is called, the compiler uses the template to ensure that proper arguments are passed, and the return value is treated correctly. These checks and controls didnt exist in the conventional C functions.
 
Function prototype is a declaration statement in the calling program and is of the following form
 
type function-name (argument list );
 
The argument list contains the types and names of arguments that must be passed to the function.
 
Example
 
float volume (int x, float y, float z);
 
Note :- Each argument variable must be declared independantly inside the parentheses i.e. a combined declaration like
 
float volume (int x, float y, z) ; is illegal.
 
In a function declaration, the names of the arguments are dummy variables and therefore they are optional. That is , the form
 
float volume (int , float, float );
 
is acceptable at the place of the abovemetioned declaration. At this stage, the compiler only checks for the type of arguments when the function is called.
 
In the function definition though , names are required because arguments must have a reference inside a function.
 
Example :-
 
float volume ( int a, float b, float c)
{
 
       float v = a*b*c;
       .........................
       .........................
}
 
the function volume () can be invoked in a program as follows :
 
float cube1= volume (b1,w1,h1);   //Calling the function
 
The variables b1, w1, h1 are known as actual parameters which specify the dimensions of cube1. Their types should match with the types declared in the protoype.
 
We can also declare a function with an empty argument list, as in the following example :-
 
void display () ;
 
In C++, this means that the function does not pass any parameters. It is identical to the statement
 
void display ( void);
 
In C an empty parantheses implies any number of argument generally returning garbage values, in C++ though we have a default void type if the parantheses is left empty.
 
Hope to see you again for the next topic.
 
Note :- Each argument variable must be declared independantly inside the parantheses.  

Monday, 10 June 2013

Data Types

Basic Data Types

Both C and C++ compilers support all the built in basic data types. With the exception of void, the basic data types may have several modifiers preceding them to serve the needs of various situations. The modifiers signed, unsigned long and short may be applied to character and integer basic data type.
However the modifier long may also be applied to double. 

Here is a list of all the combinations of basic data types with their size and range for a 16 bit machine.


User Defined Data Types

If you have used C you all must have used user defined datatypes such as struct and union in C. While these data types are legal in C++, some more features have been added to make them suitable for object oriented programming. C++ also permits us to define another user defined data type known as class which can be used just like any other basic data type, to declare variables. The class variables are known as objects, which are of central importance in OOP.

Enumerated Data Type

An enumerated data type is another user defined data type which provides a way for attaching names to numbers, thereby increasing the comprehensibility of the code. The enum keyword automatically enumerates a list of words by assigning them values 0,1,2 and so on. This facility provides an alternative means for creating symbolic constants. The syntax of an enum statement is similar to that of the struct statement.

Derived Data Type

  • Arrays :- The application of arrays in C++ is similar to that in C. And they only exception is that the size of the array should be one larger than the number of characters in the string.
  • Functions :- Functions are a lot different in C++ as compared to C. While some of these changes are simple while others require a new of thinking when organising our programs. Many of these modifications and improvements were driven by the requirements of the Object oriented concepts of C++ . We will discuss them in details later.
  • Pointers :- Pointers are declared and initialised as in C. Examples :- int *ip; ip= &x; *ip=10. C++ adds the concept of constant pointer and pointer to a constant. 
          char * const ptr1 = "GOOD";           //constant pointer
         we  cannot modify the address that ptr1 is initialized to 
         int  const * ptr2 = &m;  //pointer to a constant.

Symbolic Constants

There are two ways of creating symbolic constants in C++
  • Using the qualifier const, and
  • Defining a set of integer constants using enum keyword.
In C++ as in C , any value declared as const cannot be modified by the program in anyway. However there are some differences in implementation. In C++ , we can use const in a constant expression such as :

const int size = 10;
char name [size];
this would be illegal in C. 

Declaration of Variables

We know that in C all variables must be declared before they are used in executable statements. This is true in case of C++ as well. However there is a significant difference between C and C++ with regard to the place of their declaration in the program. C requires all the variables to be defined at the beginning of a scope. When we read a C program, we usually come across a group of variable declaration at the beginning of each scope level. Their actual use appears elsewhere in the scope, sometimes far away from the place of declaration. Before using a variable, we should go back to the beginning of the program to see whether it has been declared and if so, of what type.

C++ allows the declaration of a variable anywhere in the scope. This means that a variable can be declared right at the place of its first use. This makes the program much easier to write and reduces the errors that maybe caused because the variable are declared in the context of their use. The only disadvantage of this style of declaration is that we cannot see all the variables used in the program at a glance.

Thats all for today friends get back to you tomorrow with lots more :)