Introduction Continued

Comments

We can place comments in our code to make the code more readable and to make notes to ourselves or for any other purpose. Comments are not considered during compilation. Their purpose is only to keep notes and this is advisable because in large projects it's difficult to make out what the code is doing sometimes. It's also a good idea to embed the author of the code at the top of the file in projects so that we know who wrote that piece of code.

There are 2 different ways of placing comments. One is a single line comment using the forward slashes and another is using a forward slash and a star.

File: "comment1.cpp"

#include <iostream>using namespace std ;//This program created by instructor.int main (){ /* Inside the main function. */ cout << "This program has comments." << endl ; return 0 ;

}

Also note that spaces and new lines are also not considered by the compiler when compiling the program to machine language. We use them to make sure that the code is readable. The below program also compiles and runs fine.

#include <iostream>using namespace std ;intmain () { cout << "This program does not have comments." << endl ;return 0;}

Type conversions

We are going to lose some precision if a variable with a higher range is is assigned to another variable. with a smaller range.

Ex:

#include <iostream>using namespace std ;int main(){ char ch1 ; int x1 ; x1 = 1.9f ; ch1 = x1 ; cout << "ch1:" << (int)ch1 << endl ; x1 = 2500 ; ch1 = x1 ; cout << "ch1:" << (int)ch1 << endl ; return ( 0 ) ;}

Output:

ch1:1

ch1:-60

[amittal@hills types]$ g++ -Wconversion type2.cpp

type2.cpp: In function ‘int main()’:

type2.cpp:14:9: warning: conversion to ‘int’ alters ‘float’ constant value [-Wfloat-conversion]

x1 = 1.9f ;

^~~~

type2.cpp:15:10: warning: conversion to ‘char’ from ‘int’ may alter its value [-Wconversion]

ch1 = x1 ;

^~

type2.cpp:18:10: warning: conversion to ‘char’ from ‘int’ may alter its value [-Wconversion]

ch1 = x1 ;

Let use understand the output. The floating point 1.9 got converted to an int and the system essentially discarded the fraction and we get 1 .

x1 is 2500 and we assign that to a char which is a single byte. The 2500 in binary is :

1001 1100 0100

Since a char is a single byte we get

1100 0100

Now char is converted to an integer and it can contain both signed and unsigned numbers unless we use the qualifier "signed" or "unsigned" . So two's complement is used the and the leftmost bit states that it is a negative no. Complementing the 7 bits gives us

0 1 1 1 0 1 1

This gives 59 and we add 1 ( two's complement ) to give us 60 and since the number is negative we get -60 .

Scope

Scope refers to the life time of a variable. Where can that variable be accessed from ? That depends on how it was defined. Let us take the following example:

Ex:

// This program can't find its variable.

#include <iostream>

using namespace std;


int main()

{

cout << value;

// ERROR! value not defined yet!

int value = 100;

return 0;

}


[amittal@hills scope]$ g++ scope3.cpp

scope3.cpp: In function ‘int main()’:

scope3.cpp:7:16: error: ‘value’ was not declared in this scope

cout << value; // ERROR! value not defined yet!

The above example shows us that a variable must be defined before it can be used. If a variable is defined in a block then it's scope is limited to that block.

Ex:

//Program illustrating scope

#include <iostream>using namespace std;int value = 100;int main() { int value = 10 ; //Scope of this is till end of the function cout << value << endl ; { int value = 20 ; //scope of this is till closing brace B cout << value << endl ; { int value = 30 ; //Scope till closing brace A cout << value << endl ; } //A cout << value << endl ; } //B cout << value << endl ; cout << ::value << endl ; return 0; }

Output:

[amittal@hills scope]$ ./a.out

10

20

30

20

10

100

Characters and Strings

In C++ there are 2 ways we can store strings. One is the C style of storing strings. That is using an a character array. In this method the characters are stored in the array and terminated by the null character of 0.

#include <iostream>

#include <string.h>

using namespace std ;

int main()

{

char str1[] = "Testing" ;

string str2 = "class" ;

cout << str1 << strlen( str1 ) << endl ;

cout << str2 << str2.length() << endl ;

string str3 ;

str3 = str2 + " Something appended." ;

cout << str3 << endl ;

}

Output:

[amittal@hills chapter2]$ ./a.out

Testing7

class5

class Something appended.

We shall study this in more detail later on. The "str1" is an array of characters and we assign a string literal to it. There are functions in the standard library such as "strlen" that computer the length of the string. The "string str2" is a class defined in the library also. It is a class that someone wrote and not an inherent part of the "C++" language. We can also write our own string class if we wanted to. The class has it's own member functions such as "length()" .

Escape Sequences

\n Newline. Position the screen cursor to the beginning of the next line.\t Horizontal tab. Move the screen cursor to the next tab stop.\r Carriage return. Position the screen cursor to the beginning of the current line; do not advance to the next line.\a Alert. Sound the system bell.\\ Backslash. Used to print a backslash character.\' Single quote. Used to print a single quote character.\" Double quote. Used to print a double quote character.

cin and cout

We can use the "cout" and "cin" to output text to the console and read from console. These objects are declared in the file "<iostream>" and are in the namespace "std" . Thus we need to include the file "<iostream>" and the either do the "using namespace std" or "std::cout" to use it.

The following program takes 2 integer values from the user and outputs their sum.

File: "io1.cpp"

#include <iostream>using namespace std ;int main (){ int num1 ; int num2 ; cout << "Enter the first integer:" ; cin >> num1 ; cout << "Enter the second integer:" ; cin >> num2 ; cout << "The sum of " << num1 << " and " << num2 << " is:" << ( num1+num2) << endl ; return 0 ;}

We shall study input/output in more detail in later chapters . For now we have enough knowledge to work with these objects in a simple manner.

Exercise

Write a program to output the following lines :

Online classes are fun

I can finally catch up on my sleep.

You can use "endl" object or "\n" as end of line separator.

Constants

#include <iostream>using namespace std;//macro definition#define X 30//global integer constanttconst int Y = 10;int main(){ //local ineteger constant` const int Z = 30; cout<<"Value of X: "<<X<<endl; cout<<"Value of Y: "<<Y<<endl; cout<<"Value of Z: "<<Z<<endl; return 0;

}

