C Programming.

Slides:



Advertisements
Similar presentations
Etter/Ingber Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
Advertisements

/* program to find area of a ring */ #include int main() { float a1,a2,a,r1,r2; printf("Enter the radius : "); scanf("%f",&r1); a1 = 3.14*r1*r1; printf("Enter.
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.
Programming Recursion “To Iterate is Human, to Recurse, Divine” -- L. Peter Deutsch.
TK1913-C Programming1 TK1913-C Programming 1 C Library Functions C provides a collection of library functions for programmers If these library functions.
ICS103 Programming in C Lecture 9: Functions I
Exercise 4 Recursion. Functions – a short reminder a group of variables and statements that is assigned a name a sub-program  inside main we can call.
C Lecture Notes Functions (Cont...). C Lecture Notes 5.8Calling Functions: Call by Value and Call by Reference Used when invoking functions Call by value.
לולאות 02 יולי יולי יולי 1502 יולי יולי יולי 1502 יולי יולי יולי 15 1 Department of Computer Science-BGU.
1 Agenda - Loops while for for & while Nested Loops do-while Misc. & Questions.
Chapter 4:Functions| SCP1103 Programming Technique C | Jumail, FSKSM, UTM, 2005 | Last Updated: September 2005 Slide 1 Functions Lecture 4 by Jumail Bin.
Programming Arrays. Example 1 Write a program that reads 3 numbers from the user and print them in reverse order. How many variables do we need to store.
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
Recursion. Functions – reminder A function can call other functions. Return causes the execution of the function to terminate and returns a value to the.
Lecture 6 – Functions (2). Outline Recall - sample application functions that return no value functions that return a value Recall – global variable vs.
Chapter 9: Recursion1 CHAPTER 9 RECURSION. Recursion  Concept of recursion  A recursive: Benefit and Cost  Comparison : Iterative and recursive functions.
Functions, Pointers, Structures Keerthi Nelaturu.
1. Function prototype Function prototype is a declaration; indicates the function exists Should have function name, return type and parameter Placed before.
Functions Top-down design Breaking a complex problem into smaller parts that we can understand is a common practice. The process of subdividing a problem.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Functions (1)
Dale Roberts CSCI N305 Functions Recursion Department of Computer and Information Science, School of Science, IUPUI.
UniMAP SemII-09/10EKT120: Computer Programming1 Week 6 – Functions (2)
Chapter 5 – Functions II Outline Recursion Examples Using Recursion: The Fibonacci Series.
Functions Exercise 5. Functions a group of declarations and statements that is assigned a name  effectively, a named statement block  usually has a.
UniMAP SemI-09/10EKT120: Computer Programming1 Week 5 – Functions (1)
FUNCTION Dong-Chul Kim BioMeCIS UTA 12/7/
TMC1414/TMC1413 I NTRODUCTION T O P ROGRAMMING Lecture 06 Function.
Functions. Why use functions? They can break your problem down into smaller sub-tasks (modularity).  easier to solve complex problems They make a program.
Functions What is a function –“sub” program, with an isolated set of statements –Accepts parameters, returns a result (perhaps) –Think of it as its own.
1 ICS103 Programming in C Lecture 9: Functions I.
Functions Dr. Sajib Datta Functions A function is a self-contained unit of program code designed to accomplish a particular task. Some functions.
1 Today: Functions. 2 Some General Tips on Programming Write your code modularly Compile + test functionality in the process.
 Recursion  Pointers and Arrays #include void print3(int n){ if (n==0)return; printf ("%d\n",n); print3(n-1); printf ("%d\n",n); } void main(){ print3(5);
 Real numbers representation - Floating Point Notation  First C Program  Variables Declaration  Data Types in C ◦ char, short, int, long, float, double,
