Thursday, August 23, 2018

Environment setup for c++ development

I will discuss the environment setup on Ubuntu.

The similar approach is used for CentOS and other distributions of Linux.

To install c compiler on Ubuntu.

sudo apt-get install gcc

Below package installs both gcc and g++ compilers including libraries for c++ and java also for building.

sudo apt-get install build-essential


 To check version of c++ compiler. : gcc -v
 To check version of c++ compiler. : g++ -v 

In C++, like C (as C++ is a modification or extension of C with OOPS concepts), the execution starts with main program.
// is the single line comments
/* */ multiline comments



#include <iostream>
using namespace std;
int main()//Execution begins here
{
  cout << "C++ is better than C.\n";
  return 0;
}

Here, cout refers to standard output stream(means screen here).
<< Insertion or put operator,which inserts contents of the variable(or direct value) right side to object on left.It is also used as bit-wise left shift operator.Similar to pritf()

Similarly, >> is extraction or get-from operator.It extracts the value from left side object and assigns to variable right side.Similar to scanf()

The #include line causes prepocessor to add contents of iostream file to program.It contains declarations of cout and <<.old version of c++ uses iostream.h and latest ANSI C++ uses without extension.

Namespace: defines scope of identifiers used in a program.For using the identifiers in a namespace include using directive.Above, std is namespace and all its identifiers are brought to global scope by using statement.using and namespace are from C++ , not in C.

main() returns an integer type to OS,so used return 0 as to skip warning/error.
Default return type in C++ functions is int.

To compile the above program which is saved using a text editor like nano or vi.

g++ e1.cpp

To execute the compiled file.

./a.out

We can change name of a.out to our own by ( -o newname)

#include <iostream>
using namespace std;
int main()//Execution begins here
{
  float number1,number2,sum,average;//4 variables declared and of data type float
  cout << "Enter two numbers: ";
  cin >> number1;//standard input stream(keyboard)
  cin >> number2;

  sum = number1 + number2;
  average = sum/2;
  
  cout << "Sum = " << sum << "\n";
  cout << "Average= " << average << "\n";  //cascading output operator 

  return 0;
}


cin >> number1 >> number2  (cascading)  is equavalent to
cin >> number1;
cin >> number2;


 Like structures in C, classes are user-defined datatypes, which binds both functions and variables.





No comments:

Post a Comment