12.07.2015 Views

1. Introduction 2. Basic Constructs and Data Types - University of ...

1. Introduction 2. Basic Constructs and Data Types - University of ...

1. Introduction 2. Basic Constructs and Data Types - University of ...

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>1.</strong> <strong>Introduction</strong>Computer Systems: Hardware <strong>and</strong> S<strong>of</strong>tware (OS, Compilers, Application SW)Memory in Computer Systems: used for storing program binaries as well as basic <strong>and</strong>advanced data typesProgramming Languages (High level, portable, i.e. machine independent) Syntax <strong>and</strong>SemanticsProgram CompilationA Simple C++ Program – Compilation <strong>and</strong> Execution – CLI vs GUIErrors in Programs: Compile time errors (Syntax errors) <strong>and</strong> Run time errors (logical errors)Algorithm – a step by step procedure for solving a computational problem. Later on in thecourse, we will be studying algorithms used in numerical methods <strong>and</strong> will implement some<strong>of</strong> these algorithms using C++ .<strong>2.</strong> <strong>Basic</strong> <strong>Constructs</strong> <strong>and</strong> <strong>Data</strong> <strong>Types</strong>In this chapter we review the basics <strong>of</strong> C++: keywords, variable declaration, initialization<strong>and</strong> assignment, basic data types, arithmetic <strong>and</strong> logical operators, operator precedence(BEDMAS). We conclude the chapter with a program to compute the volume <strong>of</strong> a cylinder.We assume that the user <strong>of</strong> the program will input radius r <strong>and</strong> height h <strong>of</strong> the cylinder.C++ keywords are words that are reserved for the C++ programming language. We cannotuse them as variable names (a.k.a. identifiers). Examples <strong>of</strong> C++ keywords are if, then, else,for, while, do, etc. The complete list <strong>of</strong> C++ keywords is available from if needed.Variables hold different data values <strong>and</strong> results in a C++ program. We need to declarevariables, initialize them if needed <strong>and</strong> only then use them in a C++ program. When variablesare declared, they must be a a specific data type. Two most common data types in C++ areint <strong>and</strong> float. When variables are declared, the compiler reserves memory space for storingthe value assigned to these variables. e.g. int x, y, z; float m, n;A const keyword applied to a variable forces the variable value to be fixed. For example ifwe declare: const float pi = 3.141594, then we try to assign pi = 5.2, then we will get acompile time error.© 2011 Mohammed A. S. Khalid


The fundamental data types available in C++ are: char, short, int, long, bool, float, double,long double <strong>and</strong> wchar_t. The number <strong>of</strong> bytes used for each data type depends on thecompiler <strong>and</strong> the CPU used. The operator size<strong>of</strong> can be used to obtain the number <strong>of</strong> bytesused for each data type for a specific compiler <strong>and</strong> CPU.The assignment operator “=” is used for assigning a value to a variable. This value can be anumber or the result <strong>of</strong> an arithmetic expression. For example:int x, y, x; int p; x = 20; y = 30; p = (x*x) +y;C++ provides a large number <strong>of</strong> arithmetic, logical, relational <strong>and</strong> other types <strong>of</strong> operators.Initially we will study only relatively simple operators. We will introduce more complexoperators later as needed. Commonly used operators are: +, -, *, / (arithmetic), !, &&, ||(logical), ==, !=, >, =,


