Presentation is loading. Please wait.

Presentation is loading. Please wait.

C++ Laboratory Instructor: Andrey Dolgin

Similar presentations


Presentation on theme: "C++ Laboratory Instructor: Andrey Dolgin"— Presentation transcript:

1 C++ Laboratory Instructor: Andrey Dolgin e-mail: phd_ie@yahoo.com
Home page: 20% exam, 80% assignments 3 assignments Don’t copy assignments Obligatory attendance on all labs

2 Computer Structure (inspired by the Matrix)
Is computer clever? What about man? Memory devices bus Processor 01+10

3 Language types Computers understand only machine language.
Basically looks like a sequence of 1’s and 0’s. The computer does not understand C. Assembly – machine language with some text codes (still inconvenient). Interpreted languages – Java, Perl. The program is translated into machine language line by line during execution. Compiled languages – C, Pascal, Fortran. The program is translated into machine language before execution

4 High level languages vs. machine languages.
Actually, binary instructions.

5 Why teach C? C is small (only 32 keywords).
lots of C code are available (OS, editors, DB). C doesn’t change much. C is quick (nearly as fast as assembly). C is the basis for many languages (Java, C++). C is one of the easiest languages to learn.

6 Software Development Process
Understand Problem Definition Generalize & Decompose the problem definition Develop Solution Algorithm Write the Code Test and Debug

7 Programming Process Use any text editor to write a program a.cpp
Compile the program a.cpp->a.o C compiler will print error messages and abort Or produce an object file Link the program a.o+b.o+c.o->prog.exe linker will print error messages and abort Or produce an executable program Run the program prog

8 Our first C program Comments are good
/* HelloWorld – An example program */ #include <stdio.h> int main(void) { printf(“Hello, world!\n”); return 0; } Preprocessor directive Includes C standard library main() means “start here” This is an instruction to the compiler to insert the contents of the file stdio.h to the program prior to compilation. This file contains information about the printf fuction. This tells the compiler we are about to define a function named main. main is a special function – it is where the program starts running. Note that all C statements end with a semicolon (;). This is a C statement. This statement calls a function called printf, which causes text to be printed on the screen. Yet another C statement. This one terminates the program and informs the operating system that it has ended successfully. Return 0 from main means our program finished without errors This is a comment – starts with a /* and ends with a */. Comments are used to explain the program to a human reader, and are ignored by the compiler. Curly braces indicate the beginning and end of a block of instructions. Specifically in this case – a function. Brackets define code blocks

9 Keywords of C we need Flow (6) – if, else, return, switch, case,default Loops (5) – for, do, while, break, continue Types (5) – int, float, double, char, void Structures (3) – struct, typedef, union Counting and sizing (2) – enum, sizeof Useful types (3) – unsigned, static, const “Don’t use me” keywords (1) – goto

10 Variables

11 Declaring variables in C
Before using a variable, one must declare it. The declaration first introduces the variable type, then its name. When a variable is declared, its value is undefined.

12 Example Variable Declarations
int i; char c; float f1, f2; float f1=7.0, f2 = 5.2; unsigned int ui = 0;

13 Variable naming rules Letters, digits, underscores
CSE_8a a_very_long_name_that_isnt_very_useful fahrenheit First character cannot be a digit 8a_CSE is not valid! Case sensitive CSE_8a is different from cse_58

14 Data types in C char – a single byte character ‘A’.
short int (or just short) – an integer number, usually 2 bytes (rarely used) 15 . int - an integer number – usually 4 bytes long int (or just long) – an integer number, 4 or 8 bytes (rarely used) float – a single precision real number – usually 4 bytes double – a double precision real number – usually 8 bytes long double - a double precision real number – usually 8 bytes (rarely used) Signed vs. unsigned

15 Memory types Heap .&x .&y Stack x y Loads program in Code memory
Loader start Loads program in Code memory CPU execute Takes each instruction and executes it storing new data values in Stack or Heap Code memory Heap .&x .&y Stack x y

16 printf and scanf printf – prints to the standard output (for example screen). Can also accept variables and print their values. scanf – gets values from the standard input (for example keyboard), and assigns them to variables.

17 printf can print variable values
printf ("z=%d\n", z ); The sequence %d is a special sequence and is not printed! It indicates to printf to print the value of an integer variable written after the printed string.

18 scanf gets input from the user
scanf("%lf", &var); This statement waits for the user to type in a double value, and stores it in the variable named ‘var’. The meaning of ‘&var’ is the address of the variable var in stack. To get 2 doubles from the user, use – scanf("%lf%lf", &var1, &var2);

