Unit III Functions. C functions can be classified into two categories, namely, library functions and user defined functions.
|
|
- Shanon Lewis
- 6 years ago
- Views:
Transcription
1 Unit III Functions Functions: Function Definition, Function prototype, types of User Defined Functions, Function calling mechanisms, Built-in string handling and character handling functions, recursion, Storage Classes, multi-file compilation, Function with Arrays. C functions can be classified into two categories, namely, library functions and user defined functions. User defined functions has to be developed by the user at the time of writing a program. Function is a self contained block of code that performs a particular task. Need for user defined functions or Advantages of user defined function: 1. The program will be easier to understand, maintain and debug. 2. Reusable codes that can be used in other programs. 3. A large program can be divided into smaller modules. Hence, a large project can be divided among many programmers. Function prototype or function declaration: Function must be declared before it is used in any program, same as a variable must be declared before it is used. This declaration is called function prototype or function declaration. return type function_name (arguments list); Here, i. return type is any valid data type, ii. function name is any valid 'C' name, iii. argument list contains data type of arguments separated with comma (,) if more than one argument is present in the list. Syntax for function definition: return_type function_name(argument list) statements; return ; //optional Prepared by Aravinda Kasukurthi, CSE, RVRJCCE 1
2 Example program to explain in detail about function: int cube(int); // function prototype int x,c; printf("enter x to compute cube\n"); scanf("%d",&x); c=cube(x); // calling function, call by value, and x is actual argument or parameter printf("cube of %d = %d\n",x,c); int cube(int n) //Function Header, n is formal argument Function Definition or called function return n*n*n; A function must follow the same rules of formation of variable names in C. In the function prototype, argument list contains data types separated with comma with optional variable names and this statement ends with semicolon. In the calling function, only variable names are used along with the function name and ends with semicolon. When the compiler encounters a function call, the control is transferred to the function definition. This function is then executed line by line and a value is returned when the return statement is encountered. In the called function or function definition, variable names along with their data types are used. Open and close curly braces are used to define a block of statements. And an optional return statement is used in the function definition. If any data type is specified in the return type part, it is necessary to use return statement to return a quantity to the calling function. This situation arises when the value returned is based on certain conditions. For example, in Linear search function, for(i=0;i<n;i++) if(a[i]==ele) return i; return -1; Prepared by Aravinda Kasukurthi, CSE, RVRJCCE 2
3 In this example, if the given search element is present in the input array, then that element s position is returned. If that element is not present in the input array, -1 is returned. A function may have more than one return statement Here, Actual arguments are included in the function calling part. Formal arguments are dummy arguments means actual argument values are just copied into these formal arguments. Types of user defined functions: 1. Functions with no arguments and no return value. 2. Functions with arguments and no return value. 3. Functions with no arguments and return value. 4. Functions with arguments and return value. Functions with no arguments and no return value: void printline(); printf("name\t\troll Number\n"); printline(); printf("anuradha\t1001\nsasi Latha\t1003\n"); printline(); void printline() int i; for(i=1;i<=40;i++) printf("-"); printf("\n"); Functions with arguments and no return value: //Product of prime integers from 1 to N //return type functionname (arguments list); Prepared by Aravinda Kasukurthi, CSE, RVRJCCE 3
4 void primeprod(int); // Function prototype int n; printf("enter n\n"); scanf("%d",&n); primeprod(n); // Function calling void primeprod(int n) // Function Definition int i,j,cnt,p; for(i=1,p=1;i<=n;i++) for(j=1,cnt=0;j<=i;j++) if(i%j==0) cnt++; if(cnt==2) p=p*i; printf("product of prime integers=%d\n",p); Functions with no arguments and return value: //Product of non-prime integers from 1 to N int nprimeprod(); printf("product of non-prime integers=%d\n",nprimeprod()); int nprimeprod() int i,j,cnt,p; int n; printf("enter n\n"); scanf("%d",&n); for(i=1,p=1;i<=n;i++) for(j=1,cnt=0;j<=i;j++) if(i%j==0) cnt++; Prepared by Aravinda Kasukurthi, CSE, RVRJCCE 4
5 if(cnt!=2) p=p*i; return(p); Functions with arguments and return value: //Factorial of given number int fact(int),f; int n; printf("enter n\n"); scanf("%d",&n); f=fact(n); printf("factorial of %d = %d\n",n,f); int fact(int n) int i,f; for(i=1,f=1;i<=n;i++) f=f*i; return f; // Fib term or not int n; void fibterm(int); printf("enter n\n"); scanf("%d",&n); fibterm(n); void fibterm(int n) int a,b,c; if(n==0 n==1) Prepared by Aravinda Kasukurthi, CSE, RVRJCCE 5
6 printf("%d is fib term\n",n); return; for(a=0,b=1,c=0;c<=n;) c=a+b; a=b; b=c; if(c==n) printf("%d is fib term\n",n); break; if(c>n) printf("%d is not fib term\n",n); Function calling mechanisms: A function can be called in two ways: a. call by value. b. call by reference. Call by value: Actual arguments are included in the function calling part. Formal arguments are dummy arguments means actual argument values are just copied into these formal arguments, any changes made to these formal arguments are not reflected to the calling function. Because by default function is called by call by value. void swap(int,int); int a,b; printf("enter a,b values\n"); scanf("%d%d",&a,&b); printf("a,b values before swap function a=%d\tb=%d\n",a,b); swap(a,b); printf("\na,b values after swap function a=%d\tb=%d\n",a,b); Prepared by Aravinda Kasukurthi, CSE, RVRJCCE 6
7 void swap(int x,int y) int t=x; x=y; y=t; Enter a,b values 4 5 a,b values before swap function a=4 b=5 a,b values after swap function a=4 b=5 Call by reference: By using call by value only one value is return to calling function by explicitly use the return statement. There are situations to return more than one value to calling function. This is achieved by using call by reference mechanism. Actual arguments are included in the function calling part by passing the addresses of variables a, b are passed as arguments to function and received as pointers. Any changes made to these arguments are directly modified in their address locations, so returned to the calling function. void swap(int*,int*); int a,b; printf("enter a,b values\n"); scanf("%d%d",&a,&b); printf("a,b values before swap function a=%d\tb=%d\n",a,b); swap(&a,&b); printf("\na,b values after swap function a=%d\tb=%d\n",a,b); void swap(int *x,int *y) int t = *x; *x = *y; *y = t; Enter a, b values Prepared by Aravinda Kasukurthi, CSE, RVRJCCE 7
8 a, b values before swap function a=10 b=20 a, b values after swap function a=20 b=10 Function with Arrays: When an array is passed as argument to a function, then by default array is passed as reference. Because the base address of an array is passed to the function definition. So, any changes made to that array are reflected to the calling function without using return statement. Example program to sort given array elements using bubble sort by passing array as argument to bsort function. void bsort(int [20],int); int n,i,a[20]; printf("enter no. of elements\n"); scanf("%d",&n); printf("enter array elements\n"); for(i=0;i<n;i++) scanf("%d",&a[i]); bsort(a,n); //calling function printf("elements after sorting\n"); for(i=0;i<n;i++) printf("%d\t",a[i]); printf("\n"); void bsort(int a[20],int n) // function definition int i,j,t; for(i=0;i<n-1;i++) for(j=0;j<n-i-1;j++) if(a[j]>a[j+1]) t=a[j]; a[j]=a[j+1]; a[j+1]=t; Prepared by Aravinda Kasukurthi, CSE, RVRJCCE 8
9 enter no. of elements 5 enter array elements Elements after sorting After completion of bsort function, the resultant sorted elements are displayed in main function without using any return statement in the called function. The elements are in sorted order. Recursion: A function that calls itself is known as a recursive function. And, this technique is known as recursion. Recursion function must contain termination condition otherwise it will go into an infinite loop Recursive functions are very useful to solve many mathematical problems, such as calculating the factorial of a number, generating Fibonacci series, etc. Sum of n natural numbers using recursion: How recursion internally works: Prepared by Aravinda Kasukurthi, CSE, RVRJCCE 9
10 Advantages and Disadvantages of Recursion Recursion makes program neat and cleaner. All algorithms can be defined recursively which makes it easier to visualize and prove. If the speed of the program is vital then, you should avoid using recursion. Recursions use more memory and are generally slow. Instead, you can use loop. // Binary search using recursion (previous paper question): int bsearch(int [20],int,int,int); void bsort(int [20],int); int n,i,a[20],pos,ele; printf("enter no. of elements\n"); scanf("%d",&n); printf("enter array elements\n"); for(i=0;i<n;i++) scanf("%d",&a[i]); bsort(a,n); printf("elements after sorting\n"); for(i=0;i<n;i++) printf("%d\t",a[i]); printf("\nenter element to search\n"); scanf("%d",&ele); pos=bsearch(a,0,n-1,ele); if(pos!=-1) printf("\n%d element found in %d position\n",ele,pos); else printf("\n %d element not found\n",ele); void bsort(int a[20],int n) int i,j,t; for(i=0;i<n-1;i++) for(j=0;j<n-i-1;j++) if(a[j]>a[j+1]) t=a[j]; a[j]=a[j+1]; Prepared by Aravinda Kasukurthi, CSE, RVRJCCE 10
11 a[j+1]=t; int bsearch(int a[20],int low,int high,int ele) int mid; while(low<=high) mid=(low+high)/2; if(a[mid]==ele) return mid; else if(ele<a[mid]) return bsearch(a,low,mid-1,ele); else return bsearch(a,mid+1,high,ele); enter no. of elements 5 enter array elements Elements after sorting Enter element to search element found in 3 position // Factorial of a number using recursion int fact(int),f; int n; printf("enter n\n"); scanf("%d",&n); f=fact(n); printf("factorial of %d = %d\n",n,f); Prepared by Aravinda Kasukurthi, CSE, RVRJCCE 11
12 int fact(int n) if(n==0 n==1) return 1; else return n*fact(n-1); enter n 4 Factorial of 4 = 24 Factorial recursive function working: Assume n=4. Since the value of n is not 1, the statement return n*fact(n-1); will be executed with n=4. That is, return 4 * factorial(3); will be evaluated. The expression on the right-hand side includes a call to factorial with n = 3. This call return the following value: 3 * fact(2); Once again, fact function is called with n = 2. This time, the function returns 2*fact(1); Once again, fact function is called with n = 1. This time, the function returns 1. The sequence of operations can be summarized as follows: return 4 * fact(3) return 4 * 3 * fact(2) return 4 * 3 * 2 * fact(1) return 4 * 3 * 2 * 1 return 24 Recursive functions can be effectively used to solve problems where the solution is expressed in terms of successively applying the same solution to subsets of the problem. When recursive functions are used, it must have an if statement somewhere to force the function to return without the recursive call being executed. Otherwise, the function will never return. Prepared by Aravinda Kasukurthi, CSE, RVRJCCE 12
13 // Fibonacci series using recursion int i,n; int fib(int); printf("enter n\n"); scanf("%d",&n); for(i=0;i<n;i++) printf("%d\t",fib(i)); int fib(int n) if(n==0 n==1) return n; else return fib(n-1)+fib(n-2) ; enter n //gcd using recursion int int a,b; int gcd(int,int); printf("enter 2 numbers:"); scanf("%d%d",&a,&b); printf("greatest Common Divisor is %d",gcd(a,b)); return 0; int gcd(int a,int b) if(b==0) return a; else return gcd(b,a%b); Enter 2 numbers: Prepared by Aravinda Kasukurthi, CSE, RVRJCCE 13
14 8 6 Greatest Common Divisor is 2 Storage classes: The storage class determines the part of memory where storage allocated for a variable and how long the storage allocation continues to exist. Scope: The scope of variable determines over what part(s) of the program a variable is actually available for use. (active) or The region of a program in which a variable is available for use. Visibility: The program s ability to access a variable from the memory. Lifetime: The lifetime of a variable is the duration of time in which a variable exists in the memory during execution. Local variables: Local variables are accessed only in a block where those variables are declared. Example: void local1(); void local2(); int m=1; local1(); printf("in main m=%d\n",m); void local1() int m=11; local2(); printf("in local1 m=%d\n",m); void local2() int m=22; printf("in local2 m=%d\n",m); Prepared by Aravinda Kasukurthi, CSE, RVRJCCE 14
15 In local2 m=22 In local1 m=11 In main m=1 Global variables: Once a variable has been declared as global, any function can use it and change its value. Then, subsequent functions can reference only that new value. Global variables are initialized to zero by default. Global variable is that it is visible only from the point of declaration to the end of the program. Example: void global1(); void global2(); int m=10; global1(); m=m+1; printf("in main m=%d\n",m); void global1() global2(); m=m+11; printf("in global1 m=%d\n",m); void global2() m=m+22; printf("in global2 m=%d\n",m); In global2 m=32 In global1 m=43 In main m=44 Prepared by Aravinda Kasukurthi, CSE, RVRJCCE 15
16 Storage classes are of 4 types: 1. Automatic variables 2. Static variables 3. Register variables 4. External variables Storage specifier auto static register extern Description Storage place: CPU Memory Initial value: garbage Scope: local Lifetime: within the function only Storage place: CPU Memory Initial value: zero Scope: local Lifetime: Retains the value of the variable between different function calls. Storage place: CPU Registers Initial value: garbage Scope: local Lifetime: with in the function only Storage place: CPU Memory Initial value: zero Scope: global Lifetime: Till end of the main program. Variable definition might be anywhere in the C program. Automatic variables: int i; void autov(); for(i=1;i<=3;i++) autov(); void autov() auto int x=0; x=x+1; printf("x=%d\n",x); Prepared by Aravinda Kasukurthi, CSE, RVRJCCE 16
17 x=1 x=1 x=1 When i=1, autov() function is called for 1 st time: Because of the initial value of the automatic variables is garbage, explicitly assigning 0 to x. When x=x+1, x is incremented by 1. Then x=1 is printed. When i=2, autov() function is called for 2 nd time: Because Automatic variable s life time is local and initial value of the automatic variables is garbage, again explicitly assigning 0 to x. When x=x+1, x is incremented by 1. Then x=1 is printed. Static variables: int i; void staticv(); for(i=1;i<=3;i++) staticv(); void staticv() static int x; x=x+1; printf("x=%d\n",x); x=1 x=2 x=3 When i=1, staticv() function is called for 1 st time: Because of the initial value of the static variables is zero (0), there is no need to explicit assignment of x. When x=x+1, x is incremented by 1. Then x=1 is printed. When i=2, staticv() function is called for 2 nd time: Because of static variable s life time is throughout the program, x value is retained as 1. When x=x+1, then x=1+1=2. Then x=2 is printed. Prepared by Aravinda Kasukurthi, CSE, RVRJCCE 17
18 Register variables: register int i; void regv(); for(i=1;i<=3;i++) regv(); void regv() register int x=0; x=x+1; printf("\nx=%d",x); x=1 x=1 x=1 When i=1, regv() function is called for 1 st time: Because of the initial value of the register variables is garbage, explicitly assigning 0 to x. When x=x+1, x is incremented by 1. Then x=1 is printed. When i=2, regv() function is called for 2 nd time: Because Register variable s life time is local and initial value of the automatic variables is garbage, again explicitly assigning 0 to x. When x=x+1, x is incremented by 1. Then x=1 is printed. Extern variables: extern int y; // external declaration void globe1(); void globe2(); globe1(); y=y+10; printf("in main y=%d\n",y); globe2(); Prepared by Aravinda Kasukurthi, CSE, RVRJCCE 18
19 void globe1() y=y+1; printf("in globe1 y=%d\n",y); int y; //definition void globe2() y=y*5; printf("in globe2 y=%d\n",y); In globe1 y=1 In main y=11 In globe2 y=55 Here, y is a global variable and by default initial value of global variable is zero (0). But global variable y is declared after the and globe1() functions. So, y is unavailable to those two functions even it is declared as global variable. That variable y is made available to those two functions by declaring that variable as external variable. extern int y; //external declaration (no memory is allocated to this variable). This declaration informs the compiler, that y is declared as external variable and that variable is declared as a global variable somewhere in the program. int y; //definition When this statement is encountered in the program, compiler allocates memory to that variable. Multi file compilation: // Contents of file1.c extern int m; void externf(); int i=10; m=m+50; printf("in main i=%d\tm=%d\n",i,m); externf(); externf2(); Prepared by Aravinda Kasukurthi, CSE, RVRJCCE 19
20 externf1(); void externf() int j=11; m=m*5; printf("externf m=%d\tj=%d\n",m,j); //file2.c int m; void externf1() int k=111; m=500; printf("in extern f1 m=%d\tk=%d\n",m,k); void externf2() int l=222; m=1000; printf("in extern f2 m=%d\tl=%d\n",m,l); In the file1.c, 'm' is declared as external variable; here no memory is allocated to that variable 'm'. And that variable is globally defined in another file file2.c. That variable 'm' is made available to the file1.c by compiling these two files at the same time. //Compilation $cc file1.c file2.c $./a.out In main i=10 m=50 Externf m=250 j=11 In extern f2 m=1000 l=222 In extern f1 m=500 k=111 Prepared by Aravinda Kasukurthi, CSE, RVRJCCE 20
int Return the number of characters in string s.
1a.String handling functions: Function strcmp(const char *s1, const char *s2) strcpy(char *s1, const char *s2) strlen(const char *) strcat(char *s1, Data type returned int Task Compare two strings lexicographically.
More informationFUNCTIONS. Without return With return Without return With return. Example: function with arguments and with return value
FUNCTIONS Definition: A is a set of instructions under a name that carries out a specific task, assigned to it. CLASSIFICATION of s: 1. User defined s (UDF) 2. Library s USER DEFINED FUNCTIONS Without
More informationUnit 3 Functions. 1 What is user defined function? Explain with example. Define the syntax of function in C.
1 What is user defined function? Explain with example. Define the syntax of function in C. A function is a block of code that performs a specific task. The functions which are created by programmer are
More informationUNIT III (PART-II) & UNIT IV(PART-I)
UNIT III (PART-II) & UNIT IV(PART-I) Function: it is defined as self contained block of code to perform a task. Functions can be categorized to system-defined functions and user-defined functions. System
More information// CSE/CE/IT 124 JULY 2015, 2.a. algorithm to inverse the digits of a given integer. Step 1: Start Step 2: Read: NUMBER Step 3: r=0,rev=0
// CSE/CE/IT 124 JULY 2015, 2a algorithm to inverse the digits of a given integer Step 1: Start Step 2: Read: NUMBER Step 3: r=0,rev=0 Step 4: repeat until NUMBER > 0 r=number%10; rev=rev*10+r; NUMBER=NUMBER/10;
More informationUNIT 3 FUNCTIONS AND ARRAYS
UNIT 3 FUNCTIONS AND ARRAYS Functions Function definitions and Prototypes Calling Functions Accessing functions Passing arguments to a function - Storage Classes Scope rules Arrays Defining an array processing
More informationFUNCTIONS OMPAL SINGH
FUNCTIONS 1 INTRODUCTION C enables its programmers to break up a program into segments commonly known as functions, each of which can be written more or less independently of the others. Every function
More information& Technology. G) Functions. void. Argument2, Example: (Argument1, Syllabus for 1. 1 What. has a unique. 2) Function name. passed to.
Computer Programming and Utilization (CPU) 110003 G) Functions 1 What is user defined function? Explain with example. Define the syntax of function in C. A function is a block of code that performs a specific
More informationCSE 230 Intermediate Programming in C and C++ Functions
CSE 230 Intermediate Programming in C and C++ Functions Fall 2017 Stony Brook University Instructor: Shebuti Rayana shebuti.rayana@stonybrook.edu http://www3.cs.stonybrook.edu/~cse230/ Concept of Functions
More informationProgramming & Data Structure Laboratory. Day 2, July 24, 2014
Programming & Data Structure Laboratory Day 2, July 24, 2014 Loops Pre and post test loops for while do-while switch-case Pre-test loop and post-test loop Condition checking True Loop Body False Loop Body
More informationChapter 4 Functions By C.K. Liang
1 Chapter 4 Functions By C.K. Liang What you should learn? 2 To construct programs modularly from small pieces called functions Math functions in C standard library Create new functions Pass information
More informationCS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-0-0)
CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-0-0) Class Teacher: Pralay Mitra Department of Computer Science and Engineering Indian Institute of Technology Kharagpur An Example: Random
More informationProgramming & Data Structure Laboratory. Arrays, pointers and recursion Day 5, August 5, 2014
Programming & Data Structure Laboratory rrays, pointers and recursion Day 5, ugust 5, 2014 Pointers and Multidimensional rray Function and Recursion Counting function calls in Fibonacci #include
More informationQ 1. Attempt any TEN of the following:
Subject Code: 17212 Model Answer Page No: 1 / 26 Important Instructions to examiners: 1) The answers should be examined by key words and not as word-to-word as given in the model answer scheme. 2) The
More informationME 172. C Programming Language Sessional Lecture 8
ME 172 C Programming Language Sessional Lecture 8 Functions Functions are passages of code that have been given a name. C functions can be classified into two categories Library functions User-defined
More informationWhat Is a Function? Illustration of Program Flow
What Is a Function? A function is, a subprogram that can act on data and return a value Each function has its own name, and when that name is encountered, the execution of the program branches to the body
More informationFaculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions
Faculty of Engineering Computer Engineering Department Islamic University of Gaza 2013 C++ Programming Language Lab # 6 Functions C++ Programming Language Lab # 6 Functions Objective: To be familiar with
More informationFunctions. (transfer of parameters, returned values, recursion, function pointers).
Functions (transfer of parameters, returned values, recursion, function pointers). A function is a named, independent section of C/C++ code that performs a specific task and optionally returns a value
More information15 FUNCTIONS IN C 15.1 INTRODUCTION
15 FUNCTIONS IN C 15.1 INTRODUCTION In the earlier lessons we have already seen that C supports the use of library functions, which are used to carry out a number of commonly used operations or calculations.
More informationCS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-1-0) Introduction to arrays
CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-1-0) Introduction to arrays 1 What are Arrays? Arrays are our first example of structured data. Think of a book with pages numbered 1,2,...,400.
More information2.2 Pointers. Department of CSE
2.2 Pointers 1 Department of CSE Objectives To understand the need and application of pointers To learn how to declare a pointer and how it is represented in memory To learn the relation between arrays
More informationDepartment of Computer Science & Engineering Indian Institute of Technology Kharagpur. Practice Sheet #06
Department of Computer Science & Engineering Indian Institute of Technology Kharagpur Practice Sheet #06 Topic: Recursion in C 1. What string does the following program print? #include #include
More informationGovernment Polytechnic Muzaffarpur.
Government Polytechnic Muzaffarpur. Name of the Lab: COMPUTER PROGRAMMING LAB (MECH. ENGG. GROUP) Subject Code: 1625408 Experiment: 1 Aim: Programming exercise on executing a C program. If you are looking
More informationFunctions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.
Lab 4 Functions Introduction: A function : is a collection of statements that are grouped together to perform an operation. The following is its format: type name ( parameter1, parameter2,...) { statements
More informationb. array s first element address c. base address of an array d. all elements of an array e. both b and c 9. An array elements are always stored in a.
UNIT IV 1. Appropriately comment on the following declaration int a[20]; a. Array declaration b. array initialization c. pointer array declaration d. integer array of size 20 2. Appropriately comment on
More informationUnit 1 - Arrays. 1 What is an array? Explain with Example. What are the advantages of using an array?
1 What is an array? Explain with Example. What are the advantages of using an array? An array is a fixed-size sequenced collection of elements of the same data type. An array is derived data type. The
More information1) Write a C Program to check whether given year is Leap year or not. AIM: A C Program to check whether given year is Leap year or not.
1) Write a C Program to check whether given year is Leap year or not. AIM: A C Program to check whether given year is Leap year or not. #include int year; printf("enter a year:"); scanf("%d",&year);
More informationSUHAIL T A
SUHAIL T A Functions A number of statements grouped into a single logical unit C pgm is a collection of functions Self contained pgm segment that carries out a specific task main is a special recognized
More informationF.Y. Diploma : Sem. II [CO/CD/CM/CW/IF] Programming in C
F.Y. Diploma : Sem. II [CO/CD/CM/CW/IF] Programming in C Time : 3 Hrs.] Prelim Question Paper Solution [Marks : 70 Q.1 Attempt any FIVE of the following : [10] Q.1 (a) List any four relational operators.
More informationUnit 7. Functions. Need of User Defined Functions
Unit 7 Functions Functions are the building blocks where every program activity occurs. They are self contained program segments that carry out some specific, well defined task. Every C program must have
More information***************OUTPUT*************************** Enter the two number The addition of two number is =100
/* 1. Program to calculate the addition of two number using function */ int n1,n2,result; printf(" Enter the two number \n"); scanf("%d%d",&n1,&n2); result=addnum(n1,n2); printf(" The addition of two number
More informationTwo Approaches to Algorithms An Example (1) Iteration (2) Recursion
2. Recursion Algorithm Two Approaches to Algorithms (1) Iteration It exploits while-loop, for-loop, repeat-until etc. Classical, conventional, and general approach (2) Recursion Self-function call It exploits
More informationUEE1302(1066) F12: Introduction to Computers and Programming Function (II) - Parameter
UEE1302(1066) F12: Introduction to Computers and Programming Function (II) - Parameter What you will learn from Lab 7 In this laboratory, you will understand how to use typical function prototype with
More informationBranching is deciding what actions to take and Looping is deciding how many times to take a certain action.
3.0 Control Statements in C Statements The statements of a C program control the flow of program execution. A statement is a command given to the computer that instructs the computer to take a specific
More informationM1-R4: Programing and Problem Solving using C (JAN 2019)
M1-R4: Programing and Problem Solving using C (JAN 2019) Max Marks: 100 M1-R4-07-18 DURATION: 03 Hrs 1. Each question below gives a multiple choice of answers. Choose the most appropriate one and enter
More information'C' Programming Language
F.Y. Diploma : Sem. II [DE/EJ/ET/EN/EX] 'C' Programming Language Time: 3 Hrs.] Prelim Question Paper Solution [Marks : 70 Q.1 Attempt any FIVE of the following : [10] Q.1(a) Define pointer. Write syntax
More informationMemory Allocation in C
Memory Allocation in C When a C program is loaded into memory, it is organized into three areas of memory, called segments: the text segment, stack segment and heap segment. The text segment (also called
More informationStandard Version of Starting Out with C++, 4th Edition. Chapter 19 Recursion. Copyright 2003 Scott/Jones Publishing
Standard Version of Starting Out with C++, 4th Edition Chapter 19 Recursion Copyright 2003 Scott/Jones Publishing Topics 19.1 Introduction to Recursion 19.2 The Recursive Factorial Function 19.3 The Recursive
More informationSUMMER 13 EXAMINATION Model Answer
Important Instructions to examiners: 1) The answers should be examined by key words and not as word-to-word as given in the model answer scheme. 2) The model answer and the answer written by candidate
More informationPESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100 Department of Basic Science and Humanities
PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100 Department of Basic Science and Humanities Continuous Internal Evaluation Test 2 Date: 0-10- 2017 Marks: 0 Subject &
More informationFunctions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.
Functions In general, functions are blocks of code that perform a number of pre-defined commands to accomplish something productive. You can either use the built-in library functions or you can create
More informationLecture 04 FUNCTIONS AND ARRAYS
Lecture 04 FUNCTIONS AND ARRAYS 1 Motivations Divide hug tasks to blocks: divide programs up into sets of cooperating functions. Define new functions with function calls and parameter passing. Use functions
More informationMAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC Certified)
Subject Code: 17212 Model Answer Page No: 1/28 Important Instructions to examiners: 1) The answers should be examined by key words and not as word-to-word as given in themodel answer scheme. 2) The model
More informationArray. Arijit Mondal. Dept. of Computer Science & Engineering Indian Institute of Technology Patna IIT Patna 1
IIT Patna 1 Array Arijit Mondal Dept. of Computer Science & Engineering Indian Institute of Technology Patna arijit@iitp.ac.in Array IIT Patna 2 Many applications require multiple data items that have
More informationC Programming Lecture V
C Programming Lecture V Instructor Özgür ZEYDAN http://cevre.beun.edu.tr/ Modular Programming A function in C is a small sub-program that performs a particular task, and supports the concept of modular
More informationDarshan Institute of Engineering & Technology for Diploma Studies Unit 3
Linear and Non-Linear Data Structures Linear data structure: Linear data structures are those data structure in which data items are arranged in a linear sequence by physically or logically or both the
More informationQuestions Bank. 14) State any four advantages of using flow-chart
Questions Bank Sub:PIC(22228) Course Code:-EJ-2I ----------------------------------------------------------------------------------------------- Chapter:-1 (Overview of C Programming)(10 Marks) 1) State
More informationPROGRAMMING IN C LAB MANUAL FOR DIPLOMA IN ECE/EEE
PROGRAMMING IN C LAB MANUAL FOR DIPLOMA IN ECE/EEE 1. Write a C program to perform addition, subtraction, multiplication and division of two numbers. # include # include int a, b,sum,
More informationIntroduction to C Final Review Chapters 1-6 & 13
Introduction to C Final Review Chapters 1-6 & 13 Variables (Lecture Notes 2) Identifiers You must always define an identifier for a variable Declare and define variables before they are called in an expression
More informationStorage class in C. Automatic variables External variables Static variables Register variables Scopes and longevity of above types of variables.
1 Storage class in C Automatic variables External variables Static variables Register variables Scopes and longevity of above types of variables. 2 Few terms 1. Scope: the scope of a variable determines
More informationCS6202 - PROGRAMMING & DATA STRUCTURES UNIT I Part - A 1. W hat are Keywords? Keywords are certain reserved words that have standard and pre-defined meaning in C. These keywords can be used only for their
More informationChapter-13 USER DEFINED FUNCTIONS
Chapter-13 USER DEFINED FUNCTIONS Definition: User-defined function is a function defined by the user to solve his/her problem. Such a function can be called (or invoked) from anywhere and any number of
More informationComputer Programming: 7th Week Functions, Recursive Functions, Introduction to Pointers
Computer Programming: 7th Week Functions, Recursive Functions, Introduction to Pointers Hazırlayan Asst. Prof. Dr. Tansu Filik Introduction to Programming Languages Previously on Bil-200 Functions: Function
More informationFunctions. Chapter 5
Functions Chapter 5 Function Definition type function_name ( parameter list ) declarations statements For example int factorial(int n) int i, product = 1; for (i = 2; I
More informationMAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
Important Instructions to examiners: 1) The answers should be examined by key words and not as word-to-word as given in the model answer scheme. 2) The model answer and the answer written by candidate
More informationIt is necessary to have a single function main in every C program, along with other functions used/defined by the programmer.
Functions A number of statements grouped into a single logical unit are called a function. The use of function makes programming easier since repeated statements can be grouped into functions. Splitting
More informationArrays a kind of data structure that can store a fixedsize sequential collection of elements of the same type. An array is used to store a collection
Morteza Noferesti Arrays a kind of data structure that can store a fixedsize sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful
More informationFunctions. CS10001: Programming & Data Structures. Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur
Functions CS10001: Programming & Data Structures Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur 1 Recursion A process by which a function calls itself
More informationCHAPTER 4 FUNCTIONS. 4.1 Introduction
CHAPTER 4 FUNCTIONS 4.1 Introduction Functions are the building blocks of C++ programs. Functions are also the executable segments in a program. The starting point for the execution of a program is main
More informationSorting & Searching. Hours: 10. Marks: 16
Sorting & Searching CONTENTS 2.1 Sorting Techniques 1. Introduction 2. Selection sort 3. Insertion sort 4. Bubble sort 5. Merge sort 6. Radix sort ( Only algorithm ) 7. Shell sort ( Only algorithm ) 8.
More informationB.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University
Unit 1 Programming Language and Overview of C 1. State whether the following statements are true or false. a. Every line in a C program should end with a semicolon. b. In C language lowercase letters are
More informationProgramming in C Lab
Programming in C Lab 1a. Write a program to find biggest number among given 3 numbers. ALGORITHM Step 1 : Start Start 2 : Input a, b, c Start 3 : if a > b goto step 4, otherwise goto step 5 Start 4 : if
More informationUNIT III ARRAYS AND STRINGS
UNIT III ARRAYS AND STRINGS Arrays Initialization Declaration One dimensional and Two dimensional arrays. String- String operations String Arrays. Simple programs- sorting- searching matrix operations.
More informationSELECTION STATEMENTS:
UNIT-2 STATEMENTS A statement is a part of your program that can be executed. That is, a statement specifies an action. Statements generally contain expressions and end with a semicolon. Statements that
More informationFunctions. Functions are everywhere in C. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
1 Functions Functions are everywhere in C Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Introduction Function A self-contained program segment that carries
More informationFunctions and Recursion
Functions and Recursion CSE 130: Introduction to Programming in C Stony Brook University Software Reuse Laziness is a virtue among programmers Often, a given task must be performed multiple times Instead
More informationIMPORTANT QUESTIONS IN C FOR THE INTERVIEW
IMPORTANT QUESTIONS IN C FOR THE INTERVIEW 1. What is a header file? Header file is a simple text file which contains prototypes of all in-built functions, predefined variables and symbolic constants.
More informationLAB 7 FUNCTION PART 2
LAB 7 FUNCTION PART 2 School of Computer and Communication Engineering Universiti Malaysia Perlis 1 OBJECTIVES 1. To differentiate the file scope and block scope. 2. To write recursive function. 3. To
More informationSubject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100
Code: DC-05 Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100 NOTE: There are 11 Questions in all. Question 1 is compulsory and carries 16 marks. Answer to Q. 1. must be written in the space
More informationAN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University
AN OVERVIEW OF C, PART 3 CSE 130: Introduction to Programming in C Stony Brook University FANCIER OUTPUT FORMATTING Recall that you can insert a text field width value into a printf() format specifier:
More informationDr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)
Lecture 9 Functions Dr M Kasim A Jalil Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Objectives In this chapter, you will learn: To understand how to construct programs modularly
More informationIntroduction. C provides two styles of flow control:
Introduction C provides two styles of flow control: Branching Looping Branching is deciding what actions to take and looping is deciding how many times to take a certain action. Branching constructs: if
More informationUNIT-IV. Structure is a user-defined data type in C language which allows us to combine data of different types together.
UNIT-IV Unit 4 Command Argument line They are parameters/arguments supplied to the program when it is invoked. They are used to control program from outside instead of hard coding those values inside the
More informationWhy Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ...
Why Pointers Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation. They provide support for dynamic data structures, such
More informationDynamic memory allocation
Dynamic memory allocation outline Memory allocation functions Array allocation Matrix allocation Examples Memory allocation functions (#include ) malloc() Allocates a specified number of bytes
More informationProgramming in C. main. Level 2. Level 2 Level 2. Level 3 Level 3
Programming in C main Level 2 Level 2 Level 2 Level 3 Level 3 1 Programmer-Defined Functions Modularize with building blocks of programs Divide and Conquer Construct a program from smaller pieces or components
More informationUnit 5. Decision Making and Looping. School of Science and Technology INTRODUCTION
INTRODUCTION Decision Making and Looping Unit 5 In the previous lessons we have learned about the programming structure, decision making procedure, how to write statements, as well as different types of
More informationUNDERSTANDING THE COMPUTER S MEMORY
POINTERS UNDERSTANDING THE COMPUTER S MEMORY Every computer has a primary memory. All our data and programs need to be placed in the primary memory for execution. The primary memory or RAM (Random Access
More informationAryan College. Fundamental of C Programming. Unit I: Q1. What will be the value of the following expression? (2017) A + 9
Fundamental of C Programming Unit I: Q1. What will be the value of the following expression? (2017) A + 9 Q2. Write down the C statement to calculate percentage where three subjects English, hindi, maths
More information1. Basics 1. Write a program to add any two-given integer. Algorithm Code 2. Write a program to calculate the volume of a given sphere Formula Code
1. Basics 1. Write a program to add any two-given integer. Algorithm - 1. Start 2. Prompt user for two integer values 3. Accept the two values a & b 4. Calculate c = a + b 5. Display c 6. Stop int a, b,
More informationA. Year / Module Semester Subject Topic 2016 / V 2 PCD Pointers, Preprocessors, DS
Syllabus: Pointers and Preprocessors: Pointers and address, pointers and functions (call by reference) arguments, pointers and arrays, address arithmetic, character pointer and functions, pointers to pointer,initialization
More informationC: How to Program. Week /Apr/16
C: How to Program Week 8 2006/Apr/16 1 Storage class specifiers 5.11 Storage Classes Storage duration how long an object exists in memory Scope where object can be referenced in program Linkage specifies
More informationA PROBLEM can be solved easily if it is decomposed into parts. Similarly a C program decomposes a program into its component functions.
FUNCTIONS IN C A PROBLEM can be solved easily if it is decomposed into parts. Similarly a C program decomposes a program into its component functions. Big problems require big programs too big to be written
More informationFunctions. Autumn Semester 2009 Programming and Data Structure 1. Courtsey: University of Pittsburgh-CSD-Khalifa
Functions Autumn Semester 2009 Programming and Data Structure 1 Courtsey: University of Pittsburgh-CSD-Khalifa Introduction Function A self-contained program segment that carries out some specific, well-defined
More informationMODULE 3: Arrays, Functions and Strings
MODULE 3: Arrays, Functions and Strings Contents covered in this module I. Using an Array II. Functions in C III. Argument Passing IV. Functions and Program Structure, locations of functions V. Function
More informationC Language Part 2 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee
C Language Part 2 (Minor modifications by the instructor) 1 Scope Rules A variable declared inside a function is a local variable Each local variable in a function comes into existence when the function
More informationM3-R4: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE
M3-R4: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE NOTE: 1. There are TWO PARTS in this Module/Paper. PART ONE contains FOUR questions and PART TWO contains FIVE questions. 2. PART ONE is to be
More informationCSCI 136 Data Structures & Advanced Programming. Lecture 9 Fall 2018 Instructors: Bills
CSCI 136 Data Structures & Advanced Programming Lecture 9 Fall 2018 Instructors: Bills Administrative Details Remember: First Problem Set is online Due at beginning of class on Friday Lab 3 Today! You
More informationOBJECTIVE QUESTIONS: Choose the correct alternative:
OBJECTIVE QUESTIONS: Choose the correct alternative: 1. Function is data type a) Primary b) user defined c) derived d) none 2. The declaration of function is called a) function prototype b) function call
More informationLecture 04 FUNCTIONS AND ARRAYS
Lecture 04 FUNCTIONS AND ARRAYS 1 Motivations Divide hug tasks to blocks: divide programs up into sets of cooperating functions. Define new functions with function calls and parameter passing. Use functions
More informationNCS 301 DATA STRUCTURE USING C
NCS 301 DATA STRUCTURE USING C Unit-1 Part-2 Recursion Hammad Mashkoor Lari Assistant Professor Allenhouse Institute of Technology www.ncs301ds.wordpress.com Introduction Recursion is defined as defining
More informationLab Instructor : Jean Lai
Lab Instructor : Jean Lai Group related statements to perform a specific task. Structure the program (No duplicate codes!) Must be declared before used. Can be invoked (called) as any number of times.
More informationCSE 2421: Systems I Low-Level Programming and Computer Organization. Functions. Presentation C. Predefined Functions
CSE 2421: Systems I Low-Level Programming and Computer Organization Functions Read/Study: Reek Chapters 7 Gojko Babić 01-22-2018 Predefined Functions C comes with libraries of predefined functions E.g.:
More informationKareemNaaz Matrix Divide and Sorting Algorithm
KareemNaaz Matrix Divide and Sorting Algorithm Shaik Kareem Basha* Department of Computer Science and Engineering, HITAM, India Review Article Received date: 18/11/2016 Accepted date: 13/12/2016 Published
More informationLecture 3: C Programm
0 3 E CS 1 Lecture 3: C Programm ing Reading Quiz Note the intimidating red border! 2 A variable is: A. an area in memory that is reserved at run time to hold a value of particular type B. an area in memory
More informationI2204 ImperativeProgramming Semester: 1 Academic Year: 2018/2019 Credits: 5 Dr Antoun Yaacoub
Lebanese University Faculty of Science Computer Science BS Degree I2204 ImperativeProgramming Semester: 1 Academic Year: 2018/2019 Credits: 5 Dr Antoun Yaacoub I2204- Imperative Programming Schedule 08h00-09h40
More informationAbout Codefrux While the current trends around the world are based on the internet, mobile and its applications, we try to make the most out of it. As for us, we are a well established IT professionals
More informationBasic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces
Basic memory model Using functions Writing functions Basics Prototypes Parameters Return types Functions and memory Names and namespaces When a program runs it requires main memory (RAM) space for Program
More informationfor (i=1; i<=100000; i++) { x = sqrt (y); // square root function cout << x+i << endl; }
Ex: The difference between Compiler and Interpreter The interpreter actually carries out the computations specified in the source program. In other words, the output of a compiler is a program, whereas
More informationUnit #2: Recursion, Induction, and Loop Invariants
Unit #2: Recursion, Induction, and Loop Invariants CPSC 221: Algorithms and Data Structures Will Evans 2012W1 Unit Outline Thinking Recursively Recursion Examples Analyzing Recursion: Induction and Recurrences
More information