3. Program Flow Control <strong>and</strong>IterationsThe if statement <strong>and</strong> the use <strong>of</strong> relational <strong>and</strong> logical operators; nested if <strong>and</strong> switch statements;h<strong>and</strong>ling abnormal exits from program; for <strong>and</strong> while statements.3.1What are the resulting values <strong>of</strong> k, l <strong>and</strong> m after the following C++ code is executed?int k = 7, l, m; l = k++; m = ++k; k *= m;3.2What is the resulting value <strong>of</strong> k, after the following C++ code is executed?int k = 7if (k < 5)k++;elsek--;3.3Determine the value <strong>of</strong> c after the following C++ code is executed. Briefly describe how you gotthe answer.main(){int a, b, c = 0;for (a=1; a


Program to illustrate scope <strong>of</strong> variables#include using namespace std;int w = 10, x = 5; // defined throughout this file <strong>and</strong> can be used in any functionmain(){int y = 2, z = 4; // defined only in main functioncout


For larger array sizes, we can use for loop to initialize array elements with a constant value.int b[100] ;for(int i=0; i


passed. Arrays are always passed by reference. CBR is also useful if the function needs to updatemore than one variable in the calling program. Examples <strong>of</strong> programs using CBV <strong>and</strong> CBR aregiven in sample programs set<strong>2.</strong>A structure in C++ allows us to create user defined variables types that can include ints, floats,doubles <strong>and</strong> even other structures. This is very useful in representing data used in many realworld computing tasks. For example, consider a structure that is used to represent a complexnumber. The idea <strong>of</strong> structure can be extended to define a class that forms the basis for objectoriented programming. We will cover classes in detail later.struct complex{double real;double imag;}complex a;a.real = 10.5;a.imag = <strong>2.</strong>3; //a now represents the complex number (10.5 + <strong>2.</strong>3i)Pointer variables are used to store address <strong>of</strong> other variables. A pointer can point to only onedata type or user defined variable type. For example a pointer to int must be different from apointer to float. We can have a pointer to a pointer as well. For example consider the programgiven below.main(){int x;int *y; // y is declared as a pointer to an integerint **z; // z is declared as a pointer to a pointerx = 25; // x is now 25y = &x; // &x means address <strong>of</strong> x, y now points to x*y = 15; // x is now 15z = &y;**z = 5; // x is now 5}For more detailed explanation <strong>of</strong> pointers, see Bijan’s presentation on pointers.When we declare an array <strong>of</strong> fixed size, the compiler reserves a fixed number <strong>of</strong> memorylocations for the array. For example, consider the following declaration:int array1[100];This will reserve 100 x 4 bytes <strong>of</strong> memory in the computer to store this array. We are assumingthat each int needs 4 bytes. If the program uses only a few elements <strong>of</strong> array1 the rest <strong>of</strong> thespace is wasted. This is an example <strong>of</strong> static memory allocation. Here we specify the array sizeat compile time.© 2011 Mohammed A. S. Khalid


In many applications, the memory requirements are not known until program run time. Forexample, consider a program that creates <strong>and</strong> stores class lists for all the courses being <strong>of</strong>fered ina <strong>University</strong> for a particular term. The number <strong>of</strong> students in each course may vary from lessthan 10 to more than 200. For such applications, it will be wasteful to reserve memory at compiletime based on the largest values needed. This is where dynamic memory allocation is useful. Itallows us to reserve memory at run time. The following example illustrates dynamic memoryallocation in C++.int *parray; int asize;cout asize;parray = new int[asize]; // the new operator allocates memory to store// “asize” integers. parray is initialized to point to start <strong>of</strong> the arrayIn many Object oriented programming (OOP) is a methodology that uses objects <strong>and</strong> theirinteractions to efficiently design <strong>and</strong> implement computer programs for complex real worldapplications. OOP has many advantages such as modular programs, information hiding,inheritance, polymorphism, ease <strong>of</strong> s<strong>of</strong>tware reuse, etc. Classes <strong>and</strong> objects form the basis <strong>of</strong>OOP. A class can be thought <strong>of</strong> as a complicated user defined data type that may consist <strong>of</strong>fundamental data types, structures <strong>and</strong> even other classes. In addition to data types, the functionsfor accessing <strong>and</strong> manipulating data types are also defined in a class. This is what differentiates aclass from a structure. That is also the reason why structures are rarely used in C++. An objectcan be thought <strong>of</strong> as an instance <strong>of</strong> a class, i.e. a physical manifestation <strong>of</strong> a class in computermemory. Classes enable modular program development <strong>and</strong> s<strong>of</strong>tware reuse. They enable easiertesting <strong>of</strong> s<strong>of</strong>tware by localizing the errors in specific modules which makes it easier to find <strong>and</strong>fix program errors. They also help in the design <strong>and</strong> implementation <strong>of</strong> complex s<strong>of</strong>twaresystems by providing features for information hiding. This means that the implementation <strong>of</strong>functions in a class is hidden from the user <strong>of</strong> the class. Any changes done in the functions <strong>of</strong> theclass will not adversely affect users <strong>of</strong> the class.A class consists <strong>of</strong> data members <strong>and</strong> member functions. Consider a simple class given below forrepresenting the time <strong>of</strong> day.class time_<strong>of</strong>_day{private:int hrs, mins, secs;public:time_<strong>of</strong>_day();time_<strong>of</strong>_day(int hrs, int min, int sec);int get_hrs();int get_mins();int get_secs();void print();};© 2011 Mohammed A. S. Khalid


<strong>Data</strong> members in this class are hrs, mins <strong>and</strong> secs. The keyword private indicates that thesevariables (data members) can be changed only by member functions <strong>of</strong> this class. Note that alldata members are in a class are private by default. We are just using the keyword private toemphasize this point. There are six member functions defined for this class. The keyword publicused for member functions indicates that these functions can be called from code outside theclass. The first two functions are constructors. Their names must be identical to class names <strong>and</strong>they do not have a return type, not even void. Note that the two constructor functions haveidentical names. This is an example <strong>of</strong> function overloading. Two or more functions have thesame name but are differentiated by the number <strong>of</strong> function parameters used.It is better to list the data members <strong>and</strong> member function prototypes in the class definition as aseparate header file. Note that when we write the code for implementing member functionsoutside <strong>of</strong> class definition, we need to use the scope resolution operator “::”. The code for thetwo constructor functions is given below. There is a check in the code to make sure that valuespassed for hours (0 to 23), minutes (0 to 59) <strong>and</strong> seconds (0 to 59) are valid. Assume that if novalues are specified, the data members will be set to 0.time_<strong>of</strong>_day :: time_<strong>of</strong>_day() : hrs(0), mins(0), secs(0) {}time_<strong>of</strong>_day :: time_<strong>of</strong>_day (int h, int m, int s){if(h >= 0 && h < 23)hrs = h;elsecout


• There is more than one method for initializing a 1-D array• An array can be initialized using cout(b)List errors, if any, in each <strong>of</strong> the following statements. In case <strong>of</strong> error, briefly describe the error<strong>and</strong> write the correct statement.• int a = {11, 22}, b[33];• float c[3] = {1<strong>1.</strong>0, 2<strong>2.</strong>0, 33.0, 44.0};• d[4] = {11, 22, 33, 44};• int a[3] /11, 22, 33/;5.3Assuming that an integer variable is represented using four bytes, what are the values <strong>of</strong>variables a, b <strong>and</strong> c after the following code is executed?int a, b, c; int mtrx [5][5];a = size<strong>of</strong> (mtrx); b = size<strong>of</strong> (mtrx[1]);c = size<strong>of</strong> (mtrx[1][1]);5.4What is the value <strong>of</strong> the variables a, (*k) <strong>and</strong> (**m) after the following code is executed?int a, b, c, *k, **m;a = 10; b = ++a; c = b++;k = &b; m = &k;5.5Give the C++ code for all the member functions in the class time_<strong>of</strong>_day that was discussedearlier in this chapter.5.6Give the C++ code for defining a class called employee. The data members in this class are name(string), address (string), salary (double) <strong>and</strong> id_num (long int). Write suitable <strong>and</strong> appropriateconstructors <strong>and</strong> member functions that can be used for this class. Write a main program thatcreates objects for this class <strong>and</strong> prints out information about those objects.© 2011 Mohammed A. S. Khalid

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!