UNIT 3 FUNCTIONS AND ARRAYS

Size: px
Start display at page:

Download "UNIT 3 FUNCTIONS AND ARRAYS"

Transcription

1 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 an array - Passing arrays to Functions Multidimensional Arrays Arrays and strings

2 FUNCTIONS If a program is divided into functional parts, then each part may be independently coded and later combined into a single unit. These subprograms are called functions. Functions are much easier to understand, debug, and test. Another approach is to design a function that can be called and used whenever required.

3 Advantages It facilitates top-down modular programming as shown below. In this programming style, the high level logic of the overall problem is solved first while the details of each lower-level function are addressed later. Main program Function 1 Function 2 Function 3 Function 4

4 Advantages The length of a source program can be reduced by using functions at appropriate places. It is easy to locate and isolate a faulty function for further investigations. A function may be used by many other programs. This means that a C programmer can build on what others have already done.

5 A multi-function program A function is a self-contained block of code that performs a particular task. Once a function has been designed and packed, it can be treated as a black box that takes some data from the main program and returns a value. The inner details of operation are invisible to the rest of the program. All that the program knows about a function is: What goes in and what comes out.

6 Consider a set of statements as shown below: printline( ) int i; for(i=1;i<40;i++) printf( - ); printf( \n ); The above set of statements defines a function called printline() which could print a line of 39-characters length. This function can be used in a program as follows:

7 main() printline(); printf( This illustrates the use of C functions\n ); printline(); printline( ) int i; for(i=1;i<40;i++) printf( - ); printf( \n );

8 The program will print the following output: This illustrates the use of C functions As we know the program execution always begins with the main() function. During execution of the main(), the first statement encountered is printline(); which indicates that the function printline() is to be executed. At this point the, the program control is transferred to the function printline(); After executing the printline() function which outputs as a line of 39 characters length, the control is transferred back to the main().

9 main() function1(); function2(); function1() function3(); function2() function3() Flow of control in By a A. multi-function Vijay Bharath program

10 SYNTAX:ALL FUNCTION HAVE THE FORM function-name(argument list) argument declaration; local variable declarations; executable statement1; executable statement2; return(expression);

11 A function can have any number of executable statements. A function that does nothing, may not include any executable statements at all. For example: do_nothing() The return statement is the mechanism for returning value to the calling function. This also an optional statement. Its absence indicates that no value is being returned to the called function.

12 Argument List The argument list contains valid variable names separated by commas. The list must be surrounded by parenthesis. Note that no semicolon follows the closing parenthesis. The argument variables receive values from the calling function, thus providing a means for data communication from the calling function to the called function.

13 Examples of function arguments: quadratic(a,b,c) power(x,n) mul(a,b) All arguments variables must be declared for their types after the function header and before the opening brace of the function body. Example: power(x,n) float x; int n;

14 RETURN VALUES AND THEIR TYPES A function may or may not send back any value to the calling function. If it does, it is done through the return statement. The return statement can take one of the following forms return; or return(expression); The plain return does not return any value; it acts much as the closing brace of the function.

15 When the return is encountered, the control is immediately passed back to the calling function. The second form of return with an expression returns the value of the expression. For example, the function mul(x,y) int x, y; int p; p=x*y; return(p); Returns the value of p. The last two statements can be combined into one statement as follows: return(x*y);

16 A function may have more than one return statement. This situation arises when the value returned is based on certain condition. For E.g. if (x<=0) return(0); else return(1); All function by default return an int type. We can force a function to return a particular type of data by using a type specifier in the function header. Example: double product(x,y) float sqr_root(p)

17 Calling a function A function can be called by simply using the function name in a statement. Example : main() int p; p=mul(10,5); printf( %d\n,p); When the compiler encounters a function call, the control is transferred to the function mul(x,y). This function is then executed line by line as described and a value is returned when a return statement is encountered. This value is assigned to p.

