Introduction Continued
Contents
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. This style can span many lines. */ cout << "This program has comments." << endl ; return 0 ; }
File: comment2.cpp
#include <iostream> using namespace std ;int main () { cout << "This program does not have comments." << endl ;return 0;}
Exercise: Does the below program compile ? As the below program shows sometimes overuse of comments can make the program difficult to read.
File: ex_c1.cpp
#include <iostream> using namespace std ; //This program created by instructor. int add( int x1 /* x1 */ , int x2 /* x2 */) { //comment 1 return ( x1 + x2 ) ; //comment 2 //comment 3 } //comment 4 //comment 5 /* comment 6 */ int main () //comment 7 { cout << "This program has 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.File: type1.cpp
#include <iostream> using namespace std ; int main() { char ch1 ; int x1 ; x1 = 1.9f ; cout << "x1:" << x1 << endl ; ch1 = x1 ; //The cast is necessary otherwise a character is printed //out . cout << "ch1:" << (int)ch1 << endl ; x1 = 2500 ; ch1 = x1 ; cout << "ch1:" << (int)ch1 << endl ; return 0 ; } $ g++ type1.cpp ; ./a.exe x1:1 ch1:1 ch1:-60
$ g++ -Wconversion type1.cpp type1.cpp: In function ‘int main()’: type1.cpp:8:14: warning: conversion from ‘float’ to ‘int’ changes value from ‘1.89999998e+0f’ to ‘1’ [-Wfloat-conversion] 8 | x1 = 1.9f ; | ^~~~ type1.cpp:10:15: warning: conversion from ‘int’ to ‘char’ may change value [-Wconversion] 10 | ch1 = x1 ; | ^~ type1.cpp:15:15: warning: conversion from ‘int’ to ‘char’ may change value [-Wconversion] 15 | ch1 = x1 ;The g++ compiler assumes that we know what we are doing and by defualt does not show us any warnings. We can use the "-Wconversion" to show the warnings.
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:File: scope1.cpp
// 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; }
File: scope2.cpp
#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; }
$ ./a.exe 10 20 30 20 10 100Exercise:
What is the output of the following program ? Confirm your answer by compiling and running it.
File: ex_s1.cpp
#include <iostream> using namespace std; int value = 100; int add( int x1, int x2 ) { cout << x1 << endl ; return ( x1 + x2 ) ; } namespace group1 { int value = 10 ; } int main() { cout << group1::value << endl ; cout << add( 4, 5 ) << endl ; cout << value << endl ; cout << ::value << endl ; return 0; }
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.File: ch1.cpp
#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 ; }
$ g++ ch1.cpp ; ./a.exe 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.
File: esc1.cpp
#include <iostream> #include <string.h> using namespace std ; int main() { cout << "End line." << endl ; cout << "End line another way.\n" ; cout << "Start of Tab\tEnd of Tab" << endl ; cout << "Single Quote: \' Double Quote:\"" << endl ; }
$ g++ esc1.cpp ; ./a.exe End line. End line another way. Start of Tab End of Tab Single Quote: ' Double Quote:"
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 "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 ; }
$ g++ io1.cpp ; ./a.exe Enter the first integer:3 Enter the second integer:2 The sum of 3 and 2 is:5
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
File: const1.cpp
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. The "#define" approach does not provide different scopes.
Exercises
1) Re arrange the lines in the below program so that the right area is computed and printed out. Do not add or delete any lines.File: order1.cpp
2)
File: exf1.cpp
3)
File: exf2.cpp
Output: $ ./a.exe x1:200 y1:100Write 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.
File: exf3.cpp