In the above program we are using 2 different kinds of constants . There is the preprocessor that will replace all occurrences of "X" with 30 and there is the variable Z that cannot be modified. What is the difference between these 2 styles ? The "#define" statements are usually placed at the top of the file. Their scope exists till the end of the file. If we define a variable outside a function then that variable is a global variable and can be accessed from anywhere in the program.

Exercises

1)

The following program should print:

//Should print

//Area is 12.56

Fix the compiler errors so that it works correctly.

File: "order1.cpp"

#include <iostream>

//This function computes the area of a circle

{

Area = PI * radius * radius ;

const double PI = 3.14 ;

double Area ;

return Area ;

}


double areaOfCircle ( double radius )

/* This is the main function */

int main()

{

return ( 0 ) ;

cout << "Area is:" << areaOfCircle( radius ) << endl ;

double radius = 2 ;

}


using namespace std ;

2)

#include <iostream>

using namespace std ;

//Fibonacci sequence

// 1 , 1 , 2 , 3 , 5

// Do not use loops

// literal expressions .

// Do not use expressions in the cout statement

// Do not create more variables

int main()

{

int x1 = 1 ;

int x2 = 1 ;

int temp ;

//To do

//Third Fibonacci

cout << x2 << endl ;

//To do

//Fourth Fibonacci

cout << x2 << endl ;

}

3)

Use the below skeleton program.

#include <iostream>

using namespace std ;

int main ()

{

int x1 = 100 ;

int y1 = 200 ;

int temp ;

//TO DO

cout << "x1:" << x1 << " y1:" << y1 << endl ;

return 0 ;

}

Output:

$ ./a.exe

x1:200 y1:100

Write code to swap the values of "x1" and "x2" . Is it possible to do this with just the variables "x1" and "x2" ?

4)

What does the below program print ? Compile and run it and explain your logic. Place the global variable "value" in a namespace and modify the last statement in the main function that prints out the variable.

#include <iostream

using namespace std;


int value = 100;

void function1()

{

int value = 20 ;

cout << "value:" << value << endl ;

}


void function2()

{

cout << "value:" << value << endl ;

}

int main()

{

int value = 10 ;

//Scope of this is till end of the function

cout << value << endl ;

function1() ;

function2() ;

cout << value << endl ;

cout << ::value << endl ;

return 0;


}


Solutions


3)


#include <iostream>

using namespace std;


int main()

{

int x1 = 100 ;

int y1 = 200 ;

int temp ;


//Using temp

temp = x1 ;

x1 = y1 ;

y1 = temp ;


//Without temp

/* x1 = x1 + y1 ;

y1 = x1 - y1 ;

x1 = x1 - y1 ; */



cout << "x1:" << x1 << " y1:" << y1 << endl ; return 0;

}