18 Valid function statements printf( %d\n, mul(p,q)); Y=mul(p,q) / (p+q); If (mul(m,n) > total) printf( large ); However, a function cannot be used on the left hand side of an assignment statement. For instance: is invalid. mul(a,b) = 15;

19 Write a program to calculate the factorial #include<stdio.h> fact(int n) void main() if (n<=1) return(1); int f; else clrscr(); return(n * fact(n-1)); printf("\n enter the number"); scanf("%d",&n); f=fact(n); printf("\nfactorial of the no. is %d",f); getch();

20 Category of functions A function, may belong to one of the following categories. Category 1: Functions with no arguments and no return values. Category 2: Functions with arguments and no return values. Category 3: Functions with arguments and return values.

21 Category 1: No arguments and No return values When a function has no arguments, there is no data transfer between the calling function and the called function. This is depicted in the following Fig. function 1() functio2(); no input no output Function 2()

22 main() printline(); sum(); printline(); printline( ) int i; output: for(i=1;i<40;i++) printf( - ); enter the first number:25 printf( \n ); enter the second number:38 the sum of numbers is: 63 sum() int a,b,c; Printf( enter the first number: ); scanf( %d,&a); Printf( enter the second number: ); scanf( %d,&b); c=a+b; printf( the sum of numbers is : %d,c); It is important to note that the function sum() receives its data directly from the terminal. When the closing braces of the sum() is reached, the control is transferred back to the calling function main().

23 Category 2: Arguments but No return values The nature of data communication between the calling function and the called function with arguments but no return values is shown in Fig. function 1() function2(a); values of arguments no return value Function 2(f)

24 We shall modify declaration of both the called functions to include arguments as follows: printline(ch) value(p,r,n) The arguments ch,p,r,n are called the formal arguments. For example: value(500,0.12,5) actual arguments would send the values 500, 0.12, and 5 to the function value(p,r,n). So the actual arguments which become the values of the formal arguments of the called function.

25 The actual and formal arguments should match in number, type and order. The values of actual arguments are assigned to the formal arguments on a one to one basis, starting with the first arguments as shown below:

26 Arguments matching between the function call and the called function Function call Called function actual arguments main() function1(a1, a2, a3,....am); function1(f1, f2, f3,..... fn) formal arguments

27 We should ensure that the function call has matching arguments. In case, the actual arguments are more than the formal arguments (m > n), the extra actual arguments are discarded. On the other hand, if the actual arguments are less than the formal arguments, the unmatched formal arguments are initialized to garbage value. Any mismatch in data type may also result in passing of garbage values. Remember no error message will be generated.

28 main() int a,b; printline(); Printf( enter the first number: ); scanf( %d,&a); Printf( enter the second number: ); scanf( %d,&b); sum(a,b); printline(); printline( ) int i; output: for(i=1;i<40;i++) printf( - ); printf( \n ); enter the first number:53 enter the second number:47 the sum of numbers is: 100 sum(m,n) int m,n; int c; c=m+n; printf( the sum of numbers is : %d,c);

29 Category 3: Arguments with return values Two-way data communication between functions. We shall modify the use of two-way data communication between the calling and the called function as follows. function 1() function2(a); values of arguments Function result Function 2(f) return(e);

30 main() int a,b,x; printline(); Printf( enter the first number: ); scanf( %d,&a); Printf( enter the second number: ); scanf( %d,&b); x=sum(a,b); printf( the sum of numbers is : %d,x); printline(); printline( ) int i; output: for(i=1;i<40;i++) printf( - ); printf( \n ); enter the first number:53 enter the second number:47 the sum of numbers is: 100 sum(m,n) int m,n; int c; c=m+n; return(c);

31 Handling of Non-integer function By default the function will return integer type. For example, sum(m,n) float m,n; float c; c=m+n; return(c); does all calculations using float but the return statement will returns only the integer part of SUM. This is due to the absence of type-specifier in the function header.

