C++ PROGRAMMING BASICS

Size: px
Start display at page:

Download "C++ PROGRAMMING BASICS"

Transcription

1 C++ Notes 1 By V. D. Gokhale C++ PROGRAMMING BASICS Difference between C and C++ :- (1) When we invoke turbo C++ editor by c:\tc\tc [Enter]. The editor window shows the file name with.c extension. [noname00.c]. Means turbo C++ initially assumes that we that tc editor to write program in C. To tell the compiler, that we want to make program in C++, we should change the file extension to.cpp. This extension is the only that turbo C++ knows whether to use C or C++ compiler. The changing of extension from C to CPP, can be done by From file menu, use save as. Option. Click the mouse or press ENTER key here. A typing window will appear. Type the desired file name, then type. and finally type CPP. Then click on OK or press ENTER. The default name of file on top of editor window will get changed to your desired file name with CPP extension. (2) In C for input (by scanf()) and for output (by printf()) the inclusion of file stdio.h was not always necessary. Bur in C++, for input and output inclusion of standard library file iostream.h is must. (This is done by typing #include <iostream.h> on the top of the every program) (3) In C we use to write the main function as main(), but in C++, as a procedure, it is better to write void main(). The word void indicates that the main function is not going to return any value. ISO change int main() [empty bracket]. Thus the last statement should be return(0);. Note :- If no return value is specified, the default is int. Default parameters are int and char *[] which are command line arguments. (4) The C++ compiler ignores white space almost completely. (5) Output -> In C, the output is mainly accomplished by printf() function. In C++ the output is a accomplished by cout <<. Where cout is an identifier, which is actually an object and << is known as insertion operator or put to operator. The desired output message should be enclosed in double quotes and the whole statement is then finally terminated by semicolon. e.g. cout << message ; The output of this statement will the word -> message.

2 C++ Notes 2 By V. D. Gokhale Here the desired output is enclosed in double quotes and the whole statement is finally terminated by semicolon. * We mainly use outputs by 3 ways. (1) Only text output. (2) Only variable output. (3) Text variable output. (i) (ii) Only text output :- In this we want only some text to get output (printed) on the screen. In such type the text should be enclosed in double quotes. e.g. -> Suppose we want to get printed the text message Every age has a language of its own on screen then cout << Every age has a language of its own ; Only variable value output :- Some times we need to print variable value on screen. In this case just use variable name with cout <<. without any double quotes. e.g. -> int var1 = 10; int var2 = 20; int var3; var3 = var1 + var2; cout << var3; The screen will give output as 30. Here we want to print value in var3, hence we just use variable name without any double quotes. Note :- One of the most important difference in output by C and C++ is. In C while using printf() function, for getting variable values, we have to use identifier like %c, %f, %d for character, float and integer variable respectively. But in C++, there is no need of mentioning respective variable type. The cout << operator itself can judge the variable type. Means if we pass string to cout <<, it will print string, if we pass integer variable, it will print value of integer and so on. Thus happen due to t he property of operator overloading which is a feature of C++. ISO changes in #include -> no.h is written. e.g. #include <iostream> ISO -> In C UDF [User defined functions] can call main(). But in C++ now it is illegal. No UDF can call main(). ISO changes in cout << it is considered as std :: cout << -> here std :: is a namespace. For multiple output, we can use single cout statement and then cascade the << operator as. cout << num1 << num2 << num3;

3 C++ Notes 3 By V. D. Gokhale (iii) Both text and variable value output -> It is the combination of (1) and (2). Means text should be enclosed in double quotes and variable name without double quotes. e.g. see example in 2 cout << The sum is ; cout << var3; The output of above 2 cout statements will be The sum is 30. Here we get output in one line using 2 cout on 2 different lines. If we need to use only one cout to give both outputs we should cascade << operators twice. e.g. The same above example. cout << The sum is << var3 ; Also suppose there is 1 cout statement, prior to another cout statement and both of them do not have newline escape sequence, then the 2 outputs will appear on same line. To introduce newline (1) Either use \n escape sequence within double quotes text. (2) Or use \n (with single quote) escape sequence any where in the cout statement, but with << operator. (3) Or use a manipulator known as endl with << operator in cout statement. But note that while using endl you must include iomanip.h header file with #include directive at the top of the program, above or below # include <iostream.h>. [ endl is the new identification of \n ]. (6) Comment -> As we know well, comments make the program readable to the programmer in future. We required comments to use in 2 situations. At the beginning of any statement of program. At the end of any statement of program. (i) For using comments at the beginning of the line we can use // double slash symbol, if the comment is short. This comment sign is readable in C++ only. But if the comment itself is quite bigger and if requires 2 or 3 lines, then instead of using // 3 times, we can use C comment sign, as /*. comment. (ii). */ But when we require statement at the end of a program segment, then use // commonly in C++. (7) Variable definition -> In C we have to declare all variables before the 1 st executable statement of a program. But in C++ we can declare variable anywhere in the program, when we

4 C++ Notes 4 By V. D. Gokhale want to use it. (8) Input -> In C, input from keyboard is mainly accomplished by scanf() function. In C++ the input is accomplished by cin >>. When cin is an identifier and >> is known as extraction operator or get from operator. e.g. int num; cout << Enter a 3 digit number : ; cin >> num; Here the message in cout will get displayed on the screen and compiler will wait for you to enter any 3 digit number. Thus cin >> allows compiler to wait for input. [ Note like scanf(), there is no need to pass data type and & prefix to variable format string to cin. ] Here we need to enter multiple values the there is no need of using cin every time. We can do it by cin >> num1 >> num2 >> num3; ISO -> std :: cin. (9) In C multi time usable constants like PI etc, are predefined by # define preprocessor directive. This # define preprocessor directive can be used in C++ too but it is not so popular in C++. Instead of that in C++, const qualifier is used. Const qualifier specifies that the value of variable supplied by the word const, is not going to change through the program. Any attempt to change it, will result in an error. e.g. const float PI = ; The variable declared as const can be used as size of array. e.g. const int size = 10; char arr[size]; The syntax of const qualifier is. 1 st the keyword const. Data type. Desired variable name, generally in block letters to let to know that it is constant. Value to assign it with equal sign. * const <data type> <variable name> = <assign value> By default const is an integer. e.g. const x; means int x; (10) Manipulators -> Manipulators are operators to use with << insertion operator in const statement to modify the way of data displaying. The most common 2 manipulators are endl and setw(); endl [ std :: endl ] :- Means end line. When this is used with cout the output gets displaye on next line at the beginning. Thus it is nothing but the \n newline operator expressed in terms of words.

5 C++ Notes 5 By V. D. Gokhale endl flushes output stream while \n does not. setw() [ std :: setw() ] :- Means set width. This manipulator is used for formatted output, exactly one below the other, by setting width. For this we have to pass the desired width to it in brackets, such as setw(8) -> now it will set width of output for 8 columns. For using setw() manipulators, inclusion of iomanip.h header file is must. This is done by introducing line. # include <iomanip.h> at the top of the program. (In ISO manipulators are added in namespace <iostream> which if included, no need of iomanip.h) There are yet other 3 manipulators std :: dec, std :: oct, and std :: hex which gives decimal, octal, hexadecimal value of the variable. They should used before the variable each time. e.g. int num 123; std :: cout << std :: dec << num << std :: oct << num << std :: hex << num << std :: endl; output : decimal octal hexadecimal ISO -> During automatic type conversion C changes value from higher data type to lower without any type of warning. But C++ now sets warning message of possible data loss. Basic streams -> cout (standard output), cin (standard input), and cerr(standard error). Use them with std :: e.g. cerr <<.. [syntax is same as cout <<] Output goes to standard error device. (11) Typecast -> In C, when we do typecast we enclosed the desired data type in brackets and keep the variable name open. e.g. If we want to change int x to float value we do.(float) x; But in C++, the approach is easier and like function notation. Means data type is kept free, while variable name is enclosed in brackets. e.g. float(x); (12) In loops :- The loop is limited by braces. In C++ we can declare a variable inside this loop bode. Surprisingly variable declared inside the body or block is not visible outside the loop. e.g. int i; for(i=0;i<11;i++) int sq; sq = i * i; cout << sq << \n ;

6 C++ Notes 6 By V. D. Gokhale Here we declared variable sq inside the for loop block. This loop will give square values of number to 10. But after ending the loop, if we again type cout << sq; Then compiler will give error, that the variable sq is not defined. This shown that variable declaration can be done inside the loop block and it will be visible only inside the block and not visible outside the block. This property is not in C. (13) As per the point (7) we can define and declare variable anywhere in the C++ program, where we want to use that variable. This property can be used in loops too. e.g. for(int i=0; i<11; ++i) is valid. Means we define and declare variable I, inside the for statement. (14) Structures :- Structures should be studied in detail in C++, because they resemble to the key feature of C++, i.e. CLASSES. The syntax of a structure is almost identical to the syntax of a class. A structure is used for used for collection of data while a class is used for collection of data and function. [ Though we say that structure holds data and classes hold both data and function, actually structure itself can also hold both data and function too. ] Declaration of structure in C and C++ is same. But in C when we declare a structure variable of a particular structure, then we have to use the key word struct of the beginning, then the structure name and finally the variable name. e.g. Suppose we define structure as.. struct part struct int modelnumber; or int modelnumber; int partnumber; int partnumber; float cost; float cost; part; And now suppose we want to declare a structure variable part1 of struct part type, then in C the declaration is. struct part part1; While in C++ the keyword struct is not necessary. We can declare part1 structure variable of struct part type as. part part1;

7 C++ Notes 7 By V. D. Gokhale (15) Enumerated data types -> Same like structure, in C while declaring an enumerated data type variable, the word enum is must, while in C++ the word enum is not necessary. e.g. Suppose we want to create an enumerated data type as days which is as follows :- enum days sun, mon, tue, wed, thu, fri, sat; and now we want to declare enumerated variables d1 and d2 of enum days type, then In C the declaration should be -> enum days d1, d2; But in C++ the declaration is -> days d1, d2; [ The word enum is not necessary ]. But there is a serious problem with enum in C++. That, C++ can not work it out in input / output. e.g. enum direction north, south, east, west; direction d1; -> declaration of d1 variable of enum direction. d1 = south; -> Assigning value of south to it. cout << d1; -> Here we expect output as south. But the output arrives as 1, as north = 0and south = 1. Means though we assign the name south to d1, we will get the output of its integer value and not the actual name. Boolean variables are those which give truth / false conditions. In C and C++ there is no such Boolean variable of builded data type. Mainly used to test the output of logical expressions. By using enumerated data type and also by using the fact that falsity = 0 and truth = 1, we can create a Boolean variable as. enum Boolean false,true; -> Here we write false first because internally the first name is assigned to 0. boolean b1; [ bool b = true ] [ Now bool is a data type. Hence there is no need of enum. You can directly say bool b = true; (0 = false and 1 or nonzero = true)] (16) Functions -> It is a unit of program, in which repetitively used program statements are grouped. This unit can be used any where in the program for multiple times. There are 2 reasons for which functions are used (i) Dividing a program into functions is one of the major principle of structured programming. Thus functions provide Conceptual organization of a program. (ii) Any sequence of statements, that appears more than once in a program can be grouped as a function. Thus repetition gets avoided and program size is reduced. Any function has 3 parts

8 C++ Notes 8 By V. D. Gokhale [ i ] Function declaration. [ ii ] Calls to the function and [ iii ] Function definition. [ i ] Function declaration :- Both in C and C++, we can not use a variable, without telling the compiler what it is. Similarly we also can not use function in the program without telling the compiler. To tell the compiler, function must be declared at the beginning of the program. When a function is declared, then this declaration tells the compiler that A function that looks like this is coming up later in the program. This declaration is called as prototype. * Syntax of function declaration -> <return data type> space <user defined name> space <pair of round brackets with list of function parameters data types separated by commas>; e.g. int vijay(double, double); This example indicates that Function is going to return integer type value. The user defined function name is vijay. This function has 2 parameters (arguments) which are of double data types, separated by comma and enclosed in pair of round brackets. The declaration is terminated by semicolon. When a function does not return any value, then the word void should be used in declaration. e.g. void vijay(double, double); This example indicates that the function vijay is returning no value and hence the word void is used. When a function does not have any arguments (parameters) then in the pair of brackets, the word void is used. e.g. int vijay(void); [ By ISO, the function which has no parameters then its parenthesis may be empty ] In this example the function vijay is returning an integer value, but has no parameters hence the word void is enclosed in pair of round brackets. Or int vijay() -> legal by ISO. The function declaration can be done at 3 places in the beginning of program (i) When a function is used only by main() and not by any other sub functions, then the respective function should be declared after main() but before the 1 st program statement. (ii) When a function is used by many sub functions of a program (including or excluding main()), then this respective function should be declared before main().

9 C++ Notes 9 By V. D. Gokhale The declaration of 1 st type (after main ) is known as local function declaration, while.. The declaration of 2 nd type (before main ) is known as global function declaration. (iii) Sometimes a function is used only by one another function and not by main(). Then this respective function can be declared locally in the function which will use it, after the definition of function. Function declaration is also known as function prototype. Calls to the function -> Once declared, the function can be used anywhere and for many times in the function or program, just by maintaining its name. This is known as making call to function. If a function is declared globally, then it can be called by main() and any other sub functions. But if a function is declared locally, then it can be called by only that function, in which it is declared. If it is called by some other function then it causes error. The function which is initiated, is called as called function, while the function in which the called function is used, is called as Calling function. When a function returns any value, then it is assigned to respective variable by = operator. e.g. Suppose function vijay is returning an integer value and if is declared as int vijay, then if we want to assign the returned value to any integer variable like num, then we can call vijay as int num; num = vijay (Parameter list); Here the returned value by vijay function, will be assigned to integer variable num. If a function is not returning any value, means, if it is void, then just mentions its name and brackets with parameter list. But if it has no parameters, then keep brackets empty. Note that -> If the called function has parameters, then they must be of same data types as in declaration and should appear in same order as the declaration. e.g. -> suppose a function is declared as int vijay(int, double); and we want to call it in main(). main() int num1, num; double num2; num = vijay(num1, num2); ( This is a correct call )

10 C++ Notes 10 By V. D. Gokhale o Because 1 st parameter is int and 2 nd is double in decleration. o If call it like vijay(num2, num1); then it will give wrong answer. Because num2 is double and num1 is int, and this is contrasting with the declaration. The function Definition -> To define a function is to write the code of the function. Function definition should be done at the end of program, after the closing brace. Function definition has 5 parts. (i) Function decelerator. (ii) Opening brace of the function. (iii) Function body. (iv) return statement. (v) Closing brace of the function. (i) (ii) (iii) (iv) (v) The line which is used while declaring the function, should be repeated here, with 2 changes. The parameters are written with their data types and respective variable names, as user s wish. Means if the function is declared as int vijay(double, int); then the definition s 1 st line should be. int vijay(double a, int b) -> No semicolon. Here variables are used a and b. These variables are then used in function body. Note that, the decelerator of function definition should not be terminated by semicolon. Then give opening brace. Then write the program statements, which we are going to use. return() statement should be used, if our function is returning any value. The brackets after the keyword return should contain either variable name or the actual value. Closing brace. Note that :- Function decelerator must match the prototype exactly with respect to data type of return value and parameters and no. of parameters. When we use library functions like getch(), printf(), scanf() etc, then there is no need of writing their declarations or definitions,, because they are already

11 C++ Notes 11 By V. D. Gokhale written in header or library files which should be included at the most beginning of our program by #include <> directive. Previously we stated that, before using a function, it must be declared 1 st. But we can eliminate the function declaration, if the function definition appears in the program, before the 1 st call to the function. This approach is better in smaller programs, but in large program declaration and definition approach is much better. Passing Arguments [ Parameters ] To Functions :- (1) Passing by value :- We can pass values either directly or using value containing variables. (i) Passing values directly -> # include <iostream.h> void main() void display(char, int); -> Declaration [ with semicolon ] display( *,89); -> Call by passing values directly. void display(char ch, int nm) -> decelerator [ No Semicolon ] // function body starts int i; for(i=0;i<nm; ++I) cout << ch; // function body ends No return statement as function is void. While calling the function display(), we directly pass values. (ii) Passing variables -> Same above example can be written by passing variables. Just we have to assign * and 89 to variables and pass these variables to display. # include <iostream.h> void main() void display(char, int); declaration. char star;

12 C++ Notes 12 By V. D. Gokhale int num; star = * ; num = 89; display(star, num); -> call to function by passing variables The function display() is same as before. Here we are passing * and 89 to display(), but not directly, we 1 st assign * to variable star and 89 to variable num and then we pass star and num to display() function. Passing structure to function -> As like all variables we also can pass a structure variable to function. But as the desired structure is going to be used by both main() and function, it should be visible to function. And for this purpose just declare the desired structure globally [ before main ] and then use structure variables as the like our ordinary variables to pass to any function. (2) Passing by reference :- In the way (1) we saw that arguments [ parameters ] are passed by their values [ either directly or embedded in variables ]. But, there is another way, that we can pass parameters to desired functions not using their values but using their reference. Purpose -> Passing arguments by value makes no changes in original values of variables. Means in previous example we assign * to star variable and 89 to num variable. We pass them to display() function. The function display() copies these values into ch and nm variables respectively and use them in the function. But note that, no change is made to star and num, though changes can be made to ch and num. Though above way is safest, sometimes we may need to deal with original variables ( star and num in above example ). In such cases, when by using a function we want to change the original values, we should use pass by reference method. There is another advantage of using pass by reference method, is that, by pass by value method we can return only one value at a time from that function. But by using pass by reference method, we can force the function to return multiple values at a time. Method -> To indicate the compiler that, we are using reference method,. ampersand (&) sign is used. Changes are to be made in declaration and declarator only not in call. In declaration the data type which you want to pass by reference should be immediately terminated by & sign.

13 C++ Notes 13 By V. D. Gokhale E.g. int vijay(double, float, char); -> value method. Suppose you want to pass float data type by reference, then. int vijay(double, float&, char); -> Reference method. Here the desired data type is immediately followed by & sign. While writing declarator in function definition we write data type and desired variable name too. Just terminated the data type by & sign. The declarator of above example will be. int vijay(double n1, float& n2, char ch) funtion body; return(variable name); float& n2 :- Here too, the data type is immediately followed by & then a space and then the variable name is written. Note -> In C we use & as Address off operator and at the beginning of the variable, so as to indicate the address of that variable in the computer s memory. But in C++ the ampersand is used after the data type [ as like in C, it has no connection with variable name ] to indicate the reference and not the address. These 2 methods Passing by value and passing by reference can be well explained with an example. Suppose you call a painter to paint your house. Then to tell the painter about the wall, the paint, the color is passing by value, while painter comes in the house and does all things as it is without your intimation is passing by reference. Passing structure by reference is same as other variables -> (1) Declare structure globally. (2) In function declaration write structure name in the arguments list and immediate to that name write &. (3) Make usual call to the function, passing structure variable name as usual. (4) In function definition, while writing function declarator, write structure name, then &, then space and then the desired structure variable name, which you are going to use in the function body.

14 C++ Notes 14 By V. D. Gokhale Note -> In C reference do not exist. In C the same purpose is saved by pointers. But in C++ there are reference as well as pointers too. Returning from function :- (A) Returning values from functions :- We write any function to get some answer. This answer is usually returned from that particular function. The return statement -> When we want to return an answer from the function, 2 cases can take place Either the answer variable is already declared globally, then there is no need of mentioning the name of that answer variable along with return statement. In the program, after function call just write the answer variable name either in cout or in equation, you will get proper change in that variable, done by the function. Or the answer variable is declared locally, in the function, and we want to return this answer to the main program, then this answer variable is written in front of return statement by 2 ways. (i) return <answer variable name>; e.g. return kg; (ii) return (<answer variable name>); e.g. return(kg); Use of brackets is optional. Note :- (1) When a function returns some answer then the return data type must be indicated in function declaration and in function declarator. (2) If function does not return any value then there is no need of return statement. But such functions must be indicated by void term both in declaration and in declarator. (3) If function is not returning any value and if void is not mentioned, then compiler will consider this function as integer returning function by default. And if in such cases return statement is not used at the end of function, the compiler will give warning Function should return a value. So either write void to non value returning function or write return; at the end of such function. (4) If function is small, means it contains only one statement or equation, then to avoid unnecessary variable declaration, we can say write that single statement or equation in front of return statement directly. e.g. Using variables Avoiding unnecessary variables float poundtokg(float pnd) float poundtotkg(float pnd)

15 C++ Notes 15 By V. D. Gokhale float val, kg; return * pnd; val = ; kg = val * pnd; Here unnecessary use of val, kg return kg; is avoided by mentioning equation along with return statement directly. Note -> return statement can appear anywhere in the function body but better is to use it as last statement if not unavoidable; Ignoring return value :- If suppose your function return a double type value, and in calling function you do not specify a catcher variable to hold that return value, then function runs smoothly without any problem. But this is an occasional circumstance. Returning structure variable :- As we can return all data type variable, we also can return structure variable too. We do function declaration, starting by the name at return data type as int vijay(double, double);. Here we will use function vijay to return int value. Similarly, when we want to return structure variable from a function, we have to write structure name at the beginning of function declaration and function declarator. As we know that this structure is going to used by main program and function, the function should know it, and hence we should declare the structure globally. While using return statement, then just mention the name of structure variable you want to return from that function. But in the function body structure element must be operated separately and use structure variable name with return statement. Don t use equation structure variable with return statement. (B) Returning by reference from functions -> In procedural programming returning a value not by value itself, but by reference, is not much needed. But in overloaded operator part it is must. The major advantage of returning by reference is that we have mention function calls in our program to the right side of equal operator and not to the left side. But after returning by reference we can use function names on the left side of equal operator too. Method of returning by reference -> (1) In the function declaration, after the return data type, immediately write & the reference operator. Then space and then the function name etc.

16 C++ Notes 16 By V. D. Gokhale Overloaded functions :- (2) In function definition, while writing function declarator do the same thing. Means after return data type, immediately mention & and then proceed as usual. By doing this, the desired function will return the reference of respective data type to your main function. But, while doing this the variable, reference of which you want to use both in main program and in function, must be declared globally and also the function should be declared globally. e.g. # include <iostream.h> int x; Global declaration of both the variable int & setx(); reference of which we want to use and void main() the function as well. int & setx() return x; setx() = 92; -> Function can be used on left side of equal operator. cout << x = \n << x; Here setx() = 92 statement assign value 92 to the variable returned by this function. Now setx() returns integer value of x variable, thus 92 gets assigned to this x and returned to main program which gives output. x = 92. An overloaded function is that function which appears to perform different activities depending on the kind of data sent to it. e.g. # include <iostream.h> void repchar(); Same function name with different arguments void repchar(char); and different function bodies codes. void repchar(char, int); int i;

17 C++ Notes 17 By V. D. Gokhale void main() repchar(); repchar( = ); Repchar( +, 30); void repchar() for(i=0;i<79;++i) cout << * ; cout << endl; -> 1 st call with no parameter. -> 2 nd call with 1 parameter. -> 3 rd call with 2 parameters. No parameter is processed. 1 st code. Loops for 79 times and prints * for 79 times. void repchar(char ch) for(i=0;i<=79;++i) Character parameter = passed but not integer. cout << ch; 2 nd code. cout << endl; Loops for 79 times and prints = sign for 79 times. void repchar(char ch, int n) for(i=0;i<=n;++i) Here both character and integer parameters cout << ch; are passed. cout << endl; 3 rd code. Loops for 30 times and prints + sign for 30 times. In above example same function name repchar is used and declared globally 3 times with different parameters. Function body codes for these 3 declarations are written 3 separate times. 1 st code is written for * character and for looping of 79 times in one single line. 2 nd code is written with one parameter of character type and in call the character = is passed to it. Here too, loop counter is for 79 times in one single line. 3 rd code is written with 2 parameters. One is character type and other is integer type. Here in call the character + is passed and the integer 30 is passed which is used as loop counter. This code gives output of the character + for 30 times in one single line.

18 C++ Notes 18 By V. D. Gokhale The surprising thing is that, same function name, with different parameters and with different function bodies give different outputs. How compiler knows? the answer is though compiler see one function name, it differentiates the same name for 3 different times, because parameters are different for each time. This is knoes as function overloading. To do this -> (1) Same function name should be used. (2) Declarations should be made globally and separately for every time. (3) Function bodies should be written seperatly for every different purpose. o Feature of overloading is not present in C. Different kinds of arguments -> The compiler can also distinguish between overloaded functions with the same number of arguments, provided their type is different. Means suppose there is a function with one argument [parameter] which is a structure variable. Then as usual it will get operated on the passed structure variable. But if we pass one but different kind of variable, then too, the same function will work for float variable too, though the float variable is not structure variable. This overloading happens If the same function with same number of arguments but of different types declared 1 st globally, and Their codes are written separately. e.g. -> # include <iostream.h> struct distance int feet; float inches; ; void convert(distance); arguments void convert(float); types [ one is void main() globally. distance d1; float d2; d1.feet = 5; d1.inches = 10.5; Same function, with same number of (here one argument) but of different struct while other is float ] declared Structure variable is assigned values.

19 C++ Notes 19 By V. D. Gokhale d2 = 76.5; Float variable is assigned value. convert(d1); -> 1 st call with structure parameter. Convert(d2); -> 2 nd call with float parameter. void convert(distance d) cout << d.feet << - << d.inches << \n ; void convert(float d) int f; float i; f = d / 12; i = d f * 12; cout << f << - << i << \n ; Here same function convert is used with one parameter. 1 st time the parameter is a structure variable, but 2 nd time instead of structure variable a float variable is passed. Note that same function with same numbered but different typed variable arguments are declared globally and separately. Also their function bodies are written separately too. Default arguments :- Not only above 2 cases, but if we provide a function its all default arguments, declare it globally and if you forget to give all parameters in its call, then by default arguments it will work with no problems. Arguments :- left -> right -> Pascal calling convention. e.g. -> # include <iostream.h> void repchar(char ch = *, int n = 79); -> Here we declare function globally with global direction at its default parameters too. void main() repchar(); -> 1 st call with no argument. repchar( = ); -> 2 nd call with 1 argument. repchar( +, 30); -> 3 rd call with both arguments.

20 C++ Notes 20 By V. D. Gokhale void repchar(char ch, int n) int i; for(i=0;i<=n;++i) cout << ch; cout << endl; Very Important Either omit all arguments or omit right sided arguments. Never omit first left argument alone. Means repchar(79); will be illegal. This is because compiler looks for arguments left to right. Hence 1 st parameter is left and it is either absent with all other parameters also absent or only it can be present. If there are 3 arguments rule remains same, you can not omit 1 st and 2 nd. Means you can not omit an argument unless you omit argument to its right. Here function repchar is declared globally with character parameter * and integer loop counter 79. These are function s default parameter. While calling repchar, 1 st call is made with no arguments, this call will give output of * for 79 times in one line. 2 nd call is made with only one character parameter =, but no integer parameter is supplied. Though it is, it takes = sign in place of * and takes integer 79 as default and will give output of = signs for 79 times in one line. In 3 rd call we provide both parameters. This time default parameters (* & 79) will not work and output will be of + sign for 30 times in one line. Inline functions -> When we write a function and call it in our main program, compiler when see the call it exist from the main program, jumps to the function code, executes it, take necessary values and rejumps back to the main program. This takes negligible but some times in execution of program. If we still want to save this time and make the program execution faster, then we can use INLINE FUNCTION property. What to do? Generally we declare function at the beginning of program and write the actual function code at the end of closing brace of main program. While converting this usual function into Inline function -> (1) 1 st write the keyword inline and (2) Then write the function code as it is with declarator function body as it is but globally means before main(). So that function should be seen by the compiler before the 1 st call to it.

21 C++ Notes 21 By V. D. Gokhale e.g. -> By ordinary way # include <iostream.h> void main() double convert(double); -> Usual function declaration double ang; ang = ; ang = convert(ang); -> Usual function call cout << angle = << ang << \n ; double convert(double an) -> usual function definition with declarator while(an < 0.0) an = an ; while(an >= 360.0) an = an 360.0; return(an); This is just an example of inline function, actually looping structure like for, while, do.. while are not allowed in inline functions. By making INLINE FUNCTION :- # include <iostream.h> inline double convert(double an) The function definition with declarator is written globally, before main and with while(an < 0.0) keyword inline. an = an ; while(an >= 360.0) an = an 360.0; return(an); void main() double ang; ang = ; ang = convert(ang);

22 C++ Notes 22 By V. D. Gokhale cout << Angle = << ang << \n ; Making a function INLINE :- (1) Compiler does not jump to function code, but makes the function body as a part of program whenever call is made. (2) There is no need of separate declaration at the beginning of program. (3) Speed of execution gets increased as there are no jumps. (4) But make those functions inline which are short means of one or two lines. CLASSES AND OBJECTS o Read structures in C 1 st and then proceed. In past C++ was termed as C with classes. This nomenclature shows that classes are the key features of C++ classes are just like structures. Structures is used to group the data items together while class is used to group data and related functions together. Though this is the normal usage of structure, strictly speaking, structure also can be used to group data and function together. But the key feature of C++ is data hiding. Means in a class we can make data as private, so that the respective data is accessible only by the class, in which it is declared. [ Data hiding is also know as Data Encapsulation] Hence in C++, data and function are private by default, while these are public in structure by default. Classes and objects :- Placing data and functions together into a single entity is the central idea of Object Oriented Programming [OOP], which gives birth to the idea of classes and objects. Suppose we declare an integer variable num as int num; Then we can say that num is a variable which is supported to store any integer value only. Similarly when we declare a structure variable, we declare it with structure name and then desired variable name. e.g. struct vijay int num; -> Structure definition (vijay).

23 C++ Notes 23 By V. D. Gokhale ; float val; void main() vijay v1, v2; -> Structure variable declaration (v1, v2 of vijay type) On the same line class is defined and then its variable are declared. Variables of a class is known as objects. While defining a class, the differences with structure definition are (1) Replace the word struct by the word class. (2) Make data items private. [ This is the in general rule. If desired you can make the data public. But as encapsulation of data is the major feature of C++, generally all data items are made private. ] (3) Make functions, related with the data as public. [ This is also a in general rule. If desired, you can make functions private too. ] (4) Opening and closing braces, with termination by semicolon are similar as like structure declaration. (5) Then, in main while declaring class variable [ Onwards we are going to call them as objects ] i.e. objects 1 st write the class name and then write the desired object name. If there are more than one object, then separate object names by semicolon and after declaration of objects semicolon should be given at the end of statement. [ Similar to structure variable declaration]. Thus, general syntax of class and object is :- class class-name -> 1 st type the keyword class and then desired name of the class. -> Opening brace. Access specifier; -> Type the keyword private or public or protected, followed by colon; data; -> Type data items with their types and finally semicolon. Functions; -> Type function names with their return types and finally by semicolon.

24 C++ Notes 24 By V. D. Gokhale Access specifier; -> Data; -> So on. Functions; -> Object List; -> Closing brace with either list of objects declare here terminated semicolon or just give semicolon and declare object list in main(). or void main() class name object list separated by commas; -> If you don t declare object list at the closing brace of class, then declare it in main as 1 st give class name. Then give object name [ if more than 1 object, then separate by commas ]. Finally semicolon. e.g. # include <iostream.h> class smallobj -> The keyword class followed by class name. -> Opening braces. private : -> Access specifier. int somedata; -> Data with its data type and semicolon termination. public : -> Access specifier with colon termination. void setdata(int d) -> Function with its return type and parameter. somedata = d; -> Function body defined in the class. void showdata() -> Another function with its return type with no cout << Data is << arguments and its function body. somedata << \n ; ; -> Closing brace. As no object are declared here, terminated by semicolon. void main() -> main() function.

25 C++ Notes 25 By V. D. Gokhale -> Opening brace of main function. smallobj s1, s2; -> Objects of the class are declared. s1.setdata(1066); -> Function of the 1 st object. s2.setdata(1776); -> Function of the 2 nd object. s1.showdata(); -> Function of the 1 st object. s2.showdata(); -> Function of the 2 nd object. -> Closing brace of main function. Now we will explain all features of class and object with this example :- In this example the class is smallobj which is contain one data item and 2 functions. The data item declared within a class is known as member data. [ As the desired data is member of declared class ] Similarly function declared within a class is known as member function [ As the desired function is member of the declared class ]. An object has the same relationship to a class that a variable has to its data type. Means int num; -> Here num is an integer variable type. smallobj s1; -> Here s1 is t he object of class smallobj type. Thus an object is said to be an instance of a class. In this example, smallobj class is declared before main(). Means classes should be defined globally. Objects of smallobj class are not defined after its declaration. Hence just semicolon is given after the closing brace of smallobj class. If desired we can declare s1 and s2 of class smallobj as. class smallobj class body as before. s1, s2; -> Declaration of objects at the closing brace of class, terminated by semicolon. But, in this example objects s1 and s2 are declared in main with the class name, then object names and ( Separated by comma ) and finally a semicolon. Keywords private and public -> As stated before the key feature of C++ and OOP is data hiding. Means the data within a class can not be accessed by other classes and functions. Such data is made accessible only to that class in which it is declared and thus only respective class member functions can access such data. Thus data hiding is done by the keyword private (followed by semicolon). Now until we use another access specifier like public, all items following the word

26 C++ Notes 26 By V. D. Gokhale private will be private, to the class. [ In C++, the keyword private is optional, means if this keyword is not used, the member items will be automatically considered as private by the compiler.] When we want that, member data or functions of a class should be accessed by any other class of functions then to allow this use the keyword public (followed by semicolon). Then every data item or function, following the word public will be accessible to any other function in main program. [ To facilitate Data Hiding or Data Encapsulation, usually Data Items are made private and functions are made public ] There is another access specifier besides private and public and that specifier is protected, which we will see in Inheritance. Because this keyword is needed only there. As an unwritten rule, though data items are usually declared as private and functions as public, this is not hard and fast. Means if desired we can make data items public and function as private. The data items declared inside the class [ whether private, public or protected ] is known as Member data. Here there is only one data item some data which holds integer variable type and declared as private hence accessible only by member functions of some class and not by others. The function declared inside the class [ whether private, public, or protected ] is known as Member function. In this example setdata and showdata are the 2 member functions, whose function body is defined in the class itself. Note -> Small functions should be declared in the class itself. [ Without the word inline such functions are considered as inline by default ] When the function is bigger, it can be declared elsewhere [ usually after main].to do this (1) 1 st declare the function with its return type and parameter as prototype declaration. (2) Then, after main or after the class - 1 st write return type of the function. - Then the class name, whose member this function is. - Then double colon [ :: ]. - Then function name and its parameter with variable as usual. - Then opening brace, function body and closing brace as usual. Here double colon [ :: ] is known as scope resolution operator. Member functions defined outside the class.

27 C++ Notes 27 By V. D. Gokhale e.g. :- The function setdata can be written by this way too. # include <iostream.h> class smallobj private : int somedata; public : void setdata(int); -> Prototype declaration void showdata() cout << Data is << somedata << \n ; ; void main() as before. void smallobj :: setdata(int d) Function of the class but declared outside the class with return type somedata = d; class name :: function name (parameters) The most important point about functions in class, is the member data items are directly accessible by member functions of respective class. Means in both setdata and show data functions we can use somedata variable without any special declaration, though the functions are written inside or outside the class. The member functions in t his example are written on the same line with braces. Bur if we want to write in usual methods with separate lines we can. This is just to save space. Defining objects -> As stated before objects of a class can be declared at 2 places (1) Either at the closing braces of class (2) Or inside the main function. Declaring objects at the closing brace of class, does not require special

28 C++ Notes 28 By V. D. Gokhale notation of class. Just separate the objects (if more than 1 ) by commas and finally give semicolon. But declaring objects inside the main() requires 1 st the class name and then objects names separated by commas and finally a semicolon. In this example objects s1 and s2 of class smallobj are defined by 2 nd method. Note -> When we declare a class, it just tells compiler, what type of class will appear in future program. But it doesn t create any space in memory. As soon as we declare objects, then memory for that objects gets created in the compiler. Means in above example special memory sets for both s1 and s2 are created separately. Calling member functions of a class program -> Now when we need a function which is member of a class, e.g. setdata(), we can not call it is as usual like void main() setdata(1066); -> Wrong call, meaning less to compiler. Because as we know member functions (like structure members) should be identified by their objects only. Thus if we want to call setdata() function, we should call it with in its objects like. s1.setdata(1066); or s2.setdata(1776); Note -> As computer keeps separate memory for different objects, s1.setdata(1066) and s2.setdata(1776) are 2 separate different calls to the same function. Thus when we call s1.showdata(), it will give output 1066 and when we will call s2.showdata(), it will give output While calling member functions or member data items of an object of a class -> following syntax is used object name. member data or member function Here. Operator is same as structure member operator called as period. In above example, there is 1 member data item and 2 member functions. Similarly in a class, there may be as many data members and

29 C++ Notes 29 By V. D. Gokhale functions as we can. Similarly in above example we define only 2 objects of a class, we can define as many objects as we wish. Not only that, we can define array of objects too. In this case the objects will be differentiated on the basis of their index numbers. e.g. smallobj s[5]; -> This declares 5 objects of smallobj class with s[0], s[1], s[2], s[3], and s[4] differentiation. In this example we use integer type data item. Similarly we can use any type of data item like float, double, char, string, array, structures and unions enums, etc. On the same line, in this example both functions are void ( non returning ), but we can use any type of user defined or library function such as returning any data type or using any data type as parameter. Not only this but we can use 1 class as a data member of some other class, we also can use object returning function or function with object as its parameter. Constructors :- Suppose we have a class, say smallobj and we have 2 items and 2 functions in it. Like. class smallobj int i, somedata; -> Here keyword private is not used, because by default, if no access specifier is used, data is private. public : void setdata(int d); somedata = setdata(); void showdata() cout << Data is << somedata << \n ; Now suppose in main() we define s1, s2, s3 objects of smallobj class as. smallobj s1, s2, s3; Suppose further in program, we need such an operation in which the variable i ( or someone else) is set to 0, then everytime when we use any object s1, we have to write i = 0; In main program, when we wish to use s2 or s3 object then too, for every time before using an object we should explicitly mention i =0; To avoid this repetitive declaration of I = 0, whenever object will be created, we can include this statement in a function and make that function as

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language 1 History C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

More information

BITG 1233: Introduction to C++

BITG 1233: Introduction to C++ BITG 1233: Introduction to C++ 1 Learning Outcomes At the end of this lecture, you should be able to: Identify basic structure of C++ program (pg 3) Describe the concepts of : Character set. (pg 11) Token

More information

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018 C++ Basics Lecture 2 COP 3014 Spring 2018 January 8, 2018 Structure of a C++ Program Sequence of statements, typically grouped into functions. function: a subprogram. a section of a program performing

More information

BLM2031 Structured Programming. Zeyneb KURT

BLM2031 Structured Programming. Zeyneb KURT BLM2031 Structured Programming Zeyneb KURT 1 Contact Contact info office : D-219 e-mail zeynebkurt@gmail.com, zeyneb@ce.yildiz.edu.tr When to contact e-mail first, take an appointment What to expect help

More information

Getting started with C++ (Part 2)

Getting started with C++ (Part 2) Getting started with C++ (Part 2) CS427: Elements of Software Engineering Lecture 2.2 11am, 16 Jan 2012 CS427 Getting started with C++ (Part 2) 1/22 Outline 1 Recall from last week... 2 Recall: Output

More information

Input And Output of C++

Input And Output of C++ Input And Output of C++ Input And Output of C++ Seperating Lines of Output New lines in output Recall: "\n" "newline" A second method: object endl Examples: cout

More information

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute of Technology, Madras Lecture 05 I/O statements Printf, Scanf Simple

More information

Objectives. In this chapter, you will:

Objectives. In this chapter, you will: Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates arithmetic expressions Learn about

More information

PART I. Part II Answer to all the questions 1. What is meant by a token? Name the token available in C++.

PART I.   Part II Answer to all the questions 1. What is meant by a token? Name the token available in C++. Unit - III CHAPTER - 9 INTRODUCTION TO C++ Choose the correct answer. PART I 1. Who developed C++? (a) Charles Babbage (b) Bjarne Stroustrup (c) Bill Gates (d) Sundar Pichai 2. What was the original name

More information

Fast Introduction to Object Oriented Programming and C++

Fast Introduction to Object Oriented Programming and C++ Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming

More information

A Fast Review of C Essentials Part I

A Fast Review of C Essentials Part I A Fast Review of C Essentials Part I Structural Programming by Z. Cihan TAYSI Outline Program development C Essentials Functions Variables & constants Names Formatting Comments Preprocessor Data types

More information

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space.

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space. Chapter 2: Problem Solving Using C++ TRUE/FALSE 1. Modular programs are easier to develop, correct, and modify than programs constructed in some other manner. ANS: T PTS: 1 REF: 45 2. One important requirement

More information

CHAPTER 4 FUNCTIONS. 4.1 Introduction

CHAPTER 4 FUNCTIONS. 4.1 Introduction CHAPTER 4 FUNCTIONS 4.1 Introduction Functions are the building blocks of C++ programs. Functions are also the executable segments in a program. The starting point for the execution of a program is main

More information

CSCI 1061U Programming Workshop 2. C++ Basics

CSCI 1061U Programming Workshop 2. C++ Basics CSCI 1061U Programming Workshop 2 C++ Basics 1 Learning Objectives Introduction to C++ Origins, Object-Oriented Programming, Terms Variables, Expressions, and Assignment Statements Console Input/Output

More information

Introduction to C++ Systems Programming

Introduction to C++ Systems Programming Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions

More information

ADARSH VIDYA KENDRA NAGERCOIL COMPUTER SCIENCE. Grade: IX C++ PROGRAMMING. Department of Computer Science 1

ADARSH VIDYA KENDRA NAGERCOIL COMPUTER SCIENCE. Grade: IX C++ PROGRAMMING. Department of Computer Science 1 NAGERCOIL COMPUTER SCIENCE Grade: IX C++ PROGRAMMING 1 C++ 1. Object Oriented Programming OOP is Object Oriented Programming. It was developed to overcome the flaws of the procedural approach to programming.

More information

Lab # 02. Basic Elements of C++ _ Part1

Lab # 02. Basic Elements of C++ _ Part1 Lab # 02 Basic Elements of C++ _ Part1 Lab Objectives: After performing this lab, the students should be able to: Become familiar with the basic components of a C++ program, including functions, special

More information

CS242 COMPUTER PROGRAMMING

CS242 COMPUTER PROGRAMMING CS242 COMPUTER PROGRAMMING I.Safa a Alawneh Variables Outline 2 Data Type C++ Built-in Data Types o o o o bool Data Type char Data Type int Data Type Floating-Point Data Types Variable Declaration Initializing

More information

C++ Programming: From Problem Analysis to Program Design, Third Edition

C++ Programming: From Problem Analysis to Program Design, Third Edition C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine

More information

A A B U n i v e r s i t y

A A B U n i v e r s i t y A A B U n i v e r s i t y Faculty of Computer Sciences O b j e c t O r i e n t e d P r o g r a m m i n g Week 4: Introduction to Classes and Objects Asst. Prof. Dr. M entor Hamiti mentor.hamiti@universitetiaab.com

More information

Programming. C++ Basics

Programming. C++ Basics Programming C++ Basics Introduction to C++ C is a programming language developed in the 1970s with the UNIX operating system C programs are efficient and portable across different hardware platforms C++

More information

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING OBJECT ORIENTED PROGRAMMING STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING 1. Object Oriented Programming Paradigms 2. Comparison of Programming Paradigms 3. Basic Object Oriented Programming

More information

6.096 Introduction to C++ January (IAP) 2009

6.096 Introduction to C++ January (IAP) 2009 MIT OpenCourseWare http://ocw.mit.edu 6.096 Introduction to C++ January (IAP) 2009 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. Welcome to 6.096 Lecture

More information

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols. EEE-117 COMPUTER PROGRAMMING Basic Elements of C++ Objectives General Questions Become familiar with the basic components of a C++ program functions, special symbols, and identifiers Data types Arithmetic

More information

The C++ Language. Arizona State University 1

The C++ Language. Arizona State University 1 The C++ Language CSE100 Principles of Programming with C++ (based off Chapter 2 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

More information

Maciej Sobieraj. Lecture 1

Maciej Sobieraj. Lecture 1 Maciej Sobieraj Lecture 1 Outline 1. Introduction to computer programming 2. Advanced flow control and data aggregates Your first program First we need to define our expectations for the program. They

More information

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING Dr. Shady Yehia Elmashad Outline 1. Introduction to C++ Programming 2. Comment 3. Variables and Constants 4. Basic C++ Data Types 5. Simple Program: Printing

More information

Chapter 15 - C++ As A "Better C"

Chapter 15 - C++ As A Better C Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference

More information

2 nd Week Lecture Notes

2 nd Week Lecture Notes 2 nd Week Lecture Notes Scope of variables All the variables that we intend to use in a program must have been declared with its type specifier in an earlier point in the code, like we did in the previous

More information

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay C++ Basics Data Processing Course, I. Hrivnacova, IPN Orsay The First Program Comments Function main() Input and Output Namespaces Variables Fundamental Types Operators Control constructs 1 C++ Programming

More information

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces Basic memory model Using functions Writing functions Basics Prototypes Parameters Return types Functions and memory Names and namespaces When a program runs it requires main memory (RAM) space for Program

More information

Creating a C++ Program

Creating a C++ Program Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer. 1 Creating a C++ Program created using an

More information

UEE1302 (1102) F10: Introduction to Computers and Programming

UEE1302 (1102) F10: Introduction to Computers and Programming Computational Intelligence on Automation Lab @ NCTU Learning Objectives UEE1302 (1102) F10: Introduction to Computers and Programming Programming Lecture 00 Programming by Example Introduction to C++ Origins,

More information

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++ CHAPTER 9 C++ 1. WRITE ABOUT THE BINARY OPERATORS USED IN C++? ARITHMETIC OPERATORS: Arithmetic operators perform simple arithmetic operations like addition, subtraction, multiplication, division etc.,

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

Interview Questions of C++

Interview Questions of C++ Interview Questions of C++ Q-1 What is the full form of OOPS? Ans: Object Oriented Programming System. Q-2 What is a class? Ans: Class is a blue print which reflects the entities attributes and actions.

More information

The sequence of steps to be performed in order to solve a problem by the computer is known as an algorithm.

The sequence of steps to be performed in order to solve a problem by the computer is known as an algorithm. CHAPTER 1&2 OBJECTIVES After completing this chapter, you will be able to: Understand the basics and Advantages of an algorithm. Analysis various algorithms. Understand a flowchart. Steps involved in designing

More information

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank 1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A. integer B 1.427E3 B. double D "Oct" C. character B -63.29 D. string F #Hashtag

More information

Chapter 1 Introduction to Computers and C++ Programming

Chapter 1 Introduction to Computers and C++ Programming Chapter 1 Introduction to Computers and C++ Programming 1 Outline 1.1 Introduction 1.2 What is a Computer? 1.3 Computer Organization 1.7 History of C and C++ 1.14 Basics of a Typical C++ Environment 1.20

More information

Introduction to C++ (Extensions to C)

Introduction to C++ (Extensions to C) Introduction to C++ (Extensions to C) C is purely procedural, with no objects, classes or inheritance. C++ is a hybrid of C with OOP! The most significant extensions to C are: much stronger type checking.

More information

Basic Elements of C. Staff Incharge: S.Sasirekha

Basic Elements of C. Staff Incharge: S.Sasirekha Basic Elements of C Staff Incharge: S.Sasirekha Basic Elements of C Character Set Identifiers & Keywords Constants Variables Data Types Declaration Expressions & Statements C Character Set Letters Uppercase

More information

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

Quiz Start Time: 09:34 PM Time Left 82 sec(s) Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

PROGRAMMING IN C++ COURSE CONTENT

PROGRAMMING IN C++ COURSE CONTENT PROGRAMMING IN C++ 1 COURSE CONTENT UNIT I PRINCIPLES OF OBJECT ORIENTED PROGRAMMING 2 1.1 Procedure oriented Programming 1.2 Object oriented programming paradigm 1.3 Basic concepts of Object Oriented

More information

Object Oriented Design

Object Oriented Design Object Oriented Design Lecture 3: Introduction to C++ (Continue) Examples using declarations that eliminate the need to repeat the std:: prefix 1 Examples using namespace std; enables a program to use

More information

CS201 Latest Solved MCQs

CS201 Latest Solved MCQs Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A.

1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A. Engineering Problem Solving With C++ 4th Edition Etter TEST BANK Full clear download (no error formating) at: https://testbankreal.com/download/engineering-problem-solving-with-c-4thedition-etter-test-bank/

More information

5.3.1 Different Numbers of Arguments Example:

5.3.1 Different Numbers of Arguments Example: 5.3 Overloaded Functions An overloaded function appears to perform different activities depending on the kind of data sent to it. It performs one operation on one kind of data but another operation on

More information

INTRODUCTION 1 AND REVIEW

INTRODUCTION 1 AND REVIEW INTRODUTION 1 AND REVIEW hapter SYS-ED/ OMPUTER EDUATION TEHNIQUES, IN. Programming: Advanced Objectives You will learn: Program structure. Program statements. Datatypes. Pointers. Arrays. Structures.

More information

Data Types and Variables in C language

Data Types and Variables in C language Data Types and Variables in C language Basic structure of C programming To write a C program, we first create functions and then put them together. A C program may contain one or more sections. They are

More information

Preview from Notesale.co.uk Page 6 of 52

Preview from Notesale.co.uk Page 6 of 52 Binary System: The information, which it is stored or manipulated by the computer memory it will be done in binary mode. RAM: This is also called as real memory, physical memory or simply memory. In order

More information

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary GATE- 2016-17 Postal Correspondence 1 C-Programming Computer Science & Information Technology (CS) 20 Rank under AIR 100 Postal Correspondence Examination Oriented Theory, Practice Set Key concepts, Analysis

More information

Computer Programming : C++

Computer Programming : C++ The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2003 Muath i.alnabris Computer Programming : C++ Experiment #1 Basics Contents Structure of a program

More information

Computer Programming & Problem Solving ( CPPS ) Turbo C Programming For The PC (Revised Edition ) By Robert Lafore

Computer Programming & Problem Solving ( CPPS ) Turbo C Programming For The PC (Revised Edition ) By Robert Lafore Sir Syed University of Engineering and Technology. Computer ming & Problem Solving ( CPPS ) Functions Chapter No 1 Compiled By: Sir Syed University of Engineering & Technology Computer Engineering Department

More information

Understanding main() function Input/Output Streams

Understanding main() function Input/Output Streams Understanding main() function Input/Output Streams Structure of a program // my first program in C++ #include int main () { cout

More information

Chapter 2: Introduction to C++

Chapter 2: Introduction to C++ Chapter 2: Introduction to C++ Copyright 2010 Pearson Education, Inc. Copyright Publishing as 2010 Pearson Pearson Addison-Wesley Education, Inc. Publishing as Pearson Addison-Wesley 2.1 Parts of a C++

More information

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen Chapter 2: Introduction to C++ 2.1 Parts of a C++ Program Copyright 2009 Pearson Education, Inc. Copyright 2009 Publishing Pearson as Pearson Education, Addison-Wesley Inc. Publishing as Pearson Addison-Wesley

More information

Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team

Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team Question No: 1 ( Marks: 2 ) Write a declaration statement for an array of 10

More information

Functions. Lecture 6 COP 3014 Spring February 11, 2018

Functions. Lecture 6 COP 3014 Spring February 11, 2018 Functions Lecture 6 COP 3014 Spring 2018 February 11, 2018 Functions A function is a reusable portion of a program, sometimes called a procedure or subroutine. Like a mini-program (or subprogram) in its

More information

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords. Chapter 1 File Extensions: Source code (cpp), Object code (obj), and Executable code (exe). Preprocessor processes directives and produces modified source Compiler takes modified source and produces object

More information

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program Chapter 2: Introduction to C++ 2.1 Parts of a C++ Program Copyright 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Parts of a C++ Program Parts of a C++ Program // sample C++ program

More information

CS3157: Advanced Programming. Outline

CS3157: Advanced Programming. Outline CS3157: Advanced Programming Lecture #12 Apr 3 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline Intro CPP Boring stuff: Language basics: identifiers, data types, operators, type conversions, branching

More information

CE221 Programming in C++ Part 1 Introduction

CE221 Programming in C++ Part 1 Introduction CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab

More information

Programming with C++ Language

Programming with C++ Language Programming with C++ Language Fourth stage Prepared by: Eng. Samir Jasim Ahmed Email: engsamirjasim@yahoo.com Prepared By: Eng. Samir Jasim Page 1 Introduction: Programming languages: A programming language

More information

Introduction to C ++

Introduction to C ++ Introduction to C ++ Thomas Branch tcb06@ic.ac.uk Imperial College Software Society October 18, 2012 1 / 48 Buy Software Soc. s Free Membership at https://www.imperialcollegeunion.org/shop/ club-society-project-products/software-products/436/

More information

ME240 Computation for Mechanical Engineering. Lecture 4. C++ Data Types

ME240 Computation for Mechanical Engineering. Lecture 4. C++ Data Types ME240 Computation for Mechanical Engineering Lecture 4 C++ Data Types Introduction In this lecture we will learn some fundamental elements of C++: Introduction Data Types Identifiers Variables Constants

More information

Programming for Engineers Introduction to C

Programming for Engineers Introduction to C Programming for Engineers Introduction to C ICEN 200 Spring 2018 Prof. Dola Saha 1 Simple Program 2 Comments // Fig. 2.1: fig02_01.c // A first program in C begin with //, indicating that these two lines

More information

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

COMP322 - Introduction to C++ Lecture 02 - Basics of C++ COMP322 - Introduction to C++ Lecture 02 - Basics of C++ School of Computer Science 16 January 2012 C++ basics - Arithmetic operators Where possible, C++ will automatically convert among the basic types.

More information

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING THROUGH C++ Practical: OOPS THROUGH C++ Subject Code: 1618407 PROGRAM NO.1 Programming exercise on executing a Basic C++

More information

Program Organization and Comments

Program Organization and Comments C / C++ PROGRAMMING Program Organization and Comments Copyright 2013 Dan McElroy Programming Organization The layout of a program should be fairly straight forward and simple. Although it may just look

More information

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter

More information

Chapter 2, Part I Introduction to C Programming

Chapter 2, Part I Introduction to C Programming Chapter 2, Part I Introduction to C Programming C How to Program, 8/e, GE 2016 Pearson Education, Ltd. All rights reserved. 1 2016 Pearson Education, Ltd. All rights reserved. 2 2016 Pearson Education,

More information

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004 GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004 Functions and Program Structure Today we will be learning about functions. You should already have an idea of their uses. Cout

More information

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Computer Programming Basic Control Flow - Loops Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Objectives To learn about the three types of loops: while for do To avoid infinite

More information

UNIT-2 Introduction to C++

UNIT-2 Introduction to C++ UNIT-2 Introduction to C++ C++ CHARACTER SET Character set is asset of valid characters that a language can recognize. A character can represents any letter, digit, or any other sign. Following are some

More information

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program 1 By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program variables. Apply C++ syntax rules to declare variables, initialize

More information

printf( Please enter another number: ); scanf( %d, &num2);

printf( Please enter another number: ); scanf( %d, &num2); CIT 593 Intro to Computer Systems Lecture #13 (11/1/12) Now that we've looked at how an assembly language program runs on a computer, we're ready to move up a level and start working with more powerful

More information

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol. 1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol. B. Outputs to the console a floating point number f1 in scientific format

More information

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++ CS101: Fundamentals of Computer Programming Dr. Tejada stejada@usc.edu www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++ 10 Stacks of Coins You have 10 stacks with 10 coins each that look and feel

More information

+2 Volume II OBJECT TECHNOLOGY OBJECTIVE QUESTIONS R.Sreenivasan SanThome HSS, Chennai-4. Chapter -1

+2 Volume II OBJECT TECHNOLOGY OBJECTIVE QUESTIONS R.Sreenivasan SanThome HSS, Chennai-4. Chapter -1 Chapter -1 1. Object Oriented programming is a way of problem solving by combining data and operation 2.The group of data and operation are termed as object. 3.An object is a group of related function

More information

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University AN OVERVIEW OF C, PART 3 CSE 130: Introduction to Programming in C Stony Brook University FANCIER OUTPUT FORMATTING Recall that you can insert a text field width value into a printf() format specifier:

More information

C: How to Program. Week /Mar/05

C: How to Program. Week /Mar/05 1 C: How to Program Week 2 2007/Mar/05 Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers

More information

Unit 1 : Principles of object oriented programming

Unit 1 : Principles of object oriented programming Unit 1 : Principles of object oriented programming Difference Between Procedure Oriented Programming (POP) & Object Oriented Programming (OOP) Divided Into Importance Procedure Oriented Programming In

More information

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture 04 Programs with IO and Loop We will now discuss the module 2,

More information

Chapter 1 INTRODUCTION

Chapter 1 INTRODUCTION Chapter 1 INTRODUCTION A digital computer system consists of hardware and software: The hardware consists of the physical components of the system. The software is the collection of programs that a computer

More information

Programming with C++ as a Second Language

Programming with C++ as a Second Language Programming with C++ as a Second Language Week 2 Overview of C++ CSE/ICS 45C Patricia Lee, PhD Chapter 1 C++ Basics Copyright 2016 Pearson, Inc. All rights reserved. Learning Objectives Introduction to

More information

LECTURE 02 INTRODUCTION TO C++

LECTURE 02 INTRODUCTION TO C++ PowerPoint Slides adapted from *Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* Copyright 2012 Pearson Education Inc. COMPUTER PROGRAMMING LECTURE 02 INTRODUCTION

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

1. In C++, reserved words are the same as predefined identifiers. a. True

1. In C++, reserved words are the same as predefined identifiers. a. True C++ Programming From Problem Analysis to Program Design 8th Edition Malik TEST BANK Full clear download (no formatting errors) at: https://testbankreal.com/download/c-programming-problem-analysis-program-design-8thedition-malik-test-bank/

More information

Cpt S 122 Data Structures. Introduction to C++ Part II

Cpt S 122 Data Structures. Introduction to C++ Part II Cpt S 122 Data Structures Introduction to C++ Part II Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Objectives Defining class with a member function

More information

Variables. Data Types.

Variables. Data Types. Variables. Data Types. The usefulness of the "Hello World" programs shown in the previous section is quite questionable. We had to write several lines of code, compile them, and then execute the resulting

More information

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program Syntax What the Compiler needs to understand your program 1 Pre-Processing Any line that starts with # is a pre-processor directive Pre-processor consumes that entire line Possibly replacing it with other

More information

Fundamentals of Programming Session 4

Fundamentals of Programming Session 4 Fundamentals of Programming Session 4 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2011 These slides are created using Deitel s slides, ( 1992-2010 by Pearson Education, Inc).

More information

Tokens, Expressions and Control Structures

Tokens, Expressions and Control Structures 3 Tokens, Expressions and Control Structures Tokens Keywords Identifiers Data types User-defined types Derived types Symbolic constants Declaration of variables Initialization Reference variables Type

More information

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath UNIT - I Introduction to C Programming Introduction to C C was originally developed in the year 1970s by Dennis Ritchie at Bell Laboratories, Inc. C is a general-purpose programming language. It has been

More information

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p. Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p. 9 Self-Test Exercises p. 11 History Note p. 12 Programming and

More information