Professional Documents
Culture Documents
C Language Introduction
C is a procedural programming language. It was initially developed by Dennis Ritchie in the year
1972. It was mainly developed as a system programming language to write an operating system.
The main features of the C language include low-level memory access, a simple set of keywords,
and a clean style, these features make C language suitable for system programmings like an
operating system or compiler development.
Many later languages have borrowed syntax/features directly or indirectly from the C language.
Like syntax of Java, PHP, JavaScript, and many other languages are mainly based on the C
language. C++ is nearly a superset of C language (Few programs may compile in C, but not in
C++).
Introduction To C Language
Easy to learn
Structured language
It produces efficient programs
It can handle low-level activities
It can be compiled on a variety of computer platforms
Why Use C?
C was initially used for system development work, particularly the programs that make up the
operating system. C was adopted as a system development language because it produces code
that runs nearly as fast as the code written in assembly language. Some examples of the use of C:
Operating Systems
Language Compilers
Assemblers
Text Editors
Print Spoolers
Network Drivers
Modern Programs
Databases
Language Interpreters
Utilities
Applications of ‘c’
C programming language can be used to design different types of application like designing the
system software like OS & compiler.
Designing the application software like database & spreadsheets.
To design the graphics related applications, i.e., PC's and mobile games.
To evaluate the mathematical equations.
Features Of C Programming Language
C language is one of the powerful languages. Below are some of the features of the C language.
Reliability
Portability
Flexibility
Interactivity
Modularity
Efficiency and Effectiveness
C is the most popular programming language which has many advantages:
Modularity:
It is one of the important characteristics of C. we can split the C program into no. of modules
instead of repeating the same logic statements (sequentially). It allows the reusability
of modules.
Middle-level language:
As a middle-level language, C combines both the advantages of low level and high-level
languages. (arrays, pointers, etc.).
General-purpose programming language:
C can be used to implement any applications such as math’s oriented, graphics, business-oriented
applications.
Portability:
We can compile or execute a C program on any operating system (Unix, dos, windows).
Powerful programming language:
C is a very efficient and powerful programming language, it is best used for data structures and
designing system software. C is case sensitive language.
Advantages of C
C Language has a list of advantages due to this it is a very much popular language around the
world and best suitable for the programmer to learn at the first stage of the programming.
Procedure Oriented Language
C Language is procedure-oriented language, here user creates procedures or functions to execute
their task. Procedure-oriented language is very much easy to learn because it follows an
algorithm to execute your statements. To develop a program using procedure-oriented language,
you need to draw/prepare an algorithm and then start converting it into a procedure or functions.
Lots of Libraries
C Language provides lots of functions which consist of system generated functions and user-
defined functions. C Compiler comes with a list of header files which consist of many general
functions which can be used to develop a program, while the programmer can also create a
function as per their requirements that are called a user-generated/defined function.
Speed of Compilation
C compiler produces machine code very fast compared to other language compilers. C compiler
can compile around 1000 lines of code in a second or two. One more benefit of the C Compiler is
that it also optimize the code for faster execution.
Easy to Learn
C Language syntax is very easy to understand. It uses a keyword like if, else, goto, switch, main,
etc. This kind of keyword we all are using in our day to day life to convey meaning or to get
some decisions.
Portable
C Language setup is around 3-5 MB. So you can carry this language in your Floppy Drive or Pen
Drive. It is very easy to install and operate, Again its output is an exe file that can be executed on
any computer without any other framework/software.
Disadvantages of C
C Language also has some disadvantages. C Language does not have major disadvantages, but
some features are missing in the C Language, obviously, that's why C Language is very much
powerful now.
Object-Oriented Programming Features (OOPS)
Object-Oriented Programming Features is missing in C Language, You have to develop your
program using procedure-oriented language only.
Run-Time Type Checking is Not Available
In C Language there is no provision for run-time type checking, for example, I am passing float
value while receiving parameter is of integer type then the value will be changed, it will not give
any error message.
Namespace Feature
C does not provide namespace features, so you can't be able to use the same variable name again
in one scope. If namespace features are available, then you can able to reuse the same variable
name.
Constructor and Destructor is not available
C does not provide object-oriented features, so it doesn't have Constructor and Destructor
features. Constructor and Destructor are used to construct an object and destroy an object. So in
C Language, you have to implement the construction and destruction of the variable manually,
using a function or by other means.
Our course design of tutorials is practical and informative. At TekSlate, we offer resources to
help you learn various IT courses. We avail both written material and demo video tutorials. For
in-depth knowledge and practical experience explore Online C Tutorials.
printf("%d", a);
.
.
1.
2. Return Statement: The last part of any C program is the return statement. The return
statement refers to the returning of the values from a function. This return statement and
return value depend upon the return type of the function. For example, if the return type is
void, then there will be no return statement. In any other case, there will be a return statement
and the return value will be of the type of the specified return type.
Example:
int main()
{
int a;
printf("%d", a);
return 0;
}
1.
2. Writing first program:
Following is first program in C
C
#include <stdio.h>
int main(void)
printf("GeeksQuiz");
return 0;
An expression is a formula in which operands are linked to each other by the use of operators to
compute a value. An operand can be a function reference, a variable, an array element or a
constant.
1. a-b;
In the above expression, minus character (-) is an operator, and a, and b are the two operands.
o Arithmetic expressions
o Relational expressions
o Logical expressions
o Conditional expressions
Each type of expression takes certain types of operands and uses a specific set of operators.
Evaluation of a particular expression produces a specific value.
For example:
1. x = 9/2 + a-b;
The entire above line is a statement, not an expression. The portion after the equal is an
expression.
Arithmetic Expressions
When an expression contains only integral operands, then it is known as pure integer expression
when it contains only real operands, it is known as pure real expression, and when it contains
both integral and real operands, it is known as mixed mode expression.
The expressions are evaluated by performing one operation at a time. The precedence and
associativity of operators decide the order of the evaluation of individual operations.
When individual operations are performed, the following cases can be happened:
o When both the operands are of type integer, then arithmetic will be performed, and the
result of the operation would be an integer value. For example, 3/2 will yield 1 not 1.5 as
the fractional part is ignored.
o When both the operands are of type float, then arithmetic will be performed, and the
result of the operation would be a real value. For example, 2.0/2.0 will yield 1.0, not 1.
o If one operand is of type integer and another operand is of type real, then the mixed
arithmetic will be performed. In this case, the first operand is converted into a real
operand, and then arithmetic is performed to produce the real value. For example, 6/2.0
will yield 3.0 as the first value of 6 is converted into 6.0 and then arithmetic is performed
to produce 3.0.
Relational Expressions
Relational Description
Expression
x%2 = = 0 This condition is used to check whether the x is an even number or not. The relational
value 1 if x is an even number otherwise results in value 0.
a!=b It is used to check whether a is not equal to b. This relational expression results in 1 if
otherwise 0.
a+b = = x+y It is used to check whether the expression "a+b" is equal to the expression "x+y".
1. #include <stdio.h>
2. int main()
3. {
4.
5. int x=4;
6. if(x%2==0)
7. {
8. printf("The number x is even");
9. }
10. else
11. printf("The number x is not even");
12. return 0;
13. }
Output
Logical Expressions
o A logical expression is an expression that computes either a zero or non-zero value.
o It is a complex test condition to take a decision.
( x > 4 ) && ( x < It is a test condition to check whether the x is greater than 4 and x is less than 6. Th
6) is true only when both the conditions are true.
x > 10 || y <11 It is a test condition used to check whether x is greater than 10 or y is less than 11.
condition is true if either of the conditions holds true value.
! ( x > 10 ) && ( y It is a test condition used to check whether x is not greater than 10 and y is equal to
==2) condition is true if both the conditions are true.
1. #include <stdio.h>
2. int main()
3. {
4. int x = 4;
5. int y = 10;
6. if ( (x <10) && (y>5))
7. {
8. printf("Condition is true");
9. }
10. else
11. printf("Condition is false");
12. return 0;
13. }
Output
1. #include <stdio.h>
2. int main()
3. {
4. int x = 4;
5. int y = 9;
6. if ( (x <6) || (y>10))
7. {
8. printf("Condition is true");
9. }
10. else
11. printf("Condition is false");
12. return 0;
13. }
Output
Conditional Expressions
The above expression is a conditional expression which is evaluated on the basis of the value of
the exp1 expression. If the condition of the expression exp1 holds true, then the final conditional
expression is represented by exp2 otherwise represented by exp3.
1. #include<stdio.h>
2. #include<string.h>
3. int main()
4. {
5. int age = 25;
6. char status;
7. status = (age>22) ? 'M': 'U';
8. if(status == 'M')
9. printf("Married");
10. else
11. printf("Unmarried");
12. return 0;
13. }
Output
Conditional Statements in C programming are used to make decisions based on the conditions.
Conditional statements execute sequentially when there is no condition around the statements. If
you put some condition for a block of statements, the execution flow may change based on the
result evaluated by the condition. This process is called decision making in 'C.'
In 'C' programming conditional statements are possible with the help of the following two
constructs:
1. If statement
2. If-else statement
It is also called as branching as a program decides which statement to execute based on the result
of the evaluated condition.
If statement
It is one of the powerful conditional statement. If statement is responsible for modifying the flow
of execution of a program. If statement is always used with a condition. The condition is
evaluated first before executing any statement inside the body of If. The syntax for if statement is
as follows:hat is Linux Linux Beginner Tutorial
if (condition)
instruction;
The condition evaluates to either true or false. True is always a non-zero value, and false is a
value that contains zero. Instructions can be a single instruction or a code block enclosed by
curly braces { }.
#include<stdio.h>
int main()
{
int num1=1;
int num2=2;
if(num1<num2) //test-condition
{
printf("num1 is smaller than num2");
}
return 0;
}
Output:
1. In the above program, we have initialized two variables with num1, num2 with value as
1, 2 respectively.
2. Then, we have used if with a test-expression to check which number is the smallest and
which number is the largest. We have used a relational expression in if construct. Since
the value of num1 is smaller than num2, the condition will evaluate to true.
3. Thus it will print the statement inside the block of If. After that, the control will go
outside of the block and program will be terminated with a successful result.
Relational Operators
C has six relational operators that can be used to formulate a Boolean expression for making a
decision and testing conditions, which returns true or false :
== equal to
!= not equal to
Notice that the equal test (==) is different from the assignment operator (=) because it is one of
the most common problems that a programmer faces by mixing them up.
For example:
int x = 41;
x =x+ 1;
if (x == 42) {
printf("You succeed!");}
Output :
You succeed
Keep in mind that a condition that evaluates to a non-zero value is considered as true.
For example:
int present = 1;
if (present)
printf("There is someone present in the classroom \n");
Output :
The if-else is statement is an extended version of If. The general form of if-else is as follows:
if (test-expression)
{
True block of statements
}
Else
{
False block of statements
}
Statements;
n this type of a construct, if the value of test-expression is true, then the true block of statements
will be executed. If the value of test-expression if false, then the false block of statements will be
executed. In any case, after the execution, the control will be automatically transferred to the
statements appearing outside the block of If.
We will initialize a variable with some value and write a program to determine if the value is less
than ten or greater than ten.
Let's start.
#include<stdio.h>
int main()
{
int num=19;
if(num<10)
{
printf("The value is less than 10");
}
else
{
printf("The value is greater than 10");
}
return 0;
}
Output:
1. We have initialized a variable with value 19. We have to find out whether the number is
bigger or smaller than 10 using a 'C' program. To do this, we have used the if-else
construct.
2. Here we have provided a condition num<10 because we have to compare our value with
10.
3. As you can see the first block is always a true block which means, if the value of test-
expression is true then the first block which is If, will be executed.
4. The second block is an else block. This block contains the statements which will be
executed if the value of the test-expression becomes false. In our program, the value of
num is greater than ten hence the test-condition becomes false and else block is executed.
Thus, our output will be from an else block which is "The value is greater than 10". After
the if-else, the program will terminate with a successful result.
In 'C' programming we can use multiple if-else constructs within each other which are referred to
as nesting of if-else statements.
Conditional Expressions
For example:
#include <stdio.h>
int main() {
int y;
int x = 2;
y = (x >= 6) ? 6 : x;/* This is equivalent to: if (x >= 5) y = 5; else y = x; */
printf("y =%d ",y);
return 0;}
Output :
y =2
Nested If-else Statements
When a series of decision is required, nested if-else is used. Nesting means using one if-else
construct within another one.
#include<stdio.h>
int main()
{
int num=1;
if(num<10)
{
if(num==1)
{
printf("The value is:%d\n",num);
}
else
{
printf("The value is greater than 1");
}
}
else
{
printf("The value is greater than 10");
}
return 0;
}
Output:
The above program checks if a number is less or greater than 10 and prints the result using
nested if-else construct.
1. Firstly, we have declared a variable num with value as 1. Then we have used if-else
construct.
2. In the outer if-else, the condition provided checks if a number is less than 10. If the
condition is true then and only then it will execute the inner loop. In this case, the
condition is true hence the inner block is processed.
3. In the inner block, we again have a condition that checks if our variable contains the
value 1 or not. When a condition is true, then it will process the If block otherwise it will
process an else block. In this case, the condition is true hence the If a block is executed
and the value is printed on the output screen.
4. The above program will print the value of a variable and exit with success.
Try changing the value of variable see how the program behaves.
NOTE: In nested if-else, we have to be careful with the indentation because multiple if-else
constructs are involved in this process, so it becomes difficult to figure out individual constructs.
Proper indentation makes it easy to read the program.
The general syntax of how else-if ladders are constructed in 'C' programming is as follows:
if (test - expression 1) {
statement1;
} else if (test - expression 2) {
Statement2;
} else if (test - expression 3) {
Statement3;
} else if (test - expression n) {
Statement n;
} else {
default;
}
Statement x;
This type of structure is known as the else-if ladder. This chain generally looks like a ladder
hence it is also called as an else-if ladder. The test-expressions are evaluated from top to bottom.
Whenever a true test-expression if found, statement associated with it is executed. When all the n
test-expressions becomes false, then the default else statement is executed.
#include<stdio.h>
int main()
{
int marks=83;
if(marks>75){
printf("First class");
}
else if(marks>65){
printf("Second class");
}
else if(marks>55){
printf("Third class");
}
else{
printf("Fourth class");
}
return 0;
}
Output:
First class
The above program prints the grade as per the marks scored in a test. We have used the else-if
ladder construct in the above program.
1. We have initialized a variable with marks. In the else-if ladder structure, we have
provided various conditions.
2. The value from the variable marks will be compared with the first condition since it is
true the statement associated with it will be printed on the output screen.
3. If the first test condition turns out false, then it is compared with the second condition.
4. This process will go on until the all expression is evaluated otherwise control will go out
of the else-if ladder, and default statement will be printed.
Try modifying the value and notice the change in the output.
C - Loops
You may encounter situations, when a block of code needs to be executed several
number of times. In general, statements are executed sequentially: The first statement in
a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more
complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times.
Given below is the general form of a loop statement in most of the programming
languages −
1 while loop
Repeats a statement or group of statements while a given condition is true. It tests the
condition before executing the loop body.
2 for loop
Executes a sequence of statements multiple times and abbreviates the code that manages
the loop variable.
3 do...while loop
It is more like a while statement, except that it tests the condition at the end of the loop
body.
4 nested loops
You can use one or more loops inside any other while, for, or do..while loop.
1 break statement
2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition
prior to reiterating.
3 goto statement
Transfers control to the labeled statement.
while loop in C
Syntax
Flow Diagram
Here, the key point to note is that a while loop might not execute at all. When the condition is
tested and the result is false, the loop body will be skipped and the first statement after the while
loop will be executed.
Example
Live Demo
#include <stdio.h>
int main () {
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
for loop in C
A for loop is a repetition control structure that allows you to efficiently write a loop that needs
to execute a specific number of times.
Syntax
Example
Live Demo
#include <stdio.h>
int main () {
int a;
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
do...while loop in C
Unlike for and while loops, which test the loop condition at the top of the loop,
the do...while loop in C programming checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at
least one time.
Syntax
int main () {
/* local variable definition */
int a = 10;
/* do loop execution */
do {
printf("value of a: %d\n", a);
a = a + 1;
}while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
nested loops in C
C programming allows to use one loop inside another loop. The following section shows a few
examples to illustrate the concept.
Syntax
while(condition) {
statement(s);
}
statement(s);
}
The syntax for a nested do...while loop statement in C programming language is as follows −
do {
statement(s);
do {
statement(s);
}while( condition );
}while( condition );
A final note on loop nesting is that you can put any type of loop inside any other type of loop.
For example, a 'for' loop can be inside a 'while' loop or vice versa.
Example
The following program uses a nested for loop to find the prime numbers from 2 to 100 −
Live Demo
#include <stdio.h>
int main () {
return 0;
}
When the above code is compiled and executed, it produces the following result −
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
Array in C
C Array is a collection of variables belongings to the same data type. You can store group of data
of same data type in an array.
What is an Array?
An array is a collection of one or more values of the same type. Each value is called an element
of the array. The elements of the array share the same variable name but each element has its
own unique index number (also known as a subscript). An array can be of any type, For
example: int, float, char etc. If an array is of type int then it's elements must be of type int only.
Arrays can be single or multidimensional. The number of subscript or index determines the
dimensions of the array. An array of one dimension is known as a one-dimensional array or 1-D
array, while an array of two dimensions is known as a two-dimensional array or 2-D array.
One-dimensional array
Conceptually you can think of a one-dimensional array as a row, where elements are stored one
after another.
Syntax: datatype array_name[size];
size: Number of elements an array can hold. here are some example of array declarations:
1 int num[100];
2 float temp[20];
3 char ch[50];
num is an array of type int, which can only store 100 elements of type int.
temp is an array of type float, which can only store 20 elements of type float.
ch is an array of type char, which can only store 50 elements of type char.
1 #define SIZE 10
2
3 int main()
4{
5 int size = 10;
6
7 int my_arr1[SIZE]; // ok
8 int my_arr2[size]; // not allowed until C99
9 // ...
10 }
The two-dimensional array can be defined as an array of arrays. The 2D array is organized as
matrices which can be represented as the collection of rows and columns. However, 2D arrays
are created to implement a relational database lookalike data structure. It provides ease of
holding the bulk of data at once which can be passed to any number of functions wherever
required.
1. data_type array_name[rows][columns];
1. int twodimen[4][3];
Initialization of 2D Array in C
In the 1D array, we don't need to specify the size of the array if the declaration and initialization
are being done simultaneously. However, this will not work with 2D arrays. We will have to
define at least the second dimension of the array. The two-dimensional array can be declared and
defined in the following way.
1. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
Output
arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6
Multi-dimensional Arrays in C
C programming language allows multidimensional arrays. Here is the general form of a
multidimensional array declaration −
type name[size1][size2]...[sizeN];
For example, the following declaration creates a three dimensional integer array −
int threedim[5][10][4];
Two-dimensional Arrays
Multidimensional arrays may be initialized by specifying bracketed values for each row.
Following is an array with 3 rows and each row has 4 columns.
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
The nested braces, which indicate the intended row, are optional. The following initialization is
equivalent to the previous example −
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
#include <stdio.h>
int main () {
return 0;
}
When the above code is compiled and executed, it produces the following result −
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
As explained above, you can have arrays with any number of dimensions, although it is likely
that most of the arrays you create will be of one or two dimensions.
String and Character Array
String is a sequence of characters that are treated as a single data item and terminated by a null
character '\0'. Remember that the C language does not support strings as a data type. A string is
actually a one-dimensional array of characters in C language. These are often used to create
meaningful and readable programs.
If you don't know what an array in C means, you can check the C Array tutorial to know about
Array in the C language. Before proceeding further, check the following articles:
C Function Calls
C Variables
C Datatypes
C Syntax Rules
// valid
// Illegal
char str[4];
str = "hello";
edit set conversion code %[..] that can be used to read a line containing a variety of
characters, including white spaces.
The gets() function can also be used to read character string with white spaces
char str[20];
printf("Enter a string");
scanf("%[^\n]", &str);
printf("%s", str);
char text[20];
gets(text);
printf("%s", text);
C language supports a large number of string handling functions that can be used to carry out
many of the string manipulations. These functions are packaged in the string.h library. Hence,
you must include string.h header file in your programs to use these functions.
The following are the most commonly used string handling functions.
Method Description
strcat() function in C:
Syntax:
strcat("hello", "world");
strlen() and strcmp() function:
strlen() will return the length of the string passed to it and strcmp() will return the ASCII
difference between first unmatching character of two strings.
int j = strlen("studytonight");
printf("%d %d",j,i);
12 -1
strcpy() function:
Example of strcpy() function:
#include<stdio.h>
#include<string.h>
int main()
strcpy(s1, "StudyTonight");
strcpy(s2, s1);
printf("%s\n", s2);
return(0);
StudyTonight
strrev() function:
#include <stdio.h>
int main()
char s1[50];
printf("Enter your string: ");
gets(s1);
return(0);
String and Character Array. String is a sequence of characters that are treated as a single data
item and terminated by a null character '\0' . ... A string is actually a one-
dimensional array of characters in C language.
C Functions
In c, we can divide a large program into the basic building blocks known as function. The
function contains the set of programming statements enclosed by {}. A function can be called
multiple times to provide reusability and modularity to the C program. In other words, we can
say that the collection of functions creates a program. The function is also known
as procedureor subroutinein other programming languages.
Advantage of functions in C
o By using functions, we can avoid rewriting same logic/code again and again in a
program.
o We can call C functions any number of times in a program and from any place in a
program.
o We can track a large C program easily when it is divided into multiple functions.
o Reusability is the main achievement of C functions.
o However, Function calling is always a overhead in a C program.
Function Aspects
o Function definition It contains the actual statements which are to be executed. It is the
most important aspect to which the control comes when the function is called. Here, we
must notice that only one value can be returned from the function.
1. return_type function_name(data_type parameter...){
2. //code to be executed
3. }
Types of Functions
1. Library Functions: are the functions which are declared in the C header files such as
scanf(), printf(), gets(), puts(), ceil(), floor() etc.
2. User-defined functions: are the functions which are created by the C programmer, so
that he/she can use it many times. It reduces the complexity of a big program and
optimizes the code.
Return Value
A C function may or may not return a value from the function. If you don't have to return any
value from the function, use void for the return type.
Let's see a simple example of C function that doesn't return any value from the function.
1. void hello(){
2. printf("hello c");
3. }
If you want to return any value from the function, you need to use any data type such as int, long,
char, etc. The return type depends on the value to be returned from the function.
Let's see a simple example of C function that returns int value from the function.
1. int get(){
2. return 10;
3. }
In the above example, we have to return 10 as a value, so the return type is int. If you want to
return floating-point value (e.g., 10.2, 3.1, 54.5, etc), you need to use float as the return type of
the method.
1. float get(){
2. return 10.2;
3. }
Now, you need to call the function, to get the value of the function.
A function may or may not accept any argument. It may or may not return any value. Based on
these facts, There are four different aspects of function calls.
Example 1
1. #include<stdio.h>
2. void printName();
3. void main ()
4. {
5. printf("Hello ");
6. printName();
7. }
8. void printName()
9. {
10. printf("Javatpoint");
11. }
Output
Hello Javatpoint
Example 2
1. #include<stdio.h>
2. void sum();
3. void main()
4. {
5. printf("\nGoing to calculate the sum of two numbers:");
6. sum();
7. }
8. void sum()
9. {
10. int a,b;
11. printf("\nEnter two numbers");
12. scanf("%d %d",&a,&b);
13. printf("The sum is %d",a+b);
14. }
Output
The sum is 34
Example 1
1. #include<stdio.h>
2. int sum();
3. void main()
4. {
5. int result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. result = sum();
8. printf("%d",result);
9. }
10. int sum()
11. {
12. int a,b;
13. printf("\nEnter two numbers");
14. scanf("%d %d",&a,&b);
15. return a+b;
16. }
Output
The sum is 34
1. #include<stdio.h>
2. int sum();
3. void main()
4. {
5. printf("Going to calculate the area of the square\n");
6. float area = square();
7. printf("The area of the square: %f\n",area);
8. }
9. int square()
10. {
11. float side;
12. printf("Enter the length of the side in meters: ");
13. scanf("%f",&side);
14. return side * side;
15. }
Output
Example 1
1. #include<stdio.h>
2. void sum(int, int);
3. void main()
4. {
5. int a,b,result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. printf("\nEnter two numbers:");
8. scanf("%d %d",&a,&b);
9. sum(a,b);
10. }
11. void sum(int a, int b)
12. {
13. printf("\nThe sum is %d",a+b);
14. }
Output
The sum is 34
1. #include<stdio.h>
2. void average(int, int, int, int, int);
3. void main()
4. {
5. int a,b,c,d,e;
6. printf("\nGoing to calculate the average of five numbers:");
7. printf("\nEnter five numbers:");
8. scanf("%d %d %d %d %d",&a,&b,&c,&d,&e);
9. average(a,b,c,d,e);
10. }
11. void average(int a, int b, int c, int d, int e)
12. {
13. float avg;
14. avg = (a+b+c+d+e)/5;
15. printf("The average of given five numbers : %f",avg);
16. }
Output
Example 1
1. #include<stdio.h>
2. int sum(int, int);
3. void main()
4. {
5. int a,b,result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. printf("\nEnter two numbers:");
8. scanf("%d %d",&a,&b);
9. result = sum(a,b);
10. printf("\nThe sum is : %d",result);
11. }
12. int sum(int a, int b)
13. {
14. return a+b;
15. }
Output
1. #include<stdio.h>
2. int even_odd(int);
3. void main()
4. {
5. int n,flag=0;
6. printf("\nGoing to check whether a number is even or odd");
7. printf("\nEnter the number: ");
8. scanf("%d",&n);
9. flag = even_odd(n);
10. if(flag == 0)
11. {
12. printf("\nThe number is odd");
13. }
14. else
15. {
16. printf("\nThe number is even");
17. }
18. }
19. int even_odd(int n)
20. {
21. if(n%2 == 0)
22. {
23. return 1;
24. }
25. else
26. {
27. return 0;
28. }
29. }
Output
C Library Functions
Library functions are the inbuilt function in C that are grouped and placed at a common place
called the library. Such functions are used to perform some specific operations. For example,
printf is a library function used to print on the console. The library functions are created by the
designers of compilers. All C standard library functions are defined inside the different header
files saved with the extension .h. We need to include these header files in our program to make
use of the library functions defined in such header files. For example, To use the library
functions such as printf/scanf we need to include stdio.h in our program which is a header file
that contains all the library functions regarding standard input/output.
The list of mostly used header files is given in the following table.
SN Header Description
file
1 stdio.h This is a standard input/output header file. It contains all the library functions regardin
input/output.
4 stdlib.h This header file contains all the general library functions like malloc(), calloc(), exit(),
5 math.h This header file contains all the math operations related functions like sqrt(), pow(), et
9 signal.h All the signal handling functions are defined in this header file.
There are two methods to pass the data into the function in C language, i.e., call by
value and call by reference.
Let's understand call by value and call by reference in c language one by one.
Call by value in C
o In call by value method, the value of the actual parameters is copied into the formal
parameters. In other words, we can say that the value of the variable is used in the
function call in the call by value method.
o In call by value method, we can not modify the value of the actual parameter by the
formal parameter.
o In call by value, different memory is allocated for actual and formal parameters since the
value of the actual parameter is copied into the formal parameter.
o The actual parameter is the argument which is used in the function call whereas formal
parameter is the argument which is used in the function definition.
Let's try to understand the concept of call by value in c language by the example given below:
1. #include<stdio.h>
2. void change(int num) {
3. printf("Before adding value inside function num=%d \n",num);
4. num=num+100;
5. printf("After adding value inside function num=%d \n", num);
6. }
7. int main() {
8. int x=100;
9. printf("Before function call x=%d \n", x);
10. change(x);//passing value in function
11. printf("After function call x=%d \n", x);
12. return 0;
13. }
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100
Call by reference in C
o In call by reference, the address of the variable is passed into the function call as the
actual parameter.
o The value of the actual parameters can be modified by changing the formal parameters
since the address of the actual parameters is passed.
o In call by reference, the memory allocation is similar for both formal parameters and
actual parameters. All the operations in the function are performed on the value stored at
the address of the actual parameters, and the modified value gets stored at the same
address.
1. #include<stdio.h>
2. void change(int *num) {
3. printf("Before adding value inside function num=%d \n",*num);
4. (*num) += 100;
5. printf("After adding value inside function num=%d \n", *num);
6. }
7. int main() {
8. int x=100;
9. printf("Before function call x=%d \n", x);
10. change(&x);//passing reference in function
11. printf("After function call x=%d \n", x);
12. return 0;
13. }
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200
Call by reference Example: Swapping the values of the two variables
1. #include <stdio.h>
2. void swap(int *, int *); //prototype of the function
3. int main()
4. {
5. int a = 10;
6. int b = 20;
7. printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a a
nd b in main
8. swap(&a,&b);
9. printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of actual paramet
ers do change in call by reference, a = 10, b = 20
10. }
11. void swap (int *a, int *b)
12. {
13. int temp;
14. temp = *a;
15. *a=*b;
16. *b=temp;
17. printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal parameters, a =
20, b = 10
18. }
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10
1 A copy of the value is passed into the function An address of value is passed into the function
2 Changes made inside the function is limited to the Changes made inside the function validate outside of
function only. The values of the actual parameters do the function also. The values of the actual parameters
not change by changing the formal parameters. do change by changing the formal parameters.
3 Actual and formal arguments are created at the Actual and formal arguments are created at the same
different memory location memory location