Thursday, July 9, 2020

Functions In C Programming

Functions In C Programming Everything You Need To Know About Functions in C? Back Home Categories Online Courses Mock Interviews Webinars NEW Community Write for Us Categories Artificial Intelligence AI vs Machine Learning vs Deep LearningMachine Learning AlgorithmsArtificial Intelligence TutorialWhat is Deep LearningDeep Learning TutorialInstall TensorFlowDeep Learning with PythonBackpropagationTensorFlow TutorialConvolutional Neural Network TutorialVIEW ALL BI and Visualization What is TableauTableau TutorialTableau Interview QuestionsWhat is InformaticaInformatica Interview QuestionsPower BI TutorialPower BI Interview QuestionsOLTP vs OLAPQlikView TutorialAdvanced Excel Formulas TutorialVIEW ALL Big Data What is HadoopHadoop ArchitectureHadoop TutorialHadoop Interview QuestionsHadoop EcosystemData Science vs Big Data vs Data AnalyticsWhat is Big DataMapReduce TutorialPig TutorialSpark TutorialSpark Interview QuestionsBig Data TutorialHive TutorialVIEW ALL Blockchain Blockchain TutorialWhat is BlockchainHyperledger FabricWhat Is EthereumEthereum TutorialB lockchain ApplicationsSolidity TutorialBlockchain ProgrammingHow Blockchain WorksVIEW ALL Cloud Computing What is AWSAWS TutorialAWS CertificationAzure Interview QuestionsAzure TutorialWhat Is Cloud ComputingWhat Is SalesforceIoT TutorialSalesforce TutorialSalesforce Interview QuestionsVIEW ALL Cyber Security Cloud SecurityWhat is CryptographyNmap TutorialSQL Injection AttacksHow To Install Kali LinuxHow to become an Ethical Hacker?Footprinting in Ethical HackingNetwork Scanning for Ethical HackingARP SpoofingApplication SecurityVIEW ALL Data Science Python Pandas TutorialWhat is Machine LearningMachine Learning TutorialMachine Learning ProjectsMachine Learning Interview QuestionsWhat Is Data ScienceSAS TutorialR TutorialData Science ProjectsHow to become a data scientistData Science Interview QuestionsData Scientist SalaryVIEW ALL Data Warehousing and ETL What is Data WarehouseDimension Table in Data WarehousingData Warehousing Interview QuestionsData warehouse architectureTalend T utorialTalend ETL ToolTalend Interview QuestionsFact Table and its TypesInformatica TransformationsInformatica TutorialVIEW ALL Databases What is MySQLMySQL Data TypesSQL JoinsSQL Data TypesWhat is MongoDBMongoDB Interview QuestionsMySQL TutorialSQL Interview QuestionsSQL CommandsMySQL Interview QuestionsVIEW ALL DevOps What is DevOpsDevOps vs AgileDevOps ToolsDevOps TutorialHow To Become A DevOps EngineerDevOps Interview QuestionsWhat Is DockerDocker TutorialDocker Interview QuestionsWhat Is ChefWhat Is KubernetesKubernetes TutorialVIEW ALL Front End Web Development What is JavaScript â€" All You Need To Know About JavaScriptJavaScript TutorialJavaScript Interview QuestionsJavaScript FrameworksAngular TutorialAngular Interview QuestionsWhat is REST API?React TutorialReact vs AngularjQuery TutorialNode TutorialReact Interview QuestionsVIEW ALL Mobile Development Android TutorialAndroid Interview QuestionsAndroid ArchitectureAndroid SQLite DatabaseProgramming aria-current=page>Uncat egorizedEverything You Need To Know Ab... AWS Global Infrastructure C Programming Tutorial: The Basics you Need to Master C Everything You Need To Know About Basic Structure of a C Program How to Compile C Program in Command Prompt? How to Implement Linear Search in C? How to write C Program to find the Roots of a Quadratic Equation? Everything You Need To Know About Sorting Algorithms In C Fibonacci Series In C : A Quick Start To C Programming How To Reverse Number In C? How To Implement Armstrong Number in C? How To Carry Out Swapping of Two Numbers in C? C Program To Find LCM Of Two Numbers Leap Year Program in C Switch Case In C: Everything You Need To Know Everything You Need To Know About Pointers In C How To Implement Selection Sort in C? How To Write A C Program For Deletion And Insertion? How To Implement Heap Sort In C? How To Implement Bubble Sort In C? Binary Search In C: Everything You Need To Know Binary Search Introduction to C P rogramming-Algorithms What is Objective-C: Why Should You Learn It? How To Implement Static Variable In C? How To Implement Queue in C? How To Implement Circular Queue in C? What is Embedded C programming and how is it different? Everything You Need To Know About Functions in C? Published on Sep 10,2019 514 Views edureka Bookmark This article will introduce you a simple yet a very fundamental and important programming concept that is Functions in C and follow it up with a demonstration. Following pointers will be covered in this article,What are Functions in C?Advantages of Functions in CTypes of Function in CFunction Declaration DefinitionCalling a FunctionTypes of User-Defined Function in CNo arguments passed and no return ValueNo arguments passed but a return valueArgument passed but no return valueArgument passed and a return valueC Library FunctionsFunctions are building blocks of any programming language. In simple words, function in a set of statements, which takes inputs, perform a specific task then returns the output. The ideology behind creating function is to bind a set of related statement together which performs a specific task. So that, you dont have to write the same code multiple times for different set of inputs. You just have to call the function for different inputs, it will perform the specified task for the given input return the output. You can call the function as many times as you want. In this blog, we will learn each every nuance about functions in C programming language.Let us start with the most fundamental question.What are Functions in C?Functions are same in C as of any other programming language. It is a set of codes bind together to perform a specific task. The set of code to be executed is specified in curly braces, i.e. { }.Before learning how to write a function in C, lets first understand what the advantages are.Advantages of Functions in CThe advantages of functions are common across all the programming languages. The main idea behind function is to reduce the redundancy in the code. Suppose you have a functionality that needs to be performed multiple times in a program, so instead of writing it multiple times, you can create a function for that task and call it as many times as you want. Another hidden benefit is, if the logic of your functionality changes afterwards, then you dont have to go ahead and change it at multiple places. You just have to change the code at one place (i.e. in the function) it would be reflected throughout the program. Modularity in again an added benefit. Writing a big piece of code including each everything, reduces the readability of the code makes it difficult to manage. You can divide the code in sections for individual functionalities using functions, which is simpler to understand and easier to manage.Function also provides abstraction, where we can call a function and get the output without knowing the internal implementation.Moving on with ty pes of Function CTypes of Function in CThere are two types of functions: Library functions User-defined functionsLibrary functions are those functions which are already defined in C library such as strcat(), printf(), scanf() etc. You just need to include appropriate header files to use these functions. User-defined functions are those functions which are defined by the user. These functions are made for code reusability and for saving time and space.Now that we know the benefits of creating a function lets understand how to declare a function in C.Function Declaration DefinitionFunction Declaration:Syntax of function declaration:return_type function_name (data_type arg1, data_type arg2) int add(int x, int y); //function declarationIn Function Declaration, we specify the name of the function, the number of input parameter, their datatypes the return type of the function. Function declaration tells compiler about the list of arguments the function is expecting with their data types the return type of the function.In function declaration, specifying the names of the parameter is optional, but specifying their data types is mandatory.int add(int, int); //function declarationThe above specified function will take two integer parameters.Function Definition int add(int, int); //function declaration return_type function_name(parameters) { Function body }As shown in the above image a function definition consists of two parts i.e. function header function bodyFunction Header: function header is same as function declaration without the semicolon. Function header contains function name, parameter return type.Return Type: Return type is the data type of the value which will be returned by the function. The function may or may not return a value. If it does then the data type of the retuning value should be specified, otherwise the return type needs to be void.Function Name: This is the name of the function using which we can call the function when where needed.Parameters: The parameters are the input values which will be passed to the function. It tells about the data types of the arguments, their order and the number of arguments that will be passed to the function. The parameters are optional. You can also have functions without parameters.Function Body: The function body is the set of statement which performs a specific task. It d efines what the function does.Example: int add(int x, int y) { int sum = x+y; return(sum); } It is recommended to declare a function before we define use it. In C, we can declare define the function at the same place.Example: #include stdio.h int add(int, int); //function declaration // function definition int add(int x, int y) //function header { // function body int sum = x+y; return(sum); } // Main Function int main() { int sum = add(23, 31); printf(%d, sum); return 0; } As we can see in the above example that we are calling the function using int sum = add(23, 31); statement. The returned value from the function is stored in sum variable.Before we move ahead, there is one more important concept to understand about the parament. There are two types of parameter:Actual Parameter: Those parameters which are passed to functions while calling them is are known as actual parameter. For example, 23 31 in the above example are the actual parameters.Formal Parameter: Those parameters which are received by the functions are known as formal parameters. For example, x y in the above example are the formal parameters.Lets quickly move ahead and understand the different ways of calling a function in C.Calling a FunctionThere are two ways in which we can call a function:Call by valueCall by referenceCall by valueIn call by value method, the value of the actual parameter is passed as an argument to the function. The value of the actual parameter cannot be changed by the formal parameters.In call be value method, different memory address is allocated to formal actual parameters. Just the value of actual parameter is copied to formal parameter.Example: #include stdio.h void Call_By_Value(int num1) { num1=42; printf(nInside Function, Number is %d, num1); } int main() { int num; num=24; printf(nBefore Function, Number is %d, num); Call_By_Value(num); printf(nAfter Function, Number is %dn, num); return 0; } OutputIn the above example, before call by value function, the value of num is 24. Then, once we call the function and pass the value, change it inside the function, it becomes 42. When we come back again print the value of num in main function, it becomes 24.Call by referenceIn call by reference, the memory address of the actual parameter is passed to the function as argument. Here, the value of the actual parameter can be changed by the formal parameter.Same memory address is used for both the actual formal parameter. So, if the value of formal parameter is modified, it is reflected by the actual parameter as well.In C we use pointers to implement call by reference. As you can see in the below example, the function Call_By_Reference is expecting a pointer to an integer.Now, this num1 variable will store the memory address of the actual parameter. So, to print the value which is stored in the memory address pointed by num1 we need to use dereference operator i.e. *. So, the value of *num1 is 42.The address operator is used to get the address of a variable of any data type. So in the function call statement Call_By_Reference(num);, the address of num is passed so that num can be modified using its address.Example #include stdio.h // function definition void Call_By_Reference(int *num1) { *num1=42; printf(nInside Function, Number is %d, *num1); } // Main Function int main() { int num; num=24; printf(nBefore Function, Number is %d, num); Call_By_Reference(num); printf(nAfter Function, Number is %dn, num); return 0; } OutputIn this example, the value of num is 24 initially, inside the main function. Once it is passed to the Call_By_Reference function and the value is modified by the formal parameter, it got changed for the actual parameter as well. This is why when we are printing the value of num after the function it is printing 42.Moving on with types of user-defined function in CTypes of User-Defined Function in CThere are various kinds of user-defined functions based of the return type arguments passed.Moving on with No arguments passed and no return value1.No arguments passed and no return ValueSyntax:function declaration: void function(); function call: function(); function definition: void function() { statements; } Example #include stdio.h void add(); void add() { int x = 20; int y = 30; int sum = x+y; printf(sum %d, sum); } int main() { add(); return 0; } Moving on with No arguments passed but a return value2 No arguments passed but a return valueSyntax:function declaration: int function ( ); function call: function ( ); function definition: int function( ) { statements; return a; } Example: #include stdio.h int add(); int add() { int x = 20; int y = 30; int sum = x+y; return(sum); } int main() { int sum; sum = add(); printf(sum %d, sum); return 0; } Moving on with Arguments passed but no return value3 Argument passed but no return valueSyntax:function declaration: void function ( int ); function call: function( a ); function definition: void function( int a ) { statements; } Example: #include stdio.h void add(int, int); void add(int x, int y) { int sum = x+y; return(sum); } int main() { add(23, 31); return 0; } Moving on with Argument passed and a return value4 Argument passed and a return valueSyntax:function declaration: int function ( int ); function call: function ( a ); function definition: int function( int a ) { statements; return a; } Example #include stdio.h int add(int, int); int add(int x, int y) { int sum = x+y; return(sum); } int main() { int sum = add(23, 31); printf(%d, sum); return 0; } Now let us quickly look at the C library functions which are important in order to write a program.C Library FunctionsLibrary functions are functions in C which are pre-defined and are present by default. You just have to include the specific header file in the program you can use the functions defined in that header file. Each header file provides specific kind of functionality. The extension of the header file is .h.For example, to use the printf/scanf functions we need to include stdio.h in our program, which provide functionality regarding standard input/output.Following is the list of header files.1stdio.hStandard input/output header file2conio.hConsole input/output header file3string.hString related library functions such as gets(), puts(),etc.4stdlib.hGeneral library functions such as malloc(), calloc(), exit(), etc.5math.hMath operations related functions such as sqrt(), pow(), etc.6time.hTime-related functions7ctype.hCharacter handling functions8stdarg.hVariable argument fu nctions9signal.hSignal handling functions10setjmp.hJump functions11locale.hLocale functions12errno.hError handling functions13assert.hDiagnostics functionsNow after going through the above C functions you would have understood each every nuance of function how to implement it in C language. I hope this blog is informative and added value to you.Thus we have come to an end of this article on Functions In C. If you wish to learn more, check out the Java Training by Edureka, a trusted online learning company. Edurekas Java J2EE and SOA training and certification course is designed to train you for both core and advanced Java concepts along with various Java frameworks like Hibernate Spring.Got a question for us? Please mention it in the comments section of this blog and we will get back to you as soon as possible.Recommended blogs for you How to Compile C Program in Command Prompt? Read Article Apache Cassandra Career Opportunities: How To Bag Top Cassandra NoSQL jobs Read Article H ow To Best Implement Radix Sort Program In C? Read Article Infographic A Beginners Guide to the Indian IT Ecosystem Read Article How To Reverse Number In C? Read Article How to convert Char to Int in Java? Read Article Bugs in Software Testing â€" What, Where and How Read Article How To Best Utilize Power Function In C? Read Article Everything You Need To Know About Power BI Charts Read Article Top 10 Programming Languages to Learn In 2020 Read Article Why Your First Salary is Crucial for Your Career? Read Article Appium Studio Tutorial: All You Need To Know Read Article How To Implement Bubble Sort In C? Read Article #IndiaITRepublic â€" Top 10 Facts about IT Startups Read Article How To Implement Heap Sort In C? Read Article Announcing the Ridiculously Committed Mentors Awards Read Article Vol. XIV â€" Edureka Career Watch â€" 25th May 2019 Read Article Vol. VIII â€" Edureka Career Watch â€" 2nd Mar. 2019 Read Article How to Implement Insertion Sort in C with Example Read Article Software Testing Tutorial Know How to Perform Testing Read Article Comments 0 Comments Trending Courses Python Certification Training for Data Scienc ...66k Enrolled LearnersWeekend/WeekdayLive Class Reviews 5 (26200)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.