32 We must do two things to enable a calling function to receive a non-integer value from a called function: 1. The explicit type-specifier, corresponding to the data type required must be mentioned in the function header. The general form of the function header definition is: type-specifier function-name (argument list) argument declaration; function statements; The type-specifier tells the compiler, the type of data the function is to return.

33 2. The called function must be declared at the start of the body in the calling function, like any other variable. This is to tell the calling function the type of data that the function is actually returning. Example: #include<stdio.h> float mul(x,y) #include<conio.h> float x,y; main() return(x*y); float a,b,mul(); double div(); clrscr(); a=12.345; double div(p,q) b=9.82; float p,q; printf("%f\n", mul(a,b)); printf("%f\n", div(a,b)); return(p/q); getch();

34 Nesting of functions C permits nesting of functions freely. main() can call function1(), which calls function2, which calls function3, and soon. There is no limit as to how deeply functions can be nested.

35 Example main() int a,b,c; difference(p,q) float ratio(); int p,q; scanf( %d %d %d,&a,&b,&c); printf( %f\n,ratio(a,b,c)); if(p!=q) return(1); float ratio(x,y,z) else int x,y,z; return(0); if(difference(y,z)) return(x/(y-z)); else return(0.0);

36 Recursion When a called function in turn calls another function a process of chaining occurs. Recursion is a special case of this process, where a function calls itself. A very simple example of recursion is below:- main() printf( this is an example of recursion ); main();

37 Program to calculate the factorial value #include<stdio.h> fact(int n) void main() if (n<=1) return(1); int f; else clrscr(); return(n * fact(n-1)); printf("\n enter the number"); scanf("%d",&n); f=fact(n); printf("\nfactorial of the no. is %d",f); getch();

38 Declaration of storage class Variables in C not only have the data type but also storage class that provides the information about their location and visibility. The storage class decides the portion of the program within which the variables are recognized. Consider the following example:-

39 /* Example of storage class */ int m; main() global variable int i; float balance;... function1() function1() int i; float sum;......

40 The variable m which is declared before the main() function is called global variable. It can be used in all the functions in the program. It need not be declared in other functions. A global variable is also known as external variable. The variables i, balance, sum are called local variables because they are declared inside a function. Local variables are visible and meaningful only inside the function in which they are declared.

41 Note that the variable i has been declared in both the functions. Any change in the value of i in one function does not affect its value in the other. There are four storage classes : Storage class auto static extern register Meaning Local variable known to only to the function in which it is declared. Default is auto. Local variable which exists and retains its value even after the control is transferred to the calling function Global variable known to all functions in the file. Local variable which is stored in the register.

42 The storage class is another qualifier that can be added to a variable declaration as shown below: auto int count; register char ch; static int x; extern long total;

43 Automatic variables Automatic variables are declared inside a function in which they are to be utilized. They are created when the function is called and destroyed automatically when the function is exited. Automatic variables are therefore private (or local) to the function in which they are declared. A variable declared inside a function without storage class specification is, by default, an automatic variable.

44 For instance, the storage class of the variable number in the example below is automatic. main() int number; We may also use the keyword auto to declare automatic variables explicitly. main() auto int number;

45 main() int n, a,b; if(n<=100) int n, sum; /* sum not valid here */ Scope level 1 Scope level 2 The variable n, a and b defined in main() have scope from the beginning to the end of main(). However, the variable n defined in the main() cannot enter into the block of scope level 2 because the scope level 2 contains another variable named n. The second n is available only inside the scope level 2 and no longer available the moment control leaves the if block.

46 External variables Variables that are both alive and active throughout the entire program are known as external variables. They are also known as global variables Unlike local variables, global variables can be accessed by any function in the program. External variables are declared outside the main() function as follows:

47 External variables int number; float length; main() function1() The variable number and length are available for use in all the three functions. In case a local variable and a global variable have the same name, the local variable will have precedence over the global one in the function where it is declared. function2()

