1 מבוא למחשב שפת C תרגילי חזרה. 2 תרגיל 1 : מחשבון קלט : תרגיל חשבוני המורכב ממספרים שלמים עם פעולות חשבוניות ביניהם. התרגיל מסתיים ב =. אפשריים רווחים.

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

1 More Conditionals Instructor: Mainak Chaudhuri
Selection Statements Selects statements to execute based on the value of an expression The expression is sometimes called the controlling expression Selection.
תכנות תרגול 4 שבוע : לולאות while לולאות while while (condition) { loop body } במקרה של קיום התנאי מתבצע גוף הלולאה ברגע שהתנאי לא מתקיים נצא.
Display a 12-Month Calendar CS-2301 D-term Programming Assignment #2 12-Month Calendar CS-2301 System Programming C-term 2009 (Slides include materials.
11 Introduction to Programming in C תרגול
תכנות תרגול 6 שבוע : תרגיל שורש של מספר מחושב לפי הסדרה הבאה : root 0 = 1 root n = root n-1 + a / root n-1 2 כאשר האיבר ה n של הסדרה הוא קירוב.
More on Numerical Computation CS-2301 B-term More on Numerical Computation CS-2301, System Programming for Non-majors (Slides include materials from.
מבוא כללי למדעי המחשב תרגול 3. לולאות while לולאות while while (condition) { loop body } במקרה של קיום התנאי מתבצע גוף הלולאה ברגע שהתנאי לא מתקיים נצא.
Declarations/Data Types/Statements. Assignments Due – Homework 1 Reading – Chapter 2 – Lab 1 – due Monday.
1 Introduction to Computers and Programming Class 3 Introduction to C Professor Avi Rosenfeld.
C programming an Introduction. Types There are only a few basic data types in C. char a character int an integer, in the range -32,767 to 32,767 long.
לולאות 02 יולי יולי יולי 1502 יולי יולי יולי 1502 יולי יולי יולי 15 1 Department of Computer Science-BGU.
11 Introduction to Programming in C - Fall 2010 – Erez Sharvit, Amir Menczel 1 Introduction to Programming in C תרגול
12-2 Know how if and switch C statements control the sequence of execution of statements. Be able to use relational and logical operators in the conditional.
Lecture No: 16. The scanf() function In C programming language, the scanf() function is used to read information from standard input device (keyboard).
C programming: Variables, Expressions part II. Data Types of Arithmetic Expressions Relational Expressions Logical Expressions Multiple Assignments Compound.
CECS 121 EXAM 1. /* C Programming for the Absolute Beginner */ // by Michael Vine #include main() { printf(“\nC you later\n”); system(“pause”); }
Introduction to Computing Lecture 07: Repetition and Loop Statements (Part II) Introduction to Computing Lecture 07: Repetition and Loop Statements (Part.
Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq.
LAB 2: C BASICS ITS100: Computer and Programming Lab. Section 1 Instructor: Wirat Chinnan TAs: Ms. Sasirassamee Buavirat Mr. Thanasan Tanhermhong (Tum)
Prime numbers Jordi Cortadella Department of Computer Science.
CP104 Introduction to Programming Selection Structures_3 Lecture 11 __ 1 The Switch Statement The switch statement provides another means to select one.
1 CSE1301 Computer Programming Lecture 5: Components of a C Program (Part 1) Linda M c Iver.
Do-while loop Syntax do statement while (loop repetition condition)
Repetitive Structures BBS514 Structured Programming (Yapısal Programlama)1.
Introduction to Computer Algorithmics and Programming Ceng 113 Program Control Statements.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 7.
/* C Programming for the Absolute Beginner */ // by Michael Vine #include main() { printf(“\nC you later\n”); system(“pause”); }
Introduction to C Programming Chapter 2 : Data Input, Processing and Output.
1 Flowchart notation and loops Implementation of loops in C –while loops –do-while loops –for loops Auxiliary Statements used inside the loops –break –continue.
Chapter 3: Formatted Input/Output Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 3 Formatted Input/Output.
Lecture 4: Calculating by Iterating. The while Repetition Statement Repetition structure Programmer specifies an action to be repeated while some condition.
CSC 253 Lecture 3. Let’s look again at …  the program from the end of the last class.  Here’s the start, and the power function:  the program from.
Chapter-4 Managing input and Output operation.  Reading, processing and writing of data are three essential functions of a computer program.  Most programs.
1 Programming a Computer Lecture Ten. 2 Outline  A quick introduction to the programming language C  Introduction to software packages: Matlab for numerical.
CSE1301 Computer Programming: Lecture 6 Input/Output.
CSCI 171 Presentation 3. Operators Instructs C to perform some operation Assignment = Mathematical Relational Logical.
A data type in a programming language is a set of data with values having predefined characteristics.data The language usually specifies:  the range.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
Chapter 3: Formatted Input/Output 1 Chapter 3 Formatted Input/Output.
The following statements are for y = -1; if ( x ) if ( x>0 ) y = 1; else y = 0; A. y= -1 x0 B. y= 0 x0 C. y= 1 x
 Real numbers representation - Floating Point Notation  First C Program  Variables Declaration  Data Types in C ◦ char, short, int, long, float, double,
1 float Data Type Data type that can hold numbers with decimal values – e.g. 3.14, 98.6 Floats can be used to represent many values: –Money (but see warning.
C Programming.
מספרים אקראיים ניתן לייצר מספרים אקראיים ע"י הפונקציה int rand(void);
ECE Application Programming
Formatted Input/Output
Unit-4, Chapter-2 Managing Input and Output Operations
CS1010 Programming Methodology
Formatted Input/Output
OUTPUT STATEMENTS GC 201.
Control Structures Lecture 7.
Looping.
توابع ورودي-خروجي.
CS1100 Computational Engineering
CSC215 Homework Homework 04 Due date: Oct 14, 2016.
A function with one argument
Week 2 Variables, flow control and the Debugger
Relational, Logical, and Equality Operators
Computer Programming Techniques Semester 1, 1998
SELECTIONS STATEMENTS
Perfect squares class identifySquareButLessClever {
EECE.2160 ECE Application Programming
Recursion.
Data Types and Maths Programming Guides.
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
Presentation transcript:

1 מבוא למחשב שפת C תרגילי חזרה

2 תרגיל 1 : מחשבון קלט : תרגיל חשבוני המורכב ממספרים שלמים עם פעולות חשבוניות ביניהם. התרגיל מסתיים ב =. אפשריים רווחים בין המספרים לפעולות מספר יכול להיות שלילי, או חיובי. מספר חיובי עשוי להופיע עם + לפניו דוגמאות קלט : 123*34 = 3*+4 * 8= הנחה : הקלט תקין

3 תרגיל 1 : מחשבון ( המשך ) הקלט נעשה בשני שלבים : – קריאה של רצף תווים המייצגים מספר לתוך מחרוזת. הפונקציה get_num_from_input – הפיכת המחרוזת למספר שלם. הפונקציה getint התוכנית מנוהלת ע " י לולאה שקוראת בכל פעם מספר ופעולה. הלולאה נעצרת כאשר מופיע ‘ = ‘

4 הפונקציה get_num_from_input // reads characters representing an int from input // writes to num_string a string representing a number // returns the next char in input which is not a space char get_num_from_input(char *num_string) { char c; //reads a char at a time int i=1; scanf("%c",&c); while(is_space(c)) //skip possible spaces scanf("%c",&c); num_string[0]=c; // may also be - or + scanf("%c",&c); while (is_digit(c)) { num_string[i++]=c; scanf("%c",&c); } num_string[i]='\0'; while(is_space(c)) scanf("%c",&c); return c; }

5 הפונקציה getint // converts a string into an integer void getint(int *pn, char *num_string) { char c; //reads a char at a time int sign=1; //the sign of the number if(!is_digit(*num_string)) { sign = (num_string[0]=='-') ? -1 : 1; num_string++; } for (*pn = 0; *num_string; num_string++) *pn = 10* *pn + (*num_string-'0'); *pn *= sign; }

6 הפונקציות is_digit ו is_space // returns true if c is a space character int is_space(char c) { return c==' ' || c=='\n' || c=='\t'; } // returns true if c is a digit character int is_digit(char c) { return c>='0' && c<='9'; }

7 הפונקציה main // program: calculator // Reads a sequence of operations with integers // and prints the result // the operation must end at '=', spaces are allowed #include char get_num_from_input(char *); void getint(int *, char *); int main() { int num, result=0; char op,next_op; char snumber[11]; printf ("Enter a computation with integers ending with =:\n"); next_op=get_num_from_input(snumber); getint(&result,snumber);

8 הפונקציה main do { op=next_op; next_op=get_num_from_input(snumber); getint(&num,snumber); switch (op) { case '+': result+=num; break; case '*': result*=num; break; case '-': result-=num; break; case '/': result/=num; break; case '%': result%=num; break; default:; } } while(next_op!='='); printf("%d\n",result); return 0; }

9 תרגיל 2 : מחשבון של מספרים ממשיים קלט : תרגיל חשבוני המורכב ממספרים ממשיים עם פעולות חשבוניות ביניהם. התרגיל מסתיים ב =. אפשריים רווחים בין המספרים לפעולות מספר יכול להיות שלילי, או חיובי. מספר חיובי עשוי להופיע עם + לפניו מספר יכול להופיע עם או בלי נקודה עשרונית דוגמאות קלט : 12.34*56 = 3.14*+4.00 * -8= הנחה : הקלט תקין

10 תרגיל 2 : מחשבון של מספרים ממשיים ( המשך ) הקלט נעשה בשני שלבים : – קריאה של רצף תווים המייצגים מספר לתוך מחרוזת. הפונקציה get_num_from_input – הפיכת המחרוזת למספר ממשי. הפונקציה getdouble התוכנית מנוהלת ע " י לולאה שקוראת בכל פעם מספר ופעולה. הלולאה נעצרת כאשר מופיע ‘ = ‘

11 הפונקציה get_num_from_input // get_num_from_input: reads characters representing a floating // point number from input // writes to num_string a string representing a number // returns the next char in input which is not a space char get_num_from_input(char *num_string) { char c; //reads a char at a time int i=1; scanf("%c",&c); while(is_space(c)) //skip possible spaces scanf("%c",&c); num_string[0]=c; // may also be - or + scanf("%c",&c); while (is_digit(c)) { num_string[i++]=c; scanf("%c",&c); }

12 הפונקציה get_num_from_input ( המשך ) if (c=='.') // decimal point { num_string[i++]=c; scanf("%c",&c); while (is_digit(c)) { num_string[i++]=c; scanf("%c",&c); } num_string[i]='\0'; while(is_space(c)) scanf("%c",&c); return c; }

13 הפונקציה getdouble // converts a string into a floating point void getdouble(double *pn, char *num_string) { char c; //reads a char at a time int sign=1; //the sign of the number double decimal_part; double decimal_fraction=0.1; if(!is_digit(*num_string)) // starts with + or - { sign = (num_string[0]=='-') ? -1 : 1; num_string++; } for (*pn = 0.0; is_digit(*num_string); num_string++) *pn = 10.0* *pn + (*num_string-'0');

14 הפונקציה getdouble ( המשך ) if(*num_string=='.') { ++num_string; for (decimal_part=0.0; *num_string ; num_string++) { decimal_part += decimal_fraction*(*num_string-'0'); decimal_fraction/=10; } *pn+=decimal_part; } *pn *= sign; }

15 הפונקציה main // program: calculator // Reads a sequence of operations with real numbers // and prints the result // the operation must end at '=', spaces are allowed #include char get_num_from_input(char *); void getdouble(double *, char *); int main() { double num, result=0; char op, next_op; char snumber[11]; printf("Enter a computation with real numbers ending with =:\n"); next_op = get_num_from_input(snumber); getdouble(&result,snumber);

16 הפונקציה main do { op=next_op; next_op=get_num_from_input(snumber); getdouble(&num,snumber); switch (op) { case '+': result+=num; break; case '*': result*=num; break; case '-': result-=num; break; case '/': result/=num; break; default:; } }while(next_op!='='); printf("%lf\n",result); return 0; }

17 תרגיל 3 : פירוק מספר שלם למכפלת ראשוניים קלט : מספר שלם חיובי פלט : פרוק של המספר למכפלת מספרים ראשוניים דוגמה : 1350 = 2 * 3^3 * 5^2

18 הפונקציה decompose // decompose: decomposes n into a product of primes. // and prints the decomposition. n assumed positive // 1. find deg: highest power that 2 divides n //2. print 2^deg, and divide n by 2^deg //3. redo 1 and 2 for all odd integers, from 3 up to // square root of n void decompose(int n) { int i; // runs over divisors n int deg; // used as a degree of a prime if(n==1 || n==2 || n==3){ printf("%d = %d\n", n,n); return; } printf ("%d =",n); if (!(n%2))//n is even { deg=degree(2,n);//the highest power that 2 divides n printf (deg>1?" 2^%d ":" 2 ",deg); n /= pow_int(2,deg);// divide n by 2^deg if (n>1)// if n is a power of 2, stop here printf("*"); }

19 הפונקציה decompose ( המשך ) for (i=3; n>1 && i*i <= n; i+=2)//run over odd integers { if (!(n%i)) { deg=degree(i,n); printf (deg>1?" %d^%d ":" %d ",i,deg); n /= pow_int(i,deg); if (n>1) printf("*"); } if (n>1) // n is divisible by a prime > sqrt(n) printf (" %d",n); }

20 הפונקציה degree // degree: returns the highest power that d divides n // Algorithm. start from exp = 0. keep deviding n by d, //until d no longer divides n. increment exp by 1 //each time n is divided. int degree(int d, int n) { int exp=0; //power of d while (!(n%d)) { ++exp; n/=d; } return exp; }

21 הפונקציה pow_int // pow_int: returns a to the bth power //algorithm: a^b = a*a*...*a (b times). int pow_int(int a, int b) { int product=1; for (; b>0; --b) product*=a; return product; }

22 הפונקציה main /* module: primedec.c writes positive integers as a product of prime numbers program is teminated when typing 1 (or a smaller integer). Input: a sequence of positive integers, ended by 1. Output: For each number its decomposition to product of primes */ #include void decompose(int);int main() { int number; // this number will be decomposed do { printf("\nType a positive integer (1 or less to quit): "); scanf("%d", &number); if (number>0) { decompose(number); } } while (number>1); return 0; }

23 תרגיל 4 : פירוק מספר שלם למכפלת ראשוניים בעזרת רקורסיה קלט : מספר שלם חיובי פלט : פרוק של המספר למכפלת מספרים ראשוניים דוגמה : 1350 = 2 * 3 * 3 * 5 * 5

24 הפונקציה decompose void decompose(int n, int min_div) { int div=min_div; if(n==1) return; while(1) { if(n%div==0) { printf("%d",div); n/=div; if(n>1) printf(" * "); decompose(n,div); return; } div++; }

25 הפונקציה main int main() { int number; // this number will be decomposed do { printf("\nType a positive integer (1 or less to quit): "); scanf("%d", &number); if (number > 1) { printf("%d = ", number); decompose(number,2); } }while (number > 1); return 0; }