C Programming.
EKT120: Computer Programming
Functions Course conducted by: Md.Raihan ul Masood
Introduction to Computer Algorithmics and Programming Ceng 113
EKT120: Computer Programming
Programming Functions.
Functions Chapter 5 CS12 - Computer Programming 1 Chapter 5.
Functions Dr. Sajib Datta
Quiz 2.
Module 4 Functions – function definition and function prototype.
Functions Department of Computer Science-BGU יום רביעי 12 ספטמבר 2018.
INC 161 , CPE 100 Computer Programming
Functions Dr. Sajib Datta
מבוא כללי למדעי המחשב תרגול 2
Formatted and Unformatted Input/Output Functions
Control Structures Lecture 7.
INC 161 , CPE 100 Computer Programming
Chapter 6 - Functions Outline 5.1 Introduction
Programming application CC213
While Loop Design ENGI 1020 Fall 2018.
Functions Recursion CSCI 230
Loops in C.
שיעור רביעי: פונקציות, מבוא לרקורסיה
Recursion Department of Computer Science-BGU יום שני 10 דצמבר 2018.
A function with one argument
In C Programming Language
Introduction to Problem Solving and Programming
Functions Department of Computer Science-BGU יום שישי 26 אפריל 2019.
Main() { int fact; fact = Factorial(4); } main fact.
ICS103 Programming in C Lecture 11: Recursive Functions
ETE 132 Lecture 6 By Munirul Haque.
Recursion.
CPS125.
Presentation transcript:

C Programming

Last Lecture Reminder Functions Named Piece of Code May have a value Return Statement May have input parameters Can function of type int return char value?

Why to Use Functions? Break problem down into smaller sub-tasks Modularity – hides the implementation details We don’t have to keep writing the same thing over and over Make a program much easier to read and maintain

Function Returns Value #include <stdio.h> int max(int x, int y){ if (x<y) return y; else return x; } void main(){ int a,b; printf ("Enter two integers\n"); scanf("%d%d",&a,&b); printf("The maximal number is %d\n",max(a,b));