19 prinft/scanf conversion codes
A %<conversion code> in the printf/scanf string is replaced by a respective variable. %c – a character %d – an integer, %u – an unsigned integer. %f – a float %lf – a double %g – a nicer way to show a double (in printf) %% - the ‘%’ character (in printf)

20 Example /* Get a length in cm and convert to inches */
#include <stdio.h> int main(void) { double cm, inches; printf("Please enter length in centimeters: "); scanf("%lf",&cm); inches = cm / 2.54; printf("This is equal to %g inches\n", inches); return 0; }

21 Exercise Write a program that accepts as input - and outputs -
The Dollar-Shekel exchange rate An integer amount of dollars and outputs - The equivalent amount in Shekels

22 Solution #include <stdio.h> int main(void) {
double shekels, xchange; int dollars; printf("Enter the US$-NIS exchange rate: "); scanf("%lf", &xchange); printf("Enter the amount of dollars: "); scanf("%d", &dollars); shekels = dollars * xchange; printf("%d dollars = %g shekels\n", dollars, shekels); return 0; }

23 Char is also a number! A char variable is used to store a text character: Letters. Digits. Keyboard signs. Non-printable characters. But also small numbers (0 to 255).

24 ASCII (American Standard Code for Information Interchange)
Every character is assigned a numeric code. ‘’ operator in C returns this code, ‘A’=65 ASCII code 0 (NULL character) is important. Note continuous sets of numbers, upper case and lower case characters. Generally, you don't care about the numbers. The ASCII table.

25 Example of char as both a character and a small number
#include <stdio.h> int main(void) { char i = 'b'; printf("i as a character is %c\n", i); printf("i as an integer is %d\n", i); printf("The character after %c is %c\n", i, i + 1); return 0; }

26 Another example /* Get the position of a letter in the abc */
#include <stdio.h> int main(void) { char letter; printf("Please enter a lowercase letter\n"); scanf("%c", &letter); printf("The position of this letter in the abc is %d\n", letter-'a'+1); return 0; }

27 Exercise Write a program that accepts as input – and outputs –
A lowercase letter and outputs – The same letter in uppercase (e.g., if the input is ‘g’, the output should be ‘G’)

28 Solution /* Convert a letter to uppercase */ #include <stdio.h>
int main(void) { char letter; printf("Please enter a lowercase letter\n"); scanf("%c", &letter); printf("This letter in uppercase is %c\n", letter-'a'+’A’); return 0; }

29 Arithmetic operators An operator is an action (in our case, usually a mathematical one) performed on something (e.g. constants, variables). That “something” is called an operand. Common operators: Braces () Assignment = Addition + Subtraction - Multiplication * Division / Modulo %

30 Operations with different types
For example - 3 + 4 = 7 = 7.0 3 / 4 = 3.0 / 4 = 0.75

31 Casting variables Sometimes it is desirable for a variable of one type to be considered as belonging to another in an operation We say the variable is cast to the new type. The casting operator is of the form – (type) For example, (float)i casts the variable i to a float.

32 Casting variables #include <stdio.h> int main(void) {
int a=1, b=2; printf("%d / %d = %d\n", a, b, a/b); printf("%d / %d = %g\n", a, b, (float)a / b); return 0; }

33 Example – find what’s wrong
#include <stdio.h> int main(void) { int a = 10; int b = 20; printf("The average of %d and %d is %d\n", a, b, (a + b) * (1 / 2)); return 0; }

34 Will this work? #include <stdio.h> int main(void) { int a = 10;
int b = 20; printf ("The average of %d and %d is %d\n", a,b, (a + b)*(1.0 / 2)); return 0; }

35 Selection statements

36 Selection Statements Selects statements to execute based on the value of an expression The expression is sometimes called the controlling expression Selection statements: if statement switch statement

37 Selection statements: if
used to execute conditionally a statement or block of code. if (expression) statement If expression is true, statement is executed (what is true?). statement can be replaced by a block of statements, enclosed in curly braces.

38 An example /* This program displays the absolute value of a number given by the user */ #include <stdio.h> int main(void) { double num; printf("Please enter a real number: "); scanf("%lf", &num); if (num<0) num = -num; printf("The absolute value is %g\n", num); return 0; }

39 If-else statement if (expression) statement1 else statement2
if expression is true, statement1 is executed. if expression is false, statement2 is executed both statements can be (and very often are) replaced by blocks of statements (“compound statements”)

40 An example (fragment) int first, second, min; /* … */
if (first < second) { min = first; printf ("The first number is smaller than the second.\n"); } else min = second; printf ("The second number is smaller than the first\n"); printf("The smaller number is equal to %d\n", min);