48 int x; main() X=10; Printf( x=%d\n,x); Printf( x=%d\n, fun1()); fun3() Printf( x=%d\n,fun2()); Printf( x=%d\n,fun3()); x=x+10; return(x); fun1() X=x+10; return(x); OUTPUT: fun2() int x; X=1; return(x); x=10 X=20 X=1 X=30

49 External declaration In the below program, main() cannot access the variable y as it has been declared after the main() function. This problem is solved by declaring the variable with the storage class extern. main() extern int y;... func1() extern int y;... int y;

50 External declaration Although the variable y has been defined after the both the functions, the external declaration of y inside the function informs the compiler that y is an integer type defined somewhere else in the program. main() extern int y;... func1() extern int y;... int y;

51 Static variable The value of static variables persists until the end of a program. static int x; A static variable may be either an external type or an internal type, depending on the place of declaration. Internal static variables are those which are declared inside a function. The scope of internal static variable extend up to the end of function in which they are defined.

52 Static variable main() int i; for(i=1;i<=3;i++) stat(); stat() static int x=0; output: x=x+1; x=1 printf( x=%d\n,x); x=2 x=3

53 Register variables We can tell the compiler that a variable should be kept in one of the machine s registers, instead of keeping in the memory (where normal variables are stored). Register access is much faster than a memory access, keeping the frequently accessed variable register int count; Only few variables can be placed in the register, it is important to carefully select the variables for this purpose. However, C will automatically convert register variables into nonregister variables once the limit is reached

54

55

56

57

58

59

Unit 7. Functions. Need of User Defined Functions

Unit 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

CSE202-Lec#4. CSE202 C++ Programming

CSE202-Lec#4. CSE202 C++ Programming CSE202-Lec#4 Functions and input/output streams @LPU CSE202 C++ Programming Outline Creating User Defined Functions Functions With Default Arguments Inline Functions @LPU CSE202 C++ Programming What is

More information

It is necessary to have a single function main in every C program, along with other functions used/defined by the programmer.

It 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 information

15 FUNCTIONS IN C 15.1 INTRODUCTION

15 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 information

Functions BCA-105. Few Facts About Functions:

Functions BCA-105. Few Facts About Functions: Functions When programs become too large and complex and as a result the task of debugging, testing, and maintaining becomes difficult then C provides a most striking feature known as user defined function

More information

Storage class in C. Automatic variables External variables Static variables Register variables Scopes and longevity of above types of variables.

Storage 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 information

CSE 230 Intermediate Programming in C and C++ Functions

CSE 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 information

Unit 3 Functions. 1 What is user defined function? Explain with example. Define the syntax of function in C.

Unit 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 information

FUNCTIONS. Without return With return Without return With return. Example: function with arguments and with return value

FUNCTIONS. 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 information

& Technology. G) Functions. void. Argument2, Example: (Argument1, Syllabus for 1. 1 What. has a unique. 2) Function name. passed to.

& 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 information

Unit III Functions. C functions can be classified into two categories, namely, library functions and user defined functions.

Unit III Functions. C functions can be classified into two categories, namely, library functions and user defined functions. 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,

More information

UNIT III (PART-II) & UNIT IV(PART-I)

UNIT 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

Unit 3 Decision making, Looping and Arrays

Unit 3 Decision making, Looping and Arrays Unit 3 Decision making, Looping and Arrays Decision Making During programming, we have a number of situations where we may have to change the order of execution of statements based on certain conditions.

More information

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

Functions. 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 information

Computer Programming & Problem Solving ( CPPS ) Turbo C Programming For The PC (Revised Edition ) By Robert Lafore

Computer Programming & Problem Solving ( CPPS ) Turbo C Programming For The PC (Revised Edition ) By Robert Lafore Sir Syed University of Engineering and Technology. Computer ming & Problem Solving ( CPPS ) Functions Chapter No 1 Compiled By: Sir Syed University of Engineering & Technology Computer Engineering Department

More information

SUHAIL T A

SUHAIL 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 information

CHAPTER 4 FUNCTIONS. 4.1 Introduction

CHAPTER 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 information

