1 / 58

Assignments

Assignments. איתחול משתנים. כאשר מגדירים משתנה ערכו הוא בלתי מוגדר, וצריכים להזהר בשימושו. על מנת להשתמש בהם צריך להציב ערך. קיימם 3 דרכים להצבה ערך : איתחול השמה קליטה ממשתמש קליטה מקובץ דוגמאות איתחול: int e = 7 , r = 34, t; double ab = 9.7; char c = `k. = זה לא שווה.

aperry
Download Presentation

Assignments

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Assignments Department of Computer Science-BGU

  2. איתחול משתנים • כאשר מגדירים משתנה ערכו הוא בלתי מוגדר, וצריכים להזהר בשימושו. • על מנת להשתמש בהם צריך להציב ערך. • קיימם 3 דרכים להצבה ערך : • איתחול • השמה • קליטה ממשתמש • קליטה מקובץ • דוגמאות איתחול: • int e = 7 , r = 34, t; • double ab = 9.7; • char c = `k Department of Computer Science-BGU

  3. = זה לא שווה • האם זה אפשרי ? int a; a = a + 1; • כן – בסמנטיקה של השפה C • משמעות של הסימן = היא לא שיוויון אלא השמה! (assignment) Department of Computer Science-BGU

  4. 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. Department of Computer Science-BGU

  5. printf - מדפיסה על המסך 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. • With many variables: printf ("zeros=%d- ones=%d-letters=%d\n",a , b, d); Department of Computer Science-BGU

  6. טבלאות עם printf • printf (“%4d%7d\n”,a,b) • printf (“%8.2f%10.4g\n”,c,d) רוחב שדה של הדפסת המשתנים רוחב שדה של הדפסת המשתנים כולל הנקודה העשרונית מספר הספרות המודפסות אחרי הנקודה העשרונית Department of Computer Science-BGU

  7. scanf– מקבל נתונים מהמשתמש scanf("%lf", &var); • הוראה זו ממתין עד שהמשתמש מקליד ערך מתאים וסוג המשתנה ובהמשך על enter . • הערך מאוחסן במשתנה בשם var. • משמעות &var היא הכתובת של המשתנה var בחלק של הזכרון מוגדר כמחסנית (stack). • ניתן לקבל ערכים לשניים או יותר משתנים ביחד:scanf("%lf%lf", &var1, &var2); Department of Computer Science-BGU

  8. 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) Department of Computer Science-BGU

  9. Operator \? • \n – New line. • \t – Tabulator space. • \\ - Symbol \ Department of Computer Science-BGU

  10. Example /* Get a length in cm and convert to inches */ #include <stdio.h> void 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); } Department of Computer Science-BGU

  11. Exercise Write a program that accepts as input - • The Dollar-Shekel exchange rate • An integer amount of dollars and outputs - • The equivalent amount in Shekels Department of Computer Science-BGU

  12. Solution #include <stdio.h> void main() { 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); } Department of Computer Science-BGU

  13. char זה גם מספר • char variable is used to store a text character: • Letters. • Digits. • Keyboard signs. • Non-printable characters. • But also small numbers (0 to 255). Department of Computer Science-BGU

  14. 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. • Look for the ASCII table in the course page. Department of Computer Science-BGU

  15. דוגמא כאשר charזה גם מספר #include <stdio.h> void main(){ char i = 'b'; printf("i as a character is %c\n", i); // print b printf("i as an integer is %d\n", i); // print 98 printf("The character after %c is %c\n", i, i + 1); // b c } Department of Computer Science-BGU

  16. דוגמא נוספת /* Get the position of a letter in the abc */ #include <stdio.h> void 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); } Department of Computer Science-BGU

  17. תרגיל Write a program that accepts as input – • A lowercase letter and outputs – • The same letter in uppercase (e.g., if the input is ‘g’, the output should be ‘G’) Department of Computer Science-BGU

  18. פתרון /* Convert a letter to uppercase */ #include <stdio.h> void main() { char letter; printf("Please enter a lowercase letter\n"); scanf("%c", &letter); printf("This letter in uppercase is %c\n", letter-'a'+’A’); } Department of Computer Science-BGU

  19. 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 % Department of Computer Science-BGU

  20. לפתור את החידה ! • 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) כאן יש רווח Department of Computer Science-BGU

  21. 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 Department of Computer Science-BGU

  22. Operations with different types For example - • 3 + 4 = 7 • 3.0 + 4 = 7.0 • 3 / 4 = 0 • 3.0 / 4 = 0.75 Department of Computer Science-BGU

  23. Casting • לפעמים אנו משתמשים במשתנה מסוג אחד בפעולה שרוצים לקבל משתנה מסוג אחר. • צריכים לבצע casting לסוג החדש • אופרטור casting הוא מסוג (type) Department of Computer Science-BGU

  24. Casting #include <stdio.h> void main() { int a=1, b=2; printf("%d / %d = %d\n", a, b, a/b); // print 0 printf("%d / %d = %g\n", a, b, (float)a / b); // print 0.50 } Department of Computer Science-BGU

  25. דוגמא – מה השתבש ? #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)); } Ouput: The average of 10 and 20 is 0 Department of Computer Science-BGU

  26. האם זה עובד ? #include <stdio.h> void main(){ int a = 10, b = 20; printf ("The average of %d and %d is %d\n", a, b, (a + b)*(1.0 / 2)); } Ouput: The average of 10 and 20 is 0 Department of Computer Science-BGU

  27. זה עובד !! #include <stdio.h> void 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)); } Ouput: The average of 10 and 20 is 15.0000 Department of Computer Science-BGU

  28. 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 Department of Computer Science-BGU

  29. Prefix ++i and postfix i++ #include <stdio.h> void main() { int i=5; printf("i++=%d\n",i++); // print 5 printf(“++i=%d\n",++i); // print 7 } Department of Computer Science-BGU

  30. משפטי תנאי Department of Computer Science-BGU

  31. דוגמא של מבנה ? Department of Computer Science-BGU

  32. 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’ Department of Computer Science-BGU

  33. אופרטורים יחס • 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 Department of Computer Science-BGU

  34. אופרטורים לוגיים • 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. Department of Computer Science-BGU

  35. AND - && Department of Computer Science-BGU

  36. OR - || Department of Computer Science-BGU

  37. NOT - ! Department of Computer Science-BGU

  38. 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)) Department of Computer Science-BGU

  39. משפטי תנאי • ביצוע של משפטי תנאי מבוסס על ערך לוגי של ביטוי. • ביטוים אלה נקראיים : controlling expression . • משפט תנאי if • משפט תנאי switch Department of Computer Science-BGU

  40. משפט תנאי 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 … } Department of Computer Science-BGU

  41. דוגמא /* This program displays the absolute value of a number given by the user */ #include <stdio.h> void 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); } Department of Computer Science-BGU

  42. משפט תנאי if – else if (expression) statement1 (or block of statements) else statement2 (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”) Department of Computer Science-BGU

  43. דוגמא ( חלק מתכנית) 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); /* … */ Department of Computer Science-BGU

  44. דוגמא נוספת 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"); printf("The expression a == b is %d\n", a == b); } Department of Computer Science-BGU

  45. אופרטור = במשפטי תנאי • 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 -> true • (y = 0) equals 0 -> false Department of Computer Science-BGU

  46. 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! Department of Computer Science-BGU

  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 Department of Computer Science-BGU

  48. Else-if if (expression) statement else if (expression) statement else if (expression) statement else statement Department of Computer Science-BGU

  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"); Department of Computer Science-BGU

  50. אופרטור: ? expr1? expr2: expr3 • If expr1 is true (non-zero), expr2 is evaluated. Otherwise, expr3 is evaluated Department of Computer Science-BGU

More Related