Hello!
This introductory lecture contains a few rather simple programs. I wanted to select them as mostly typical for C/C++. Following the traditions, let me start with a sort of "hello world!" code:
If you name this file as in a comment of the top line, the regular way to compile it and
execute might be:
A general information about control statements. C++ provides three types of loop controls: while, do/while, and for. The for control is as popular, as do/end do, or, do/continue in FORTRAN. Three selection controls include a single if structure, a double selection if/else structure, and multiple-selection switch structure. No problems should arise from the first two. As for the last one, below please find modification of the "Hello" code, for which the switch structure is employed.
The name of person whom you would like to forward your greetings.
With using a request of C-function get()
by the input object cin, The most interesting in this program is how the switch structure works. It is enclosed within the while statement. I want to draw your attention to the fact, that all cases should be identified by integer numbers. In "Hello_1" the characters in, let say, line 14 are overloaded in integers. You can easily check this by inserting a new line between lines 15 and 16: cout << name << endl;. For "a" you will arrive at 97, for "A", at 65. Roll a Die
The next example "Roll-a-die" is also predominantly addressed to the Fortran world.
It will show us, how the random number generator works. The loop structure
for, strictly speaking, two
for statements, will be a help, as well as
the array of integer numbers frequency.
The output on your machine might be of the following kind:
Face Frequency
If you execute this program repeatedly the output will be the same. So, it's possible
to conclude that the random number generator creates pseudorandom numbers. That's
right. The reason for this is that rand()
function generates an integer between 0 and RAND_MAX, a symbolic int constant defined in
stdlib.h. For two-byte integers this
constant is at least 32767, for four-byte integers, 2147483647. So, that was a reason why
for having the integers randomly distrubuted between 1 and 6, we used the modulus division,
as in line 15. However, rand()
always selects the same random number series. If you wish to get rid of such a restriction,
use function srand(unsigned int).
You will observe a little improvement, if you insert the following content
at the lines 9 and 10:
In "Roll-a-die" you meet with post- & pre-incrementing. In both cases, the integer number
is incremented by 1, a difference can be briefly described as follows:
Arrays and strings, which we briefly discussed above, are closely related to pointers. So, they should be introducted as well: A pointer is a variable that holds a memory address. Try this simple program:
8. int * ptrValue = & value; The pointer operator (*) is always used in a pointer declaration, and for dereferencing a pointer, as it is done in line 9. This last operation returns a value whose address the pointer holds. The pointer with this sort of a definition is not const, in the code below the pointer holds, first, the address of value1, then, of value2.
7. int * const ptrValue = & value1; Compiler returns an error in this case: Holding the address of value1, ptrValue cannot be changed to point to anything else. The value can be modified through ptrValue, but ptrValue always points to the same memory location. However, if your change looks like this 7. const int * ptrValue = & value1;the program works properly. Now
ptrValue points to
const value, but can be changed itself.
However, trying to modify the value, which pointer holds, like this
The least privilege is granted by a constant pointer to constant data. Syntax is now evident: const int * const ptrValue = & value; One of the most important pointer's task is to manage data on the free store.
In C++ you allocate memory on the free store by using the
new keyword. After finishing with managing data, you must call
delete on the pointer. And remember that
the free store is free, but its resources are limited, so, do not forget to check
whether memory is available. In C a similar management is performed via the key words
malloc and
free.
In lines 6-10 an elementary memory control is imposed. More sofisticated way for the memory control is to use assertion. In this case you should include the standard file 3. #include <assert.h>Then the conditional statement is simply replaced by 7. assert (ptrValue != 0);After checking that no memory problems arise, the address will be displayed due to line 12. In my desktop computer it was 0x00780DA0. In line 13 the dereferenced pointer is used to store data. Line 15 is our farewell to the pointer. After deleting it, be careful: do not use it again in the program. Towards ReferencesA reference is an alias: creating a reference, you initialize it with target's name. From that moment on, the reference acts as an alternative name for the target, and anything you do to the reference is done to the target.
The output is easy to anticipate: 5 5 56 6 6 7 7 7
An easy rule for dealing with references: if you declare them, but do not initialize,
a compile-time error comes.
What should we know about functions is that
Let us consider now the swap function which performs a permutation of arguments by value. I draw your attention to the fact that the function should be declared and defined, like we did this with variables.
You will get the output, which looks like this: In Main: Before swap: x = 5, y = 7In Swap: Before swap: x = 5, y = 7 In Swap: After swap: x = 7, y = 5 In Main: After swap: x = 5, y = 7 In spite of our efforts to swap the variables, they remained unchanged. That is because local copies were made in the swap function. Let us look, what happens, if we pass the arguments by reference. Passing Arguments in Functions by Reference Using Reference
Now you get the following output: In Main: Before swap: x = 5, y = 7In Swap: Before swap: rX = 5, rY = 7 In Swap: After swap: rX = 7, rY = 5 In Main: After swap: x = 7, y = 5 We reached our goal. The variables exchanged by their values. And this happened, because we manipulated with references. Remember, that references are aliases of corresponding variables? So, that was just our case: Manipulating with refrences, we did this with the original variables as well. Passing Arguments in Functions by Reference Using Pointers
The program is not finished. So, it will be your exercize to complete it. InterludeThe final part of this Introductory Day involves a brief info about Recursive functions, Arrays, and Strings. The Fibonacci Series in Recursion There exist many modifications of this Series. The original set was proposed long time ago by italian mathematician Fibonacci. Now you can meet with the Fibonacci numbers in different sorts of applications, e.g., in biology, quantum chaos, etc. Let us define the Fibonacci series recursively: fibonacci(0)=0fibonacci(1)=1 fibonacci(n)=fibonacci(n-1)+fibonacci(n-2) The recursive program looks very compact, although a rich content is hidden in a recursion procedure:
An exercise for you again: try to right your own program, using the C++ syntax, which would determine the Fibonacci numbers iteratively. A word of caution about recursive programs: each level of recursion in the example from above results in doubling of the number of variable calls. Although recursive procedures are very readable and well-organized, the number of calls, when executing, grows exponentially. Arrays
For this moment let me confine to the syntax of arrays.
Remember, when you declare the array like this
Multiple-dimensional arrays I would like to illustrate in two dimensions. The array int z[2][3] may be interpreted as two-dimensional matrix where the second subscript is related to columns (from 0 to 2), and the first subscript to rows (from 0 to 1). Notice that the function definition specifies the parameters of the mentioned above array as int z[][3], for example, if function void printArray calls it, the syntax should be as follows: void printArray(int z[] [3]){ ...function's body...} A possible initialization of the array int z[2] [3] = { {1, 2, 3}, {4, 5, 6} };might be re-written as follows int z[2] [3] = { 1, 2, 3, 4, 5, 6 };Pointers & Arrays: Relationship
the array name without a subscript is a pointer to the first element of the array.
This is equivalent to rPtr = &r[0];The pointer arithmetic definition is based on this analogy, for example, you may dereference the tenth element of the array with the pointer expression, *(rPtr + 9);or, even like this *(r + 9);String as a Character Array We met already with strings as character arrays, however, with no accompanying exlanations. Recall, in hello.cpp we declared string name as char name[80];This means that with the statement cin >> name;we may store from a keyboard a character array capable of storing up to 79 characters and a terminating null. If I decide to store my name into that string, the structure of the character array will be as follows: name = {'G','e','n','n','a','d','y','\0', .... }The meaningless part of the array is denoted by dots. Try a program echoo.cpp. It and its modifications are for visualizing a character array structure.
This program returns you a string, that you stored, as a vertical echo. Comment line 10 and
uncomment line 11. The structure of a complete array, its meaning and meaningless parts,
will be visualized.
Character arrays can be initialized by using the following feature of arrays: If the array size is omitted from a declaration with an initialized list, the number of elements in the array will be the number of elements in the initialized list. Let me illustrate this with my name again: char name[] = {'G','e','n','n','a','d','y','\0'};The array size is evidently 8. This kind of initialization can be done in a much easier manner: char name[] = "Gennady";Although the number of literal characters in name is 7, the length of name is 8 because of a terminating null. Strings via Pointers Initialization of my name can be also done with a variable of type char *: char *namePtr = "Gennady";This last declaration creates pointer variable namePtr that points to the string Gennady somewhere in memory. Manipulating Strings Here I collected an elementary information on how to manipulate strings with string library functions. First two are strcpy and strncpy. How they work is shown in copy.cpp:
Functions strcat and strncat append the second argument, a string, to its first argument, a character array. See the example below.
A couple of notes in connection with append.cpp: first, unsigned int and unsigned long types may be substituted by the size_t type, which is defined in the standard C library. Second, appending with strcat and strncat is accompanied by replacing a terminating null of the first argument by the first character of the second argument. A terminating null is appended to the result. strlen is a function of int type. It returns the number of characters within a string: terminating null is not included. Exersizes 1. Find errors, if they exist, in the following fragments: (a) char name[80](b) int frequency[] = {1, 2, 3, 4, 5}; (c) int a[6] = {0}; int i = 1; while (i < 6) a[i++] = i; cout << a << endl; (d) #include <iostream.h>; main() { cout << srand(time(NULL)) << endl; return 0; } (e) int *ptrValue = 0; int &rValue; (f) int value = 5; int &rValue = value; int *ptrValue = rValue; (g) int swap (int v, int w) { int tmpr; tmpr = v; v = w; w = tmpr; } (h) char name[80]; cin >> name << endl; while (name !='0') { case '1': cout << "Hello everybody!" << endl break; default: cout << "Enter 0, or, 1" << endl break; } cout << "Goodbye everybody!"; 2. Write a program, which will allow you to calculate factorial recursively. 3. What is a difference between two outputs? Make necessary corrections in the case of errors. (a) int a[6] = {0}; int i = 1; while (i < 6) a[i++] = i; (b) int a[6] = {0}; int i = 1; while (i < 6) a[++i] = i; 4. Define void swap(int *,int*) in swap_by_pointer.cpp. 5. Write a program, which will return the Fibonacci numbers iteratively. 6. Write a program, which will tokenize a string: "The introductory day of the C++ course is over". |