Download presentation
Presentation is loading. Please wait.
1
Lecturer: Ami Berler ami@cs.bgu.ac.il Semester A 2010-2011
מעבדת תכנות C++/C Lecturer: Ami Berler Semester A Jhhkjhkguyfuiuol n kjnbklhjhoujhouhoih Communication Systems Engineering - BGU 12 ספטמבר 18
2
Info Page: http://www.cse.bgu.ac.il/Courses/course.asp?ID=484
Course requirements: 4 assignments If the grade of the final exam is at least 56, the final grade is 30% final exam and 70% home assignment. In case of having a grade lower than 56 in the final exam, the final grade is the grade of the final exam. Literature: C Programming Language, Brian W. Kernighan and Dennis M. Ritchie The C++ Programming Language, Bjarne Stroustrup C++ Complete reference, Herb Schildt Communication Systems Engineering - BGU 12 ספטמבר 18
3
Objectives Acquire familiarity with the C and C++ programming languages. Emphasis is placed on Object Oriented Programming (OOP). Working under Unix(Linux) Operating System. Communication Systems Engineering - BGU 12 ספטמבר 18
4
Meetings The first 4-6 meetings introduce the C language syntax and concepts: Types, operators and control flow Functions and program structure Pointers and arrays Structures, dynamic memory and I/O Linked lists Files The remainder of the meetings addresses C++ programming: Object oriented programming concepts Name spaces, statements Classes Operator overloading Inheritance Templates Exceptions Communication Systems Engineering - BGU 12 ספטמבר 18
5
Announcements You need look for announcements in the page of the course. Office hours : Lecturer : Wednesday – 1300 – –Room 305- Building 34 (schedule by mail). Assistant: Monday – – Room 418 – Building 37 Communication Systems Engineering - BGU 12 ספטמבר 18
6
Computer Structure CPU Internal Memory Output Input Mouse Keyboard
Microphone Detectors Monitor Speakers Motors Hard Disk CD / DVD Tape DiskOnKey External Memory Communication Systems Engineering - BGU 12 ספטמבר 18
7
Internal Memory Components
ROM – Read Only Memory An integrated circuit chip containing programs and data that can be accessed and read but cannot be modified (only way specials programs). RAM – Random Access Memory The PC's primary storage area, used to write, store and retrieve information and program instructions which are then passed to the CPU for processing. Communication Systems Engineering - BGU 12 ספטמבר 18
8
Memory Unit : Byte Byte is a unit of digital information. It is an ordered collection of bits (binary digit), in which each bit denotes the binary value of 1 or 0. number of bits used to encode a character of text in the computer, which depended on computer hardware architecture; but today it almost always means eight bits. A byte can represent 28 = 256 distinct values, such as the integers from 0 to 255 ASCII (American Standard Code for Information Interchange) Communication Systems Engineering - BGU 12 ספטמבר 18
9
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 Communication Systems Engineering - BGU 12 ספטמבר 18
10
High level languages vs. machine languages.
Actually, binary instructions. Communication Systems Engineering - BGU 12 ספטמבר 18
11
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. Communication Systems Engineering - BGU 12 ספטמבר 18
12
Software Development Process
Understand Problem Definition Generalize & Decompose the problem definition Develop Solution Algorithm Write the Code Test and Debug Communication Systems Engineering - BGU 12 ספטמבר 18
13
Programming Process Use any text editor to write a program a.c
Compile the program a.c->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 Communication Systems Engineering - BGU 12 ספטמבר 18
14
Writing the code In this course we use the Linux (Unix) operating system . The gcc compiler is a native linux C/C++ compiler We can use a simple text editor (gedit,vim,emacs) or a more evolved integrated development environment (IDE) like netbeans and eclipse, in order to edit the code and than use the compiler to compile the code. Assume the code is edited in a file named - HelloWorld.c (.c is the common extension for C code) gcc −Wall HelloWorld.c −o HelloWorld.out would generate a HelloWorld.out (.out is the common extension for executable file for the Linux operating system) Communication Systems Engineering - BGU 12 ספטמבר 18
15
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” Brackets define code blocks Note that all C statements end with a semicolon (;). Communication Systems Engineering - BGU 12 ספטמבר 18
16
void main() 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. Communication Systems Engineering - BGU 12 ספטמבר 18
17
printf() This is a C statement.
This statement calls a function called printf, which causes text to be printed on the screen. Communication Systems Engineering - BGU 12 ספטמבר 18
18
#include <stdio.h>
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 and others functions. Communication Systems Engineering - BGU 12 ספטמבר 18
19
Identifiers Communication Systems Engineering - BGU 12 ספטמבר 18
20
Identifiers naming rules
Letters, digits, underscores i 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 Communication Systems Engineering - BGU 12 ספטמבר 18
21
Naming Using Identifiers
Variables. Reserved Words Functions. Constants . Structures. Unions. Type of variables. Communication Systems Engineering - BGU 12 ספטמבר 18
22
Variables Communication Systems Engineering - BGU 12 ספטמבר 18
23
Declaring variables in C
Before using a variable, one must declare it. The declaration first introduces the variable type, then its name. Many variables of the same type can be separated by , Communication Systems Engineering - BGU 12 ספטמבר 18
24
Example Variable Declarations
int i; char c; float f1, f2; unsigned int ui ; double t1,t2,t3; Communication Systems Engineering - BGU 12 ספטמבר 18
25
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 Communication Systems Engineering - BGU 12 ספטמבר 18
26
Initialize variables When a variable is declared, its value is undefined. In order to use variable it must be valuable. There are three ways: Assignment Input from user Initialization Examples of initialization: int e = 7 , r = 34, t; double ab = 9.7; char c = `k`; Communication Systems Engineering - BGU 12 ספטמבר 18
27
Assignments Communication Systems Engineering - BGU 12 ספטמבר 18
28
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 Communication Systems Engineering - BGU 12 ספטמבר 18
29
Stack vs. Heap Both are used for memory management.
The stack is used to store your code, and runtime values : parameters, return address, links, return value and local variables. Heaps are used to contain all your dynamically allocated variables. A heap maintains a freelist (list of all the free space available) and as and when you allocate and deallocate memory it updates this free list Communication Systems Engineering - BGU 12 ספטמבר 18
30
Stack vs. Heap (cont.) The stack is local to your program space and is therefore usually faster to access. The heap is memory that resides outside of your programs direct control and as such must be acquired and allocated via the operating systems functions or by special interrupt calls. The management of a heap is relatively complex. Communication Systems Engineering - BGU 12 ספטמבר 18
31
Example /* Get a length in cm and convert to inches */ #include <stdio.h> int main() { double cm, inches; printf("Please enter length in centimeters: "); scanf("%lf",&cm); inches = cm / 2.54; printf(“%g centimeters are equal to %g inches\n", cm, inches); return 0; } Communication Systems Engineering - BGU 12 ספטמבר 18
32
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. Communication Systems Engineering - BGU 12 ספטמבר 18
33
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. Communication Systems Engineering - BGU 12 ספטמבר 18
34
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); var1 and var2 were defined as double. Communication Systems Engineering - BGU 12 ספטמבר 18
35
prinft/scanf - Conversion codes - %?
? is replaced by a respective variable. %c – a character %d – an integer, %u – an unsigned integer. %ld – a long integer. %f – a float. %lf – a double. %g – a nicer way to show a double (in printf) %x – an hexadecimal. %s – a string . %% - the ‘%’ character (in printf) Communication Systems Engineering - BGU 12 ספטמבר 18
36
Operator \? \n – New line. \t – Tabulator space. \\ - Symbol \
Communication Systems Engineering - BGU 12 ספטמבר 18
37
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. Communication Systems Engineering - BGU 12 ספטמבר 18
38
ASCII table 12 ספטמבר 18 ~ Communication Systems Engineering - BGU -
HEX DEC CHR CTRL 00 NUL 20 32 SP 40 64 @ 60 96 ` 01 1 SOH ^A 21 33 ! 41 65 A 61 97 a 02 2 STX ^B 22 34 " 42 66 B 62 98 b 03 3 ETX ^C 23 35 # 43 67 C 63 99 c 04 4 EOT ^D 24 36 $ 44 68 D 100 d 05 5 ENQ ^E 25 37 % 45 69 E 101 e 06 6 ACK ^F 26 38 & 46 70 F 102 f 07 7 BEL ^G 27 39 ' 47 71 G 103 g 08 8 BS ^H 28 ( 48 72 H 104 h 09 9 HT ^I 29 ) 49 73 I 105 i 0A 10 LF ^J 2A * 4A 74 J 6A 106 j 0B 11 VT ^K 2B + 4B 75 K 6B 107 k 0C 12 FF ^L 2C , 4C 76 L 6C 108 l 0D 13 CR ^M 2D - 4D 77 M 6D 109 m 0E 14 SO ^N 2E . 4E 78 N 6E 110 n 0F 15 SI ^O 2F / 4F 79 O 6F 111 o 16 DLE ^P 30 50 80 P 112 p 17 DC1 ^Q 31 51 81 Q 113 q 18 DC2 ^R 52 82 R 114 r 19 DC3 ^S 53 83 S 115 s DC4 ^T 54 84 T 116 t NAK ^U 55 85 U 117 u SYN ^V 56 86 V 118 v ETB ^W 57 87 W 119 w CAN ^X 58 88 X 120 x EM ^Y 59 89 Y 121 y 1A SUB ^Z 3A : 5A 90 Z 7A 122 z 1B ESC 3B ; 5B 91 [ 7B 123 { 1C FS 3C < 5C 92 \ 7C 124 | 1D GS 3D = 5D 93 ] 7D 125 } 1E RS 3E > 5E 94 ^ 7E 126 ~ 1F US 3F ? 5F 95 _ 7F 127 Communication Systems Engineering - BGU 12 ספטמבר 18
39
Example of char as both a character and a small number
#include <stdio.h> int main() { 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; } Communication Systems Engineering - BGU 12 ספטמבר 18
40
Another example /* Get the position of a letter in the abc */ #include <stdio.h> int main() { 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; } Communication Systems Engineering - BGU 12 ספטמבר 18
41
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’) Communication Systems Engineering - BGU 12 ספטמבר 18
42
Solution /* Convert a letter to uppercase */ #include <stdio.h> int main() { 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; } Communication Systems Engineering - BGU 12 ספטמבר 18
43
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 % Communication Systems Engineering - BGU 12 ספטמבר 18
44
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) Communication Systems Engineering - BGU 12 ספטמבר 18
45
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 Communication Systems Engineering - BGU 12 ספטמבר 18
46
Operations with different types
For example - 3 + 4 = 7 = 7.0 3 / 4 = 0 3.0 / 4 = 0.75 Communication Systems Engineering - BGU 12 ספטמבר 18
47
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. Communication Systems Engineering - BGU 12 ספטמבר 18
48
Casting variables #include <stdio.h> void main() { int a=1, b=2; printf("%d / %d = %d\n", a, b, a/b); printf("%d / %d = %g\n", a, b, (float)a / b); } Windows format Communication Systems Engineering - BGU 12 ספטמבר 18
49
Example – find what’s wrong
#include <stdio.h> void main() { int a = 10; int b = 20; printf("The average of %d and %d is %d\n", a, b, (a + b) * (1 / 2)); } Communication Systems Engineering - BGU 12 ספטמבר 18
50
Will this work? #include <stdio.h> int main() { 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; } Communication Systems Engineering - BGU 12 ספטמבר 18
51
This works !! #include <stdio.h> int main(void) { int a = 10; int b = 20; printf ("The average of %d and %d is %f\n", a,b, (a + b)*(1.0 / 2)); return 0; } Communication Systems Engineering - BGU 12 ספטמבר 18
52
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 Communication Systems Engineering - BGU 12 ספטמבר 18
53
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; } Communication Systems Engineering - BGU 12 ספטמבר 18
54
Selection statements 12 ספטמבר 18
Communication Systems Engineering - BGU 12 ספטמבר 18
55
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’ Communication Systems Engineering - BGU 12 ספטמבר 18
56
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 Communication Systems Engineering - BGU 12 ספטמבר 18
57
Logical operators Allows to evaluate two or more expressions -
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 !A – ‘not’ - True when A is not, and vice versa. Communication Systems Engineering - BGU 12 ספטמבר 18
58
AND - && A && B B A F T 12 ספטמבר 18
Communication Systems Engineering - BGU 12 ספטמבר 18
59
OR - || A || B B A F T Communication Systems Engineering - BGU 12 ספטמבר 18
60
NOT - ! ! A A T F Communication Systems Engineering - BGU 12 ספטמבר 18
61
Logical Expressions There are logical order in the expressions(similar to the algebraic order) && - similar to * || - similar to + ! - similar t0 negative (A <= B) && (N != M) || (Y > Z) is different from (A <= B) && ((N != M) || (Y > Z)) Communication Systems Engineering - BGU 12 ספטמבר 18
62
Bitwise Bitwise AND - & Bitwise OR - | Bitwise XOR - ^
Assignment by bitwise left and right shift: <<= >>= Assignment by bitwise AND, OR and XOR &= |= ^= Communication Systems Engineering - BGU 12 ספטמבר 18
63
Bitwise #include <stdio.h> int main ( ) { unsigned char Byte = 1 ; // Byte variables printf( "Byte i s : %d\n" , Byte ) ; // 1 printf( "Byte<<1 i s : %d\n" , Byte<<=1) ; //2 printf( "Byte<<1 i s : %d\n" , Byte<<=1) ; // 4 printf( "Byte<<1 i s : %d\n" , Byte<<=1) ; // 8 printf ( "Byte<<1 i s : %d\n" , Byte<<=1) ; // 16 printf( "Byte<<1 i s : %d\n" , Byte<<=1) ; // 32 printf( "Byte<<1 i s : %d\n" , Byte<<=1) ; // 64 printf( "Byte<<1 i s : %d\n" , Byte<<=1) ; // 128 printf( "Byte<<1 i s : %d\n" , Byte<<=1) ; // 0 return 0; } Communication Systems Engineering - BGU 12 ספטמבר 18
64
Bitwise #include <stdio.h> int main ( ) { unsigned char Byte = 1 ; // Byte variables char FindBit = 1; Byte = 89 ; // Set number : printf( " Bit 0 : %d\n" , Byte & FindBit ) ; // 1 FindBit<<=1; printf ( " Bit 1 : %d\n" , Byte & FindBit ) ; // 0 printf( " Bit 2 : %d\n" , Byte & FindBit ) ; // 0 printf( " Bit 3 : %d\n" , Byte & FindBit ) ; // 8 printf( " Bit 4 : %d\n" , Byte & FindBit ) ; // 16 FindBit<<=1; printf( " Bit 5 : %d\n" , Byte & FindBit ) ; // 0 printf( " Bit 6 : %d\n" , Byte & FindBit ) ; // 64 printf( " Bit 7 : %d\n" , Byte & FindBit ) ; // 0 return 0 ; { Communication Systems Engineering - BGU 12 ספטמבר 18
65
Selection Statements 12 ספטמבר 18
Communication Systems Engineering - BGU 12 ספטמבר 18
66
Example Structure ? 12 ספטמבר 18
Communication Systems Engineering - BGU 12 ספטמבר 18
67
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 Communication Systems Engineering - BGU 12 ספטמבר 18
68
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. if (expression) { statements … } Communication Systems Engineering - BGU 12 ספטמבר 18
69
An example /* This program displays the absolute value of a number given by the user */ #include <stdio.h> int main() { 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; } Communication Systems Engineering - BGU 12 ספטמבר 18
70
If-else statement if (expression) statement1 (or block of statements)
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”) Communication Systems Engineering - BGU 12 ספטמבר 18
71
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); Communication Systems Engineering - BGU 12 ספטמבר 18
72
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"); Communication Systems Engineering - BGU 12 ספטמבר 18
73
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 Communication Systems Engineering - BGU 12 ספטמבר 18
74
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! Communication Systems Engineering - BGU 12 ספטמבר 18
75
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 Communication Systems Engineering - BGU 12 ספטמבר 18
76
Else-if if (expression) statement else if (expression) else
Communication Systems Engineering - BGU 12 ספטמבר 18
77
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"); Communication Systems Engineering - BGU 12 ספטמבר 18
78
The ?: operator expr1 ? expr2 : expr3
If expr1 is true (non-zero), expr2 is evaluated. Otherwise, expr3 is evaluated Communication Systems Engineering - BGU 12 ספטמבר 18
79
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; } Communication Systems Engineering - BGU 12 ספטמבר 18
80
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); ==== Communication Systems Engineering - BGU 12 ספטמבר 18
81
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); ==== Communication Systems Engineering - BGU 12 ספטמבר 18
82
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 } Communication Systems Engineering - BGU 12 ספטמבר 18
83
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"); } Communication Systems Engineering - BGU 12 ספטמבר 18
84
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 gpout from the switch statement, that is , to immediately jump to the next statement after the switch statement Communication Systems Engineering - BGU 12 ספטמבר 18
85
Loops Communication Systems Engineering - BGU 12 ספטמבר 18
86
Desinnig a loop ? ? Communication Systems Engineering - BGU 12 ספטמבר 18
87
Loops for, while, do-while 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. Communication Systems Engineering - BGU 12 ספטמבר 18
88
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. Communication Systems Engineering - BGU 12 ספטמבר 18
89
Example - factorial #include <stdio.h> int main() { 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) Communication Systems Engineering - BGU 12 ספטמבר 18
90
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! Communication Systems Engineering - BGU 12 ספטמבר 18
91
Solution #include <stdio.h> int main() { 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; } Communication Systems Engineering - BGU 12 ספטמבר 18
92
Additional Exercise Input – Output – Two integers – A and B
Only if A and B are Digits Otherwise return to input. Communication Systems Engineering - BGU 12 ספטמבר 18
93
Solution #include <stdio.h> void main() { int a, b, flag = 1; while ( flag){ flag = 0; printf("Please enter two numbers.\n"); scanf("%d%d", &a, &b); if(a > 9 || a < 0) flag = 1; else if (b > 9 || b < 0 ) } // executing statements using a and b Communication Systems Engineering - BGU 12 ספטמבר 18
94
Compact Solution #include <stdio.h> int main() { int a, b, flag = 1; while ( flag){ flag = 0; printf("Please enter two numbers.\n"); scanf("%d%d", &a, &b); if(a > 9 || a < 0 || b > 9 || b < 0 ) flag = 1; } // executing statements using a and b return 0; Communication Systems Engineering - BGU 12 ספטמבר 18
95
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) Communication Systems Engineering - BGU 12 ספטמבר 18
96
Example – waiting for legal input
#include <stdio.h> int main() { 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; } Communication Systems Engineering - BGU 12 ספטמבר 18
97
Loop for - format Program before the for loop for( ; ; ) { loop body;
} Continue the program after for loop initialize condition increment False True Communication Systems Engineering - BGU 12 ספטמבר 18
98
For loops (cont.) Equivalent to while… Any for loop can be converted to while loop and vice versa. 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. Communication Systems Engineering - BGU 12 ספטמבר 18
99
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. Communication Systems Engineering - BGU 12 ספטמבר 18
100
Using break void main () {
. loop1(expression1) { loop2(expression2) { break; } // end loop2 // continue with loop1 } // end loop1 } void main () { . loop(expression) { break; } // continue with the program Communication Systems Engineering - BGU 12 ספטמבר 18
101
Continue in the loop 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. Communication Systems Engineering - BGU 12 ספטמבר 18
102
Using continue void main () { . loop(expression) { continue; } // continue with the program Communication Systems Engineering - BGU 12 ספטמבר 18
103
Write a program that accepts a number from the user,
Exercise Write a program that accepts a number from the user, and checks whether it is prime. Communication Systems Engineering - BGU 12 ספטמבר 18
104
Solution (isprime.c) #include <stdio.h> int main() { 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; } Communication Systems Engineering - BGU 12 ספטמבר 18
105
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...) Communication Systems Engineering - BGU 12 ספטמבר 18
106
Solution (listprimes.c)
#include <stdio.h> void main() { 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); } // end for } Communication Systems Engineering - BGU 12 ספטמבר 18
107
Exercise Write a program that prints an upside-down half triangle of *. The height of the pyramid is the input. ***** **** *** ** * Communication Systems Engineering - BGU 12 ספטמבר 18
108
Solution #include<stdio.h> int main() { 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; Communication Systems Engineering - BGU 12 ספטמבר 18
109
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. Communication Systems Engineering - BGU 12 ספטמבר 18
110
Solution 1 #include <stdio.h> int main() { 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; Communication Systems Engineering - BGU 12 ספטמבר 18
111
Solution 2 (with break) #include <stdio.h> void main() { 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; // break the inner for loop only !! if (j == i) // i is prime. We found our guy break; } printf("The largest prime not larger than %d is %d.\n", last, i); Communication Systems Engineering - BGU 12 ספטמבר 18
112
Arrays Communication Systems Engineering - BGU 12 ספטמבר 18
113
Problems with simple variables
Hard to give up values high number of variables. Complex to sort a high number of variables by value. Impossible to use loops . Communication Systems Engineering - BGU 12 ספטמבר 18
114
Arrays A block of many variables of the same type.
Array can be declared for any type. E.g. int A[10] is an array of 10 integers. Examples: list of students’ marks series of numbers entered by user vectors matrices Communication Systems Engineering - BGU 12 ספטמבר 18
115
Arrays in Memory Sequence of variables of specified type
The array variable itself holds the address in memory of beginning of sequence Example: double S[10]; The k-th element of array A is specified by A[k-1] (0 based) 1 2 3 4 5 6 7 8 9 S … Communication Systems Engineering - BGU 12 ספטמבר 18
116
Example - reverse #include <stdio.h> void main() { int i, A[10]; printf("please enter 10 numbers:\n"); for(i=0; i<10; i++) scanf("%d",&A[i]); printf("numbers in reversed order:\n"); for(i=9; i>=0; i--) printf("%d\n",A[i]); } Constant integer type Communication Systems Engineering - BGU 12 ספטמבר 18
117
#define #define defines a symbolic name.
During preprocessing phase, symbolic names are replaced by the replacement text. Communication Systems Engineering - BGU 12 ספטמבר 18
118
Reverse with #define /* get 10 integers from the user and printing them in reversed order*/ #include <stdio.h> #define NUM 10 void main() { int i; int A[NUM]; printf(“Please enter %d numbers:\n",NUM); for(i=0; i<NUM; i++) scanf("%d",&A[i]); printf("numbers in reversed order:\n"); for(i=NUM-1; i>=0; i--) printf("%d\n",A[i]); } Communication Systems Engineering - BGU 12 ספטמבר 18
119
Will it work ? #define NUM 10 void main() { int i = 10; int A[i];
Example : #include <stdio.h> #define NUM 10 void main() { int i = 10; int A[i]; … NO !! Need a constant integer type , no variable ! Communication Systems Engineering - BGU 12 ספטמבר 18
120
Initialization Like in the case of regular variables, we can initialize the array during declaration. The number of initializers cannot be more than the number of elements in the array But it can be lessin which case, the remaining elements are initialized to 0 The next declarations: int array1[5] = {0}; int array2[8] = {2, 4, 6, 8}; meaning: int array1[5] = {0,0,0,0,0}; int array2[] = {2, 4, 6, 8,0,0,0,0}; Communication Systems Engineering - BGU 12 ספטמבר 18
121
Initialization (cont.)
If you like, the array size can be inferred from the number of initializers. Leaving the square brackets empty . So these are identical declarations : int array1 [8] = {2, 4, 6, 8, 10, 12, 14, 16}; int array2 [] = {2, 4, 6, 8, 10, 12, 14, 16}; Communication Systems Engineering - BGU 12 ספטמבר 18
122
Bubble Sort #include <stdio.h> void main() { int array[] = {78,73,63,62,58,45,34,11}; int i,temp, n = 8 , flag; do { flag = 0; for ( i = 0 ; i < n-1 ; i++) { if ( array[i] > array[i+1] ) { temp = array[i]; array[i] = array[i+1]; array[i+1] = temp; flag = 1; } } while (flag); Communication Systems Engineering - BGU 12 ספטמבר 18
123
Insertion Sort #include <stdio.h> int main() { int array[]= {12 ,3,34,14,98,33,9,17}; int temp,loops = 0 ,j, i, n = 8; for ( i = 1 ; i < n ; i++) { temp = array[i]; j = i-1; loops++; while (( j >=0) && ( temp < array[j])) { array[j+1] = array[j]; j--; } array[j+1] = temp; } Communication Systems Engineering - BGU 12 ספטמבר 18
124
Selection Sort void selection_sort(int list[], int n) { int i, j, min; for (i = 0; i < n - 1; i++) { min = i; for (j = i+1; j < n; j++) { if (list[j] < list[min]) { min = j; } } temp = list[i]; list[i] = list[min]); list[min] = list[i]; } Communication Systems Engineering - BGU 12 ספטמבר 18
125
Two Dimensional Arrays
We sometimes want to keep an inherent Two-Dimensional structure of data. Example: We can define a two-dimensional 3x3 matrix by double A[3][3]; Communication Systems Engineering - BGU 12 ספטמבר 18
126
Two Dimensional Arrays
Array of arrays: int A[2][3] = { {1, 2, 3}, {4, 5, 6} }; Means an array of 2 integer arrays, each of length 3. Access: j-th element of the i-th array is A[i][j] Communication Systems Engineering - BGU 12 ספטמבר 18
127
Initialization Two Dimensional Arrays
When initializing the array, it is necessary to indicate the size of the second dimension: double B[][2] = {{1,2}, {2,3}, {3,4}}; Filling with zeros (0) is similar to one dimension array. Communication Systems Engineering - BGU 12 ספטמבר 18
128
Exercise Write a program that defines 3 matrices A,B,C of size 3x3 with float elements; initialize the first two matrices (A and B) Compute the matrix multiplication of A and B and store it in C (i.e. C = A*B) Matrix Multiplication: Print all the matrices on the screen Communication Systems Engineering - BGU 12 ספטמבר 18
129
Strings in C Communication Systems Engineering - BGU 12 ספטמבר 18
130
String Problem : It may be much shorter A sequence of characters.
Stored, as might be expected, in an array of chars. Another way to initialize: char A[]=“blabla”; Problem : It may be much shorter than the array where it’s stored How can we know where a string end ?! Communication Systems Engineering - BGU 12 ספטמבר 18
131
The Terminator Strings terminate with NULL character, signed by ‘\0’ (ASCII code 0). This is a convention used to know where the string ends. It means that in order to hold a string of 7 chars we need an array of length at least 8 So the previous initialization : char A[]=“blabla”; is equivalent to char A[] = {‘b’, ‘l’, ‘a’, ‘b’, ‘l’, ‘a’, ‘\0’}; Communication Systems Engineering - BGU 12 ספטמבר 18
132
Printing strings printf allows printing whole strings at once using %s – char str[200]; /* … */ printf(“%s\n”, str); This will print the contents of str ,cell by cell, until a ‘\0’ is encountered this may be less than 200, but also more Communication Systems Engineering - BGU 12 ספטמבר 18
133
The fool on the null #include <stdio.h> void main() { char str[]="I'm a full string"; printf("%s\n",str); str[7]='o'; str[8]='o'; str[11]='\0'; str[11] = ‘s’; printf("%s\n", str); } Communication Systems Engineering - BGU 12 ספטמבר 18
134
Reading-in strings There are several ways of accepting strings as input from the user. The obvious way to go is read character by character using getchar() Communication Systems Engineering - BGU 12 ספטמבר 18
135
Reading-in strings - scanf
A simpler way is to use scanf To read in a string to a variable str we can use: scanf(“%s”, str); Note there’s no ‘&’ sign!!! Scanf reads-in letters until a space or newline is encountered The maximum length can be stated in the parentheses – scanf(“%10s”, str); This will read in 10 letters, plus the ‘\0’ sign (so str should have place for 11 characters) Communication Systems Engineering - BGU 12 ספטמבר 18
136
Reading-in strings – gets()
An other simpler way is to use gets() To read in a string to a variable str we can use: gets( str); Note there’s no ‘&’ sign too!!! gets reads-in letters until a newline (pressing enter on the keyboard) is encountered. The maximum length can be stated for the array of characters declaration minus 1. gets change the new line for the `\0` sign as last character in the string. Communication Systems Engineering - BGU 12 ספטמבר 18
137
Writing out strings – puts()
A simpler way to write out a string is to use puts() To write out a string that is into variable str we can use: puts( str); puts write out letters until a `\0` sign is encountered. puts change the `\0` sign for new line as the last character in the string. Communication Systems Engineering - BGU 12 ספטמבר 18
138
Comparing strings We cannot just compare strings’ contents by
char A[7]=“Hello”; char B[7]=“Hello”; if(A==B) { … } Because A and B are addresses of A[0] and B[0] A==B only if A and B are the same string in memory In order to compare the contents we must scan char by char ‘H’ ‘e’ ‘l’ ‘o’ ‘\0’ …. B A Communication Systems Engineering - BGU 12 ספטמבר 18
139
String library Like in the case of stdio.h and math.h, we have a special library for handling strings We should #include <string.h> Functions: strlen(s) – returns the length of s strcmp(s1, s2) – compares s1 with s2 strcpy(s1, s2) – copies to contents of s2 to s1 strcat(s1 , s2) – add the s1 at the end of s2 and more… Communication Systems Engineering - BGU 12 ספטמבר 18
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.