Chapter-13 USER DEFINED FUNCTIONS

Chapter-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 information

CSE 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. 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 information

Faculty 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 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 information

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath UNIT - I Introduction to C Programming Introduction to C C was originally developed in the year 1970s by Dennis Ritchie at Bell Laboratories, Inc. C is a general-purpose programming language. It has been

More information

Functions. 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 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 information

Functions. Functions are everywhere in C. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR

Functions. 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 information

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

Functions. 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 information

FUNCTIONS OMPAL SINGH

FUNCTIONS 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

Data Types and Variables in C language

Data Types and Variables in C language Data Types and Variables in C language Basic structure of C programming To write a C program, we first create functions and then put them together. A C program may contain one or more sections. They are

More information

Subject: Fundamental of Computer Programming 2068

Subject: Fundamental of Computer Programming 2068 Subject: Fundamental of Computer Programming 2068 1 Write an algorithm and flowchart to determine whether a given integer is odd or even and explain it. Algorithm Step 1: Start Step 2: Read a Step 3: Find

More information

Functions. (transfer of parameters, returned values, recursion, function pointers).

Functions. (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 information

UIC. C Programming Primer. Bharathidasan University

UIC. C Programming Primer. Bharathidasan University C Programming Primer UIC C Programming Primer Bharathidasan University Contents Getting Started 02 Basic Concepts. 02 Variables, Data types and Constants...03 Control Statements and Loops 05 Expressions

More information

Functions. Arash Rafiey. September 26, 2017

Functions. Arash Rafiey. September 26, 2017 September 26, 2017 are the basic building blocks of a C program. are the basic building blocks of a C program. A function can be defined as a set of instructions to perform a specific task. are the basic

More information

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

IMPORTANT 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 information

Prepared by: Shraddha Modi

Prepared by: Shraddha Modi Prepared by: Shraddha Modi Introduction In looping, a sequence of statements are executed until some conditions for termination of the loop are satisfied. A program loop consist of two segments Body of

More information

C Programming Lecture V

C 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 information

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language 1 History C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC

More information

CS6202 - 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 information

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-0-0)

CS11001/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 information

C: How to Program. Week /Mar/05

C: How to Program. Week /Mar/05 1 C: How to Program Week 2 2007/Mar/05 Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers

More information

Chapter 5 C Functions

Chapter 5 C Functions Chapter 5 C Functions Objectives of this chapter: To construct programs from small pieces called functions. Common math functions in math.h the C Standard Library. sin( ), cos( ), tan( ), atan( ), sqrt(

More information

OBJECTIVE QUESTIONS: Choose the correct alternative:

OBJECTIVE 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 information

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size];

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size]; Arrays An array is a collection of two or more adjacent memory cells, called array elements. Array is derived data type that is used to represent collection of data items. C Array is a collection of data

More information

Tutorial No. 2 - Solution (Overview of C)

Tutorial No. 2 - Solution (Overview of C) Tutorial No. 2 - Solution (Overview of C) Computer Programming and Utilization (2110003) 1. Explain the C program development life cycle using flowchart in detail. OR Explain the process of compiling and

More information

F.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 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 information

Chapter 2 - Introduction to C Programming

Chapter 2 - Introduction to C Programming Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers 2.4 Memory Concepts 2.5 Arithmetic

More information

Flow Control. CSC215 Lecture

Flow Control. CSC215 Lecture Flow Control CSC215 Lecture Outline Blocks and compound statements Conditional statements if - statement if-else - statement switch - statement? : opertator Nested conditional statements Repetitive statements

More information

C Functions. CS 2060 Week 4. Prof. Jonathan Ventura

C Functions. CS 2060 Week 4. Prof. Jonathan Ventura CS 2060 Week 4 1 Modularizing Programs Modularizing programs in C Writing custom functions Header files 2 Function Call Stack The function call stack Stack frames 3 Pass-by-value Pass-by-value and pass-by-reference

More information

AN 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 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 information

Lecture 04 FUNCTIONS AND ARRAYS