41 True or false In C, every expression has a numeric value
An expression is ‘true’ when its non-zero If it is zero, it is false Therefore, in the following – if (expression) statement statement is executed if expression is non zero.

42 Relational operators They are –
A == B (Note the difference from A = B) A != B A < B A > B A <= B A >= B The value of logical expression is non-zero if it’s true, zero if it’s false

43 An example int a, b; printf("Enter two Numbers\n");
scanf("%d%d", &a, &b); if (a == b) { printf("The numbers equal %d\n", a); printf("The expression a == b is %d\n", a == b); } else printf("The numbers are not equal\n");

44 The assignment operator =
The assignment operator is also an operator. Hence, expressions involving it have a numeric value This value equals to whatever appears on the right of the assignment operator For example – (x = 4) equals 4 (y = 0) equals 0

45 A very common mistake Very often a programmer might confuse between the equality operator and the assignment operator - if (x==4) … if (x=4) … The second is usually a mistake, but legal in C so the compiler doesn’t call it!

46 Logical operators Allows to evaluate two or more expressions -
!A – ‘not’ - True when A is not, and vice versa. A && B – ‘and’ - True when both A and B are true A || B – ‘or’ (inclusive or) - True when either A or B (or both) are true

47 Else-if if statements distinguish between exactly 2 cases and execute different code in each case The else-if construction allows for a multi-way decision

48 Else-if if (expression) statement else if (expression) else

49 An example if (grade >= 90) printf ("A\n");
else if (grade >= 80) printf ("B\n"); else if (grade >= 70) printf ("C\n"); else if (grade >= 60) printf ("D\n"); else printf ("F\n");

50 The ?: operator expr1 ? expr2 : expr3
If expr1 is true (non-zero), expr2 is evaluated. Otherwise, expr3 is evaluated

51 The ?: operator #include <stdio.h> int main(void) {
int i, j, min; printf("Please enter two numbers: "); scanf("%d%d", &i, &j); min = i<j ? i : j; printf("The minimum between %d and %d is %d\n", i, j, min); return 0; }

52 The switch statement a multiway conditional statement
similar to the if-else if-else "statement" allows the selection of an arbitrary number of choices based on an integer value switch (expression) {   case const-expr: statements   case const-expr: statements   …   default: statements }

53 That grade example again
switch (grade/10) { case 10: case 9: printf ("A\n"); break; case 8: printf ("B\n"); case 7: printf ("C\n"); case 6: printf ("D\n"); default: printf ("F\n"); }

54 Give me a break when the switch transfers to the chosen case, it starts executing statements at that point it will “fall through” to the next case unless you “break” out it causes the program to immediately jump to the next statement after the switch statement

55 Riddle me this Suppose a program’s execution reaches the following line – scanf(“%d%c”, &i, &ch); And suppose the user input is – 100 b What will be the contents of i and ch? Answer i == 100 ch == ‘ ‘ (there’s a space in there)

56 Spaces in scanf One way to overcome this problem is to introduce a space before the %c – scanf(“%d %c”, &i, &ch); The space tells scanf to ignore all whitespace characters that come after the %d is read

57 Loops

58 Loops Used to repeat the same instruction(s) over and over again.
C provides some flexible ways of deciding how many times to loop, or when to exit a loop. for, while, do-while loops.

59 While loops while (condition) { statement(s); }
The statements are executed as long as condition is true When the condition is no longer true, the loop is exited.

60 Example - factorial #include <stdio.h> int main(void) {
int i,n,fact = 1; printf("Enter a number\n"); scanf("%d", &n); i=1; while (i<=n) fact = fact*i; i++; } printf("the factorial is %d\n", fact); return 0; This is a counter Every iteration i is incremented by 1. Equivalent to i=i+1.

61 getchar getchar() gets a single character from the user.
Requires including stdio.h Returns a non-positive number on failure. Similar to scanf. char c; c = getchar(); char c; scanf(“%c”, &c); ====

62 putchar putchar(‘char’) prints out the character inside the brackets.
Requires including stdio.h Similar to printf. char c; putchar(c); char c; printf(“%c”, c); ====

63 Exercise Input – Output – Note – Two integers – A and B
How many times A contains B This is the result of the integer division A/B Note – Do not use the division operator!

64 Solution #include <stdio.h> int main(void) { int a, b, res;
printf("Please enter two numbers.\n"); scanf("%d%d", &a, &b); res = 0; while ( (res+1) * b <= a) res = res + 1; printf("%d / %d = %d", a, b, res); return 0; }