Void Function void ShowHelp(void) { printf("This function explains what this program does…\n"); printf(“Usage:…"); /* ... */ } int main(void) char choice; printf("Please enter your selection: "); scanf("%c", &choice); if (choice==‘h’) ShowHelp(); else if /* Program continues … */

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

Pass-by-value - Example int increment(int b) { b=b+1; return b; } int main(void) int a=5,b=1; a = increment(b); printf("a = %d, b = %d\n", a, b); return 0;

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;

Scope of Variables Local Variables Global Variables Static Variables Declared in the function Global Variables Declared outside of the function Static Variables

Scope – Local Variables int factorial(int n) { int fact = 1; printf(“fact = %d\n", fact); while (n>1) fact *= n; n--; } return fact; #include <stdio.h> int factorial(int n); int main() { int n, fact = 0; printf("Enter a number\n"); scanf("%d", &n); fact = factorial(n); printf("the factorial is %d\n", fact); printf(“n = %d\n", n); return 0; }

Scope – Global Variables int factorial(int n) { int fact = 1; printf(“GlobalVar = %d\n", ++GlobalVar); while (n>1) fact *= n; n--; } return fact; #include <stdio.h> int GlobalVar = 4; int factorial(int n); int main() { int n, fact = 0; printf(“GlobalVar = %d\n", ++GlobalVar); printf("Enter a number\n"); scanf("%d", &n); fact = factorial(n); printf("the factorial is %d\n", fact); return 0; }

Scope – Static Variables int factorial(int n) { int fact = 1; static int StatVar = 0; printf(“StatVar = %d\n", ++StatVar); while (n>1) fact *= n; n--; } return fact; #include <stdio.h> int factorial(int n); int main() { int n, fact = 0; printf("Enter a number\n"); scanf("%d", &n); for (i = 0; i < 5; i++) { fact = factorial(n); printf("the factorial is %d\n", fact); } return 0;

Recursion

חלוקת השוקולד רוצים לחלק חפיסת שוקולד של 32 קוביות בין 32 תלמידים. רוצים לחלק חפיסת שוקולד של 32 קוביות בין 32 תלמידים. כל חלוקה לוקחת שנייה אחת. השוקולד נמס תוך 6 שניות. כיצד אפשר לבצע את חלוקת החפיסה כך שהשוקולד לא יִמס?

פתרון לשתף את כל הכיתה בחלוקה: המורה תחלק את השוקולד ל-2 ותמסור לשני תלמידים. כל אחד מהתלמידים יחלק את החתיכה שקיבל ל-2 וימסור לשני תלמידים. התהליך יסתיים כאשר כל תלמיד יחזיק קובייה אחת.

Recurrent Algorithm Definition Algorithm that solves the problem by invoking itself on the same simpler\smaller problem until the problem can be solved directly.

Factorial n! = 1*2*3*… *(n-1)*n – General algorithm

Recurrent Problem Definition - Factorial 0! = 1 – Basic case n! = n*(n-1)! – Recurrent step – solving complex case for n>0 – stop condition

Factorial int factorial(int n) { int fact = 1; while (n>1) fact *= n; n--; } return fact; #include <stdio.h> int main() { int n, fact = 0; printf("Enter a number\n"); scanf("%d", &n); fact = factorial(n); printf("the factorial is %d\n", fact); printf(“n = %d\n", n); return 0; }

Recurrent Factorial int recFactorial(int n){ if(n<=1) return 1; return n*recFactorial(n-1); } #include <stdio.h> int main() { int n, fact = 0; printf("Enter a number\n"); scanf("%d", &n); fact = recFactorial(n); printf("the factorial is %d\n", fact); printf(“n = %d\n", n); return 0; }

Recurrent Problem Definition - Factorial 0! = 1 – Basic case n! = n*(n-1)! – Recurrent step – solving complex case for n>0 – Stop condition

Stars Print #include <stdio.h> void star(int n){ while (n<=0){ printf("*"); n--; } void main(){ star(3);

Stars Print #include <stdio.h> void star(int n){ printf("*"); star (n-1); } void main(){ star(3);

Stars Print #include <stdio.h> void star(int n){ if (n<=0) return; printf("*"); star (n-1); } void main(){ star(3);

Types of Recursion Linear Recursion Tail Recursion Binary Recursion רקורסיה "רגילה" Tail Recursion רקורסיית זנב Binary Recursion רקורסיה כפולה Mutual Recursion רקורסיה הדדית

Linear Recursion Call step(n-1) Solve step n Return Result

Solve step (n-1) Call step(n-2) Tail Recursion Solve step n Call step(n-1) Solve step (n-1) Call step(n-2) Solve step 1 Return Result

Binary Recursion Solve step n Call step(n-1) return Solve step 1 return

Mutual Recursion A: Solve step n Call B(n-1) B: Solve step (n-1) Call B(n-2) A: Solve step n-2 Call B(n-3) B: Solve step (n-3) Call B(n-4)

print1 #include <stdio.h> void print1(int n){ if (n==0)return; printf ("%d\n",n); print1(n-1); } void main(){ print1(5);

print2 #include <stdio.h> void print2(int n){ if (n==0)return; print2(n-1); printf ("%d\n",n); } void main(){ print2(5);

Another example - power Xy = x*x*…*x Recursive definitions (assume non-negative y): Base: x0=1 Xy = X*(Xy-1) Xy = (Xy/2)2 (for even y’s only) y times

int rec_pow(int x, int y) { if (y == 0) return 1; if (y%2 == 0) return square(rec_pow(x,y/2)); else return x*rec_pow(x,y-1); }

Exercise Write a program that receives two non- negative integers and computes their product recursively. Hint: Notice that the product a*b is actually a+a+…+a (b times).

double power(double val, unsigned pow) { if(pow == 0) / double power(double val, unsigned pow) { if(pow == 0) /* pow(x, 0) returns 1 */ return(1.0); else return(power(val, pow - 1) * val); }