Lecture 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 information

M.EC201 Programming language

M.EC201 Programming language Power Engineering School M.EC201 Programming language Lecture 13 Lecturer: Prof. Dr. T.Uranchimeg Agenda The union Keyword typedef and Structures What Is Scope? External Variables 2 The union Keyword The

More information

Programming for Engineers Introduction to C

Programming for Engineers Introduction to C Programming for Engineers Introduction to C ICEN 200 Spring 2018 Prof. Dola Saha 1 Simple Program 2 Comments // Fig. 2.1: fig02_01.c // A first program in C begin with //, indicating that these two lines

More information

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions. Introduction In the programs that we have dealt with so far, all statements inside the main function were executed in sequence as they appeared, one after the other. This type of sequencing is adequate

More information

Technical Questions. Q 1) What are the key features in C programming language?

Technical Questions. Q 1) What are the key features in C programming language? Technical Questions Q 1) What are the key features in C programming language? Portability Platform independent language. Modularity Possibility to break down large programs into small modules. Flexibility

More information

Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100

Subject: 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 information

DECLARAING AND INITIALIZING POINTERS

DECLARAING AND INITIALIZING POINTERS DECLARAING AND INITIALIZING POINTERS Passing arguments Call by Address Introduction to Pointers Within the computer s memory, every stored data item occupies one or more contiguous memory cells (i.e.,

More information

C Functions. Object created and destroyed within its block auto: default for local variables

C Functions. Object created and destroyed within its block auto: default for local variables 1 5 C Functions 5.12 Storage Classes 2 Automatic storage Object created and destroyed within its block auto: default for local variables auto double x, y; Static storage Variables exist for entire program

More information

Structured Programming. Functions and Structured Programming. Functions. Variables

Structured Programming. Functions and Structured Programming. Functions. Variables Structured Programming Functions and Structured Programming Structured programming is a problem-solving strategy and a programming methodology. The construction of a program should embody topdown design

More information

Functions. Systems Programming Concepts

Functions. Systems Programming Concepts Functions Systems Programming Concepts Functions Simple Function Example Function Prototype and Declaration Math Library Functions Function Definition Header Files Random Number Generator Call by Value

More information

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows Unti 4: C Arrays Arrays a kind of data structure that can store a fixed-size 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 information

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ...

Why 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 information

Basics of Programming

Basics of Programming Unit 2 Basics of Programming Problem Analysis When we are going to develop any solution to the problem, we must fully understand the nature of the problem and what we want the program to do. Without the

More information

Fundamentals of Programming Session 12

Fundamentals of Programming Session 12 Fundamentals of Programming Session 12 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2014 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

IV Unit Second Part STRUCTURES

IV Unit Second Part STRUCTURES STRUCTURES IV Unit Second Part Structure is a very useful derived data type supported in c that allows grouping one or more variables of different data types with a single name. The general syntax of structure

More information

Function. specific, well-defined task. whenever it is called or invoked. A function to add two numbers A function to find the largest of n numbers

Function. specific, well-defined task. whenever it is called or invoked. A function to add two numbers A function to find the largest of n numbers Functions 1 Function n A program segment that carries out some specific, well-defined task n Example A function to add two numbers A function to find the largest of n numbers n A function will carry out

More information

Programming 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 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 information

Fundamentals of Programming Session 4

Fundamentals of Programming Session 4 Fundamentals of Programming Session 4 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2011 These slides are created using Deitel s slides, ( 1992-2010 by Pearson Education, Inc).

More information

Function Call Stack and Activation Records

Function Call Stack and Activation Records 71 Function Call Stack and Activation Records To understand how C performs function calls, we first need to consider a data structure (i.e., collection of related data items) known as a stack. Students

More information

SOLUTION FOR FUNCTION. 1) Write a program to display Hello 10 times. Create user-defined function message().