65 Break in a loop When break is encountered, the loop is exited regardless of whether the condition is still true. The program then continues to run from the first line after the while loop. If called within a nested loop, break breaks out of the inner loop only.

66 Continue When continue is encountered, the rest of the loop is ignored. The program then continues to run from the beginning of the loop. Rarely used. Can usually be replaced by an appropriate if-else statement.

67 For loops For loops are controlled by a counter variable.
for( c =init_value;c<=fin_value;c+=increment_value) { loop body; } c is a incremented after every iteration (can also be decreased!) c is a counter.

68 For loops (cont.) Equivalent to while… Any for loop can be converted to while loop and vice versa But some applications are more natural to for, and others to while. If we want to perform something for a predefined number of times, better use for. If we just wait for something to happen (not after a certain number or iterations), better use while.

69 Incremental operators
Used as a short-hand for incrementing (or decrementing) variables. i++ or ++i == i = i + 1 i-- or --i == i = i – 1 i += a == i = i + a i -= a == i = i - a i *= a == i = i * a i /= a == i = i / a

70 Prefix ++i and postfix i++
#include <stdio.h> int main(void) { int i=5; printf("i++=%d\n",i++); //i++=5 printf(“++i=%d\n",++i); //++i=7 return 0; }

71 Exercise Write a program that accepts a number from the user, and checks whether it is prime.

72 Solution (isprime.c) #include <stdio.h> int main(void) {
int i, num; printf("enter a number\n"); scanf("%d", &num); for(i = 2 ; i < num; i++) if (num % i == 0) /* Then we know it's not a prime */ break; if (i < num) printf("%d is not a prime number!\n", num); else printf("%d is indeed a prime number!\n", num); return 0; }

73 Exercise Extend the former program so it accepts a number from the user, and prints out all of the prime numbers up to that number (Hint – gotta use nested loops here...)

74 Solution (listprimes.c)
#include <stdio.h> int main(void) { int i, j, last; printf("enter a number\n"); scanf("%d", &last); for(i = 2; i <= last; i++) for(j = 2 ; j < i; j++) if (i % j == 0) break; if (j == i) printf("the number %d is prime\n", i); } return 0;

75 Exercise Write a program that prints an upside-down half triangle of *. The height of the pyramid is the input. ***** **** *** ** *

76 Solution #include<stdio.h> int main(void) { int i, j, size;
printf(“Please enter a size:\n”); scanf(“%d”,&size); for (i = 1; i <= size; i++) for(j = i; j <= size; j++) printf("*"); printf("\n"); } return 0;

77 Exercise Change the former prime-listing program, so that is displays only the largest prime number which is smaller than or equal to the user’s input.

78 Solution 1 #include <stdio.h> int main(void) { int i, j, last;
int found = 0; /* This indicates whether we found the largest prime */ printf("enter a number\n"); scanf("%d", &last); i = last; while (!found) /* Loop until we find our guy */ for(j = 2 ; j < i; j++) if (i % j == 0) break; if (j == i) /* If this is true then i is prime */ found = 1; else i--; } printf("The largest prime not larger than %d is %d.\n", last, i); return 0;

79 Solution 2 (with break) #include <stdio.h> int main(void) {
int i, j, last; printf("enter a number\n"); scanf("%d", &last); for(i=last;i>1;i--) for(j = 2 ; j < i; j++) if (i % j == 0) break; if (j == i) /* i is prime. We found our guy */ } printf("The largest prime not larger than %d is %d.\n", last, i); return 0;

80 Do while loops do { statement(s) } while (expression);
Similar to while loops Except the condition is evaluated after the loop body The loop body is always executed at least once, even if the expression is never true (equals zero)

81 Example – waiting for legal input
#include <stdio.h> int main(void) { int i; printf("Please enter a positive number.\n"); do { scanf("%d", &i); if (i<=0) printf("That's not a positive number! Try again.\n"); } while (i<=0); /* The program continues.... */ return 0; }

82 Functions

83 Functions a group of declarations and statements that is assigned a name effectively, a named statement block usually has a value a sub-program when we write our program we always define a function named main inside main we can call other functions which can themselves use other functions, and so on…

84 Example - Square This is a function defined outside main
#include <stdio.h> double square(double a) { return a*a; } int main(void) double num; printf("enter a number\n"); scanf("%lf",&num); printf("square of %g is %g\n",num,square(num)); return 0; This is a function defined outside main Here is where we call the function square