SOLUTION FOR FUNCTION. 1) Write a program to display Hello 10 times. Create user-defined function message(). SOLUTION FOR FUNCTION 1) Write a program to display Hello 10 times. Create user-defined function message(). #include #include void message(int); int i; for (i=1;i

More information

UNIT - V STRUCTURES AND UNIONS

UNIT - V STRUCTURES AND UNIONS UNIT - V STRUCTURES AND UNIONS STRUCTURE DEFINITION A structure definition creates a format that may be used to declare structure variables. Let us use an example to illustrate the process of structure

More information

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

B.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 information

UNIT-IV. Structure is a user-defined data type in C language which allows us to combine data of different types together.

UNIT-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 information

UNIT 3 OPERATORS. [Marks- 12]

UNIT 3 OPERATORS. [Marks- 12] 1 UNIT 3 OPERATORS [Marks- 12] SYLLABUS 2 INTRODUCTION C supports a rich set of operators such as +, -, *,,

More information

Declaration Syntax. Declarations. Declarators. Declaration Specifiers. Declaration Examples. Declaration Examples. Declarators include:

Declaration Syntax. Declarations. Declarators. Declaration Specifiers. Declaration Examples. Declaration Examples. Declarators include: Declarations Based on slides from K. N. King Declaration Syntax General form of a declaration: declaration-specifiers declarators ; Declaration specifiers describe the properties of the variables or functions

More information

M.CS201 Programming language

M.CS201 Programming language Power Engineering School M.CS201 Programming language Lecture 4 Lecturer: Prof. Dr. T.Uranchimeg Agenda How a Function Works Function Prototype Structured Programming Local Variables Return value 2 Function

More information

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are: LESSON 1 FUNDAMENTALS OF C The purpose of this lesson is to explain the fundamental elements of the C programming language. C like other languages has all alphabet and rules for putting together words

More information

Functions. Prof. Indranil Sen Gupta. Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur. Introduction

Functions. Prof. Indranil Sen Gupta. Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur. Introduction Functions Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur Programming and Data Structure 1 Function Introduction A self-contained program segment that

More information

M1-R4: Programing and Problem Solving using C (JAN 2019)

M1-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

A Fast Review of C Essentials Part I

A Fast Review of C Essentials Part I A Fast Review of C Essentials Part I Structural Programming by Z. Cihan TAYSI Outline Program development C Essentials Functions Variables & constants Names Formatting Comments Preprocessor Data types

More information

Model Viva Questions for Programming in C lab

Model Viva Questions for Programming in C lab Model Viva Questions for Programming in C lab Title of the Practical: Assignment to prepare general algorithms and flow chart. Q1: What is a flowchart? A1: A flowchart is a diagram that shows a continuous

More information

Fundamentals of Computer Programming Using C

Fundamentals of Computer Programming Using C CHARUTAR VIDYA MANDAL S SEMCOM Vallabh Vidyanagar Faculty Name: Ami D. Trivedi Class: FYBCA Subject: US01CBCA01 (Fundamentals of Computer Programming Using C) *UNIT 3 (Structured Programming, Library Functions

More information

AMCAT Automata Coding Sample Questions And Answers

AMCAT Automata Coding Sample Questions And Answers 1) Find the syntax error in the below code without modifying the logic. #include int main() float x = 1.1; switch (x) case 1: printf( Choice is 1 ); default: printf( Invalid choice ); return

More information

Fundamentals of Programming Session 14

Fundamentals of Programming Session 14 Fundamentals of Programming Session 14 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4 BIL 104E Introduction to Scientific and Engineering Computing Lecture 4 Introduction Divide and Conquer Construct a program from smaller pieces or components These smaller pieces are called modules Functions

More information

Q 1. Attempt any TEN of the following:

Q 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 information

User Defined Functions

User Defined Functions User Defined Functions CS 141 Lecture 4 Chapter 5 By Ziad Kobti 27/01/2003 (c) 2003 by Ziad Kobti 1 Outline Functions in C: Definition Function Prototype (signature) Function Definition (body/implementation)

More information

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor. 3.Constructors and Destructors Develop cpp program to implement constructor and destructor. Constructors A constructor is a special member function whose task is to initialize the objects of its class.

More information

Computer Programming Unit 3

Computer Programming Unit 3 POINTERS INTRODUCTION Pointers are important in c-language. Some tasks are performed more easily with pointers such as dynamic memory allocation, cannot be performed without using pointers. So it s very

More information

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

Dr 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 information

LESSON 6 FLOW OF CONTROL

LESSON 6 FLOW OF CONTROL LESSON 6 FLOW OF CONTROL This lesson discusses a variety of flow of control constructs. The break and continue statements are used to interrupt ordinary iterative flow of control in loops. In addition,

More information

A Fast Review of C Essentials Part II

A Fast Review of C Essentials Part II A Fast Review of C Essentials Part II Structural Programming by Z. Cihan TAYSI Outline Fixed vs. Automatic duration Scope Global variables The register specifier Storage classes Dynamic memory allocation

More information

Iterative Languages. Scoping

Iterative Languages. Scoping Iterative Languages Scoping Sample Languages C: static-scoping Perl: static and dynamic-scoping (use to be only dynamic scoping) Both gcc (to run C programs), and perl (to run Perl programs) are installed

More information

Fundamental Concepts and Definitions

Fundamental Concepts and Definitions Fundamental Concepts and Definitions Identifier / Symbol / Name These terms are synonymous: they refer to the name given to a programming component. Classes, variables, functions, and methods are the most

More information

Test Paper 3 Programming Language Solution Question 1: Briefly describe the structure of a C program. A C program consists of (i) functions and (ii) statements There should be at least one function called

More information

University of Kelaniya Sri Lanka

University of Kelaniya Sri Lanka University of Kelaniya Sri Lanka Scope, Lifetime and Storage Class of a Variable COSC 12533/ COST 12533 SACHINTHA PITIGALA 2017 - Sachintha Pitigala < 1 What is Scope? Scope of Identifier: The scope of

More information

C: How to Program. Week /Apr/16

C: 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 information

Language Fundamentals

Language Fundamentals Language Fundamentals VBA Concepts Sept. 2013 CEE 3804 Faculty Language Fundamentals 1. Statements 2. Data Types 3. Variables and Constants 4. Functions 5. Subroutines Data Types 1. Numeric Integer Long

More information

Case Control Structure. Rab Nawaz Jadoon DCS. Assistant Professor. Department of Computer Science. COMSATS IIT, Abbottabad Pakistan

Case Control Structure. Rab Nawaz Jadoon DCS. Assistant Professor. Department of Computer Science. COMSATS IIT, Abbottabad Pakistan Case Control Structure DCS COMSATS Institute of Information Technology Rab Nawaz Jadoon Assistant Professor COMSATS IIT, Abbottabad Pakistan Introduction to Computer Programming (ICP) Decision control

More information

Functions and Recursion

Functions 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 information

C Programming Class I

C Programming Class I C Programming Class I Generation of C Language Introduction to C 1. In 1967, Martin Richards developed a language called BCPL (Basic Combined Programming Language) 2. In 1970, Ken Thompson created a language

More information

Functions and Recursion

Functions and Recursion Functions and Recursion 1 Storage Classes Scope Rules Functions with Empty Parameter Lists Inline Functions References and Reference Parameters Default Arguments Unary Scope Resolution Operator Function

More information

Software Design & Programming I

Software Design & Programming I Software Design & Programming I Starting Out with C++ (From Control Structures through Objects) 7th Edition Written by: Tony Gaddis Pearson - Addison Wesley ISBN: 13-978-0-132-57625-3 Chapter 4 Making

More information

Chapter 7 Functions. Now consider a more advanced example:

Chapter 7 Functions. Now consider a more advanced example: Chapter 7 Functions 7.1 Chapter Overview Functions are logical groupings of code, a series of steps, that are given a name. Functions are especially useful when these series of steps will need to be done

More information