85 Why use functions? they can break your problem down into smaller sub-tasks easier to solve complex problems they make a program much easier to read and maintain abstraction – we don’t have to know how a function is implemented to use it generalize a repeated set of instructions we don’t have to keep writing the same thing over and over

86 Characteristics of Functions
return-type name(arg_type1 arg_name1, arg_type2 arg_name2, …) { function body; return value; } int main(void) { } double square(double a) { return a*a; }

87 Return Statement Return causes the execution of the function to terminate and usually returns a value to the calling function The type of the value returned must be the same as the return-type defined for the function (or a ‘lower’ type) If no value is to be returned, the return-type of the function should be set to ‘void’

88 Factorial calculation example
int main(void) { int num; printf("enter a number\n"); scanf("%d",&num); printf("%d!=%d\n",num,factorial(num)); return 0; } #include <stdio.h> int factorial(int n) { int i, fact = 1; for (i=2; i<=n; i++) fact *= i; return fact; }

89 A Detailed Example Write a program that receives a nominator and a denominator from the user, and displays the reduced form of the number. For example, if the input is 6 and 9, the program should display 2/3.

90 Example – solution (step I)
#include <stdio.h> int main(void) { int n, d; printf("Please enter nominator and denominator: "); scanf("%d%d", &n, &d); Calculate n’s and d’s Greatest Common Divisor printf("The reduced form of %d/%d is %d/%d", n, d, n/gcd, d/gcd); return 0; }

91 Example – solution (step II)
#include <stdio.h> int main(void) { int n, d, g; printf("Please enter nominator and denominator: "); scanf("%d%d", &n, &d); g = gcd(n, d); printf("The reduced form of %d/%d is %d/%d", n, d, n/g, d/g); return 0; }

92 Example – solution (step III)
/* Returns the greatest common divisor of its two parameters. Assumes both are positive. The function uses the fact that the if r = mod(y, x) then the gcd of y and x equals the gcd of x and r. */ int gcd(int x, int y) { int tmp; while(x > 0) tmp = x; x = y % x; y = tmp; } return y;

93 The Great Void Sometimes there’s no reason for a function to return a value In these cases, the function return type should be ‘void’ If the ‘return’ keyword is used within such a function it exits the function immediately. No value needs be specified If the function receives no parameters, the parameter list should be replaced by ‘void’

94 Pass-by-value Function arguments are passed to the function by copying their values rather than giving the function direct access to the actual variables A change to the value of an argument in a function body will not change the value of variables in the calling function

95 Scope of variables The scope of a variable is the boundaries within which it can be used in a program. Normally variables are local in scope - this means they can only be used in the function where they are declared. A variable declared within a function is unrelated to variables declared elsewhere, even if they have the same name Global variables can be declared , which can be used in any function. Global variables are a BAD PRACTICE.

96 Wrong way to do it int add_one(int b) { a=b+1; } int main(void)
int a=34,b=1; add_one(b); printf("a = %d, b = %d\n", a, b); return 0;

97 Bad global variable use example
#include<stdio.h> void printRow(int); int i, size; int main(void) { printf(“Please enter a size:\n”); scanf(“%d”,&size); for (i = 1; i <= size; i++) printRow(i); return 0; } void printRow(int length) for(i = length; i <= size; i++) printf("*"); printf("\n"); Variables here are global This program only prints ONE row of stars

98 Function Declaration Most software projects in C are composed of more than one file We want to be able to define the function in one file, and to use it in all files For this reason, the function must be declared in every file in which it’s called, before it’s called for the first time the declaration contains: the function name the data types of the arguments (their names are optional) the data type of the return value

99 Function Declaration #include <stdio.h>
int factorial(int a); /* Function Declaration! */ int main(void){ int num; printf("enter a number\n"); scanf("%d",&num); printf("%d!=%d\n",num,factorial(num)); return 0; } int factorial(int a){ int i,b=1; for(i=1; i<=a; i++) b=b*i; return b;

100 Function Declaration stdio.h actually contains a large set of function declarations The #include directive tells the compiler to insert these declarations into the file, so that these functions could be called

101 The math library A collection of mathematical functions
Need to include the header file math.h (#include <math.h>) Use functions of the library, e.g. double s,p; s=sqrt(p); Declared in math.h : double sqrt ( double x );

102 The math library sin(x), cos(x), tan(x) asin(x), acos(x), atan(x)
x is given in radians asin(x), acos(x), atan(x) log(x) sqrt(x) pow(x,y) – raise x to the yth power. ceil(x), floor(x) …and more


Download ppt "C++ Laboratory Instructor: Andrey Dolgin"

Similar presentations


Ads by Google