6. Fundamentals of C Programming
6. Fundamentals of C Programming
A computer is a computational device which is used to process the data under the control of a
computer program. Program is a sequence of instruction along with data. While executing the
program, raw data is processed into a desired output format. These computer programs are
written in a programming language which are high level languages. High level languages are
nearly human languages which are more complex then the computer understandable language
which are called machine language, or low level language.
Basic example of a computer program written in C programming language:
#include<stdio.h>
int main(void)
{
printf("C is a programming language");
return 0;
}
Between high-level language and machine language there are assembly language also called
symbolic machine code. Assembly language are particularly computer architecture specific.
Utility program (Assembler) is used to convert assembly code into executable machine code.
High Level Programming Language are portable but require Interpretation or compiling
toconvert it into a machine language which is computer understood.
Algorithm
An algorithm is a set of steps of operations to solve a problem performing calculation, data
processing, and automated reasoning tasks. An algorithm is an efficient method that can be
expressed within finite amount of time and space.
An algorithm is the best way to represent the solution of a particular problem in a very simple
and efficient way. If we have an algorithm for a specific problem, then we can implement it in
any programming language, meaning that the algorithm is independent from any
programming languages.
Algorithm Design
The important aspects of algorithm design include creating an efficient algorithm to solve a
problem in an efficient way using minimum time and space.
To solve a problem, different approaches can be followed. Some of them can be efficient with
respect to time consumption, whereas other approaches may be memory efficient. However, one
has to keep in mind that both time consumption and memory usage cannot be optimized
simultaneously. If we require an algorithm to run in lesser time, we have to invest in more
memory and if we require an algorithm to run with lesser memory, we need to have more time.
Problem Development Steps
The following steps are involved in solving computational problems.
Problem definition
Development of a model
Specification of an Algorithm
Designing an Algorithm
Checking the correctness of an Algorithm
Analysis of an Algorithm
Implementation of an Algorithm
Program testing
Documentation
Characteristics of Algorithms
The main characteristics of algorithms are as follows −
Algorithms halt in a finite amount of time. Algorithms should not run for infinity, i.e., an
algorithm must end at some point
Pseudocode
Pseudocode gives a high-level description of an algorithm without the ambiguity associated
with plain text but also without the need to know the syntax of a particular programming
language.
The running time can be estimated in a more general manner by using Pseudocode to represent
the algorithm as a set of fundamental operations which can then be counted.
Algorithm: Insertion-Sort
Input: A list L of integers of length n
Output: A sorted list L1 containing those integers present in L
Step 1: Keep a sorted list L1 which starts off empty
Step 2: Perform Step 3 for each element in the original list L
Step 3: Insert it into the correct position in the sorted list L1.
Step 4: Return the sorted list
Step 5: Stop
Here is a pseudocode which describes how the high level abstract process mentioned above in
the algorithm Insertion-Sort could be described in a more realistic way.
Flowchart Symbols
Here is a chart for some of the common symbols used in drawing flowcharts.
Flowchart can have only one start and one stop symbol
In 1978, Brian Kernighan and Dennis Ritchie produced the first publicly available description
of C, now known as the K&R standard.
The UNIX operating system, the C compiler, and essentially all UNIX application programs
have been written in C. C has now become a widely used professional language for various
reasons −
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
Facts about C
C was invented to write an operating system called UNIX.
The language was formalized in 1988 by the American National Standard Institute
(ANSI).
Today C is the most widely used and popular System Programming Language.
Today's most popular Linux OS and RDBMS MySQL have been written in C.
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
might be −
Operating Systems
Language Compilers
Assemblers
Text Editors
Print Spoolers
Network Drivers
Modern Programs
Databases
Language Interpreters
Utilities
C Programs
A C program can vary from 3 lines to millions of lines and it should be written into one or more
text files with extension ".c"; for example, hello.c. You can use "vi", "vim" or any other text
editor to write your C program into a file.
This tutorial assumes that you know how to edit a text file and how to write source code inside a
program file.
Keywords
The following list shows the reserved words in C. These reserved words may not be used as
constants or variables or any other identifier names.
double
C - Data Types
Advertisements
Previous Page
Next Page
Data types in c refer to an extensive system used for declaring variables or functions of different
types. The type of a variable determines how much space it occupies in storage and how the bit
pattern stored is interpreted.
1 Basic Types
They are arithmetic types and are further classified into: (a) integer types and (b)
floating-point types.
2 Enumerated types
They are again arithmetic types and they are used to define variables that can
only assign certain discrete integer values throughout the program.
4 Derived types
They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union
types and (e) Function types.
The array types and structure types are referred collectively as the aggregate types. The type of
a function specifies the type of the function's return value. We will see the basic types in the
following section, where as other types will be covered in the upcoming chapters.
Integer Types
The following table provides the details of standard integer types with their storage sizes and
value ranges −
Type Storage size Value range
To get the exact size of a type or a variable on a particular platform, you can use
the sizeof operator. The expressions sizeof(type) yields the storage size of the object or type in
bytes. Given below is an example to get the size of int type on any machine −
#include <stdio.h>
#include <limits.h>
int main() {
When you compile and execute the above program, it produces the following result on Linux −
Floating-Point Types
The following table provide the details of standard floating-point types with storage sizes and
value ranges and their precision −
The header file float.h defines macros that allow you to use these values and other details about
the binary representation of real numbers in your programs. The following example prints the
storage space taken by a float type and its range values −
#include <stdio.h>
#include <float.h>
int main() {
When you compile and execute the above program, it produces the following result on Linux −
There are various functions in C which do not return any value or you can say
they return void. A function with no return value has the return type as void. For
example, void exit (int status);
There are various functions in C which do not accept any parameter. A function
with no parameter can accept a void. For example, int rand(void);
3 Pointers to void
A pointer of type void * represents the address of an object, but not its type. For
example, a memory allocation function void *malloc( size_t size ); returns a
pointer to void which can be casted to any data type.
C - Variable
A variable is nothing but a name given to a storage area that our programs can manipulate. Each
variable in C has a specific type, which determines the size and layout of the variable's memory;
the range of values that can be stored within that memory; and the set of operations that can be
applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore character. It must
begin with either a letter or an underscore. Upper and lowercase letters are distinct because C is
case-sensitive. Based on the basic types explained in the previous chapter, there will be the
following basic variable types −
1 char
2 int
3 float
4 double
5 void
C programming language also allows to define various other types of variables, which we will
cover in subsequent chapters like Enumeration, Pointer, Array, Structure, Union, etc. For this
chapter, let us study only basic variable types.
Variable Definition in C
A variable definition tells the compiler where and how much storage to create for the variable.
A variable definition specifies a data type and contains a list of one or more variables of that
type as follows −
type variable_list;
Here, type must be a valid C data type including char, w_char, int, float, double, bool, or any
user-defined object; and variable_list may consist of one or more identifier names separated by
commas. Some valid declarations are shown here −
int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; declares and defines the variables i, j, and k; which instruct the compiler to
create variables named i, j and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The initializer
consists of an equal sign followed by a constant expression as follows −
Variable Declaration in C
A variable declaration provides assurance to the compiler that there exists a variable with the
given type and name so that the compiler can proceed for further compilation without requiring
the complete detail about the variable. A variable definition has its meaning at the time of
compilation only, the compiler needs actual variable definition at the time of linking the
program.
A variable declaration is useful when you are using multiple files and you define your variable
in one of the files which will be available at the time of linking of the program. You will use the
keyword extern to declare a variable at any place. Though you can declare a variable multiple
times in your C program, it can be defined only once in a file, a function, or a block of code.
Example
Try the following example, where variables have been declared at the top, but they have been
defined and initialized inside the main function −
#include <stdio.h>
// Variable declaration:
extern int a, b;
extern int c;
extern float f;
int main () {
/* variable definition: */
int a, b;
int c;
float f;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
f = 70.0/3.0;
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of c : 30
value of f : 23.333334
Defining Constants
There are two simple ways in C to define constants −
#include <stdio.h>
#define LENGTH 10
#define WIDTH 5
int main() {
int area;
printf("%c", NEWLINE);
return 0;
When the above code is compiled and executed, it produces the following result −
value of area : 50
#include <stdio.h>
int main() {
int area;
printf("%c", NEWLINE);
return 0;
When the above code is compiled and executed, it produces the following result −
value of area : 50
C - Header Files
A header file is a file with extension .h which contains C function declarations and macro
definitions to be shared between several source files. There are two types of header files: the
files that the programmer writes and the files that comes with your compiler.
You request to use a header file in your program by including it with the C preprocessing
directive #include, like you have seen inclusion of stdio.h header file, which comes along with
your compiler.
Including a header file is equal to copying the content of the header file but we do not do it
because it will be error-prone and it is not a good idea to copy the content of a header file in the
source files, especially if we have multiple source files in a program.
A simple practice in C or C++ programs is that we keep all the constants, macros, system wide
global variables, and function prototypes in the header files and include that header file
wherever it is required.
We can also limit the number of digits or characters that can be input or output, by adding a
number with the format string specifier, like "%1d" or "%3s", the first one means a single
numeric digit and the second one means 3 characters, hence if you try to input 42,
while scanf() has "%1d", it will take only 4 as input. Same is the case for output.
In C Language, computer monitor, printer etc output devices are treated as files and the same
process is followed to write output to these devices as would have been followed to write the
output to a file.
Error is an illegal operation performed by the user which results in abnormal working of the
program.
Programming errors often remain undetected until the program is compiled or executed. Some of
the errors inhibit the program from getting compiled or executed. Thus errors should be removed
before compiling and executing.
The most common errors can be broadly classified as follows.
Type of errors
1. Syntax errors: Errors that occur when you violate the rules of writing C/C++ syntax are
known as syntax errors. This compiler error indicates something that must be fixed before
the code can be compiled. All these errors are detected by compiler and thus are known as
compile-time errors.
Most frequent syntax errors are:
Missing Parenthesis (})
Printing the value of variable without declaring it
Missing semicolon like this:
// C program to illustrate
// syntax error
#include<stdio.h>
void main()
{
int x = 10;
int y = 15;
// C program to illustrate
// syntax error
#include<stdio.h>
int main(void)
{
// while() cannot contain "." as an argument.
while(.)
{
printf("hello");
}
return 0;
}
Error:
error: expected expression before '.' token
while(.)
In the given example, the syntax of while loop is incorrect. This causes a syntax error.
2. Run-time Errors : Errors which occur during program execution(run-time) after
successful compilation are called run-time errors. One of the most common run-time error
is division by zero also known as Division error. These types of error are hard to find as the
compiler doesn’t point to the line at which the error occurs.
For more understanding run the example given below.
// C program to illustrate
// run-time error
#include<stdio.h>
void main()
{
int n = 9, div = 0;
// wrong logic
// number is divided by 0,
// so this program abnormally terminates
div = n/0;
// C program to illustrate
// linker error
#include<stdio.h>
void Main() // Here Main() should be main()
{
int a = 10;
printf("%d", a);
}
Error:
(.text+0x20): undefined reference to `main'
4. Logical Errors : On compilation and execution of a program, desired output is not
obtained when certain input values are given. These types of errors which provide incorrect
output but appears to be error free are called logical errors. These are one of the most
common errors done by beginners of programming.
These errors solely depend on the logical thinking of the programmer and are easy to detect
if we follow the line of execution and determine why the program takes that path of
execution.
// C program to illustrate
// logical error
int main()
{
int i = 0;
// C program to illustrate
// semantic error
void main()
{
int a, b, c;
a + b = c; //semantic error
}
Error
error: lvalue required as left operand of assignment
a + b = c; //semantic error
Operators Precedence in C
Operator precedence determines the grouping of terms in an expression and decides how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has a higher precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Computers do not understand human languages. In fact, at the lowest level, computers only
understand sequences of numbers that represent operational codes (op codes for short). On the
other hand, it would be very difficult for humans to write programs in terms of op codes.
Therefore, programming languages were invented to make it easier for humans to write computer
programs.
Programming languages are for humans to read and understand. The program (source code) must
be translated into machine language so that the computer can execute the program (as the
computer only understands machine language). The way that this translation occurs depends on
whether the programming language is a compiled language or an interpreted language.
The following illustrates the programming process for a compiled programming language.
A compiler takes the program code (source code) and converts the source code to a machine
language module (called an object file). Another specialized program, called a linker, combines
this object file with other previously compiled object files (in particular run-time modules) to
create an executable file. This process is diagrammed below. Click Initial build to see an
animation of how the executable is created. Click Run executable to simulate the running of an
already created executable file. Click Rebuild to simulate rebuilding of the executable file.
UNIT 3
In a 'C' program are executed sequentially. This happens when there is no condition around the
statements. If you put some condition for a block of statements the flow of execution might
change based on the result evaluated by the condition. This process is referred to as decision
making in 'C.' The decision-making statements are also called as control statements.
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:
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 { }.
Output:
The above program illustrates the use of if construct to check equality of two numbers.
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:
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
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.
Summary
Decision making or branching statements are used to select one path based on the result
of the evaluated expression.
It is also called as control statements because it controls the flow of execution of a
program.
'C' provides if, if-else constructs for decision-making statements.
We can also nest if-else within one another when multiple paths have to be tested.
The else-if ladder is used when we have to check various ways based upon the result of
the expression.
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 −
C programming language provides the following types of loops to handle looping requirements.
1 while loop
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.
Loop Control Statements
Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed.
1 break statement
Terminates the loop or switch statement and transfers execution to the statement
immediately following the loop or switch.
2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its
condition prior to reiterating.
3 goto statement
#include <stdio.h>
int main () {
for( ; ; ) {
}
return 0;
When the conditional expression is absent, it is assumed to be true. You may have an
initialization and increment expression, but C programmers more commonly use the for (; ;)
construct to signify an infinite loop.
Table of Contents
C Arrays
How to declate arrays?
How to access array elements?
How to initialize an array?
How to insert elements to an array?
Initialize array during declaration
Example: Arrays
Be careful while using arrays in C
An array is a collection of a fixed number of values of a single type. For example: if you want to
store 100 integers in sequence, you can create an array for it.
int data[100];
The size and type of arrays cannot be changed after its declaration.
data_type array_name[array_size];
For example,
float mark[5];
Here, we declared an array, mark, of floating-point type and size 5. Meaning, it can hold 5
floating-point values.
Suppose you declared an array mark as above. The first element is mark[0], second element
is mark[1] and so on.
Here,
mark[0] is equal to 19
mark[1] is equal to 10
mark[2] is equal to 8
mark[3] is equal to 17
mark[4] is equal to 9
mark[3] = 9;
scanf("%d", &mark[2]);
scanf("%d", &mark[i]);
printf("%d", mark[0]);
printf("%d", mark[i-1]);
Example: C Arrays
// Program to find the average of n (n < 10) numbers using arrays
#include <stdio.h>
int main()
{
int marks[10], i, n, sum = 0, average;
printf("Enter n: ");
scanf("%d", &n);
for(i=0; i<n; ++i)
{
printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);
sum += marks[i];
}
average = sum/n;
return 0;
}
Output
Enter n: 5
Enter number1: 45
Enter number2: 35
Enter number3: 38
Enter number4: 31
Enter number5: 49
Average = 39
int testArray[10];
Table of Contents
Multidimensional array
How to initialize a multidimensional array?
o 2d array
o 3d array
Example 1: 2d array to store and print values
Example 2: Sum of two matrices
Example 3: Three Dimensional Array
In C programming, you can create array of an array known as multidimensional array. For
example,
float x[3][4];
Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can think the array
as table with 3 row and each row has 4 column.
Similarly, you can declare a three-dimensional (3d) array. For example,
float y[2][4][3];
You can think this example as: Each 2 elements have 4 elements, which makes 8 elements and
each 8 elements can have 3 elements. Hence, the total number of elements is 24.
Above code are three different ways to initialize a two dimensional arrays.
You can initialize a three dimensional array in a similar way like a two dimensional array. Here's
an example,
int test[2][3][4] = {
};
#include <stdio.h>
int main()
{
int temperature[CITY][WEEK];
for (int i = 0; i < CITY; ++i) {
for(int j = 0; j < WEEK; ++j) {
printf("City %d, Day %d: ", i+1, j+1);
scanf("%d", &temperature[i][j]);
}
}
Output
City 1, Day 1: 33
City 1, Day 2: 34
City 1, Day 3: 35
City 1, Day 4: 33
City 1, Day 5: 32
City 1, Day 6: 31
City 1, Day 7: 30
City 2, Day 1: 23
City 2, Day 2: 22
City 2, Day 3: 21
City 2, Day 4: 24
City 2, Day 5: 22
City 2, Day 6: 25
City 2, Day 7: 26
Displaying values:
City 1, Day 1 = 33
City 1, Day 2 = 34
City 1, Day 3 = 35
City 1, Day 4 = 33
City 1, Day 5 = 32
City 1, Day 6 = 31
City 1, Day 7 = 30
City 2, Day 1 = 23
City 2, Day 2 = 22
City 2, Day 3 = 21
City 2, Day 4 = 24
City 2, Day 5 = 22
City 2, Day 6 = 25
City 2, Day 7 = 26
#include <stdio.h>
int main()
{
float a[2][2], b[2][2], c[2][2];
int i, j;
if(j==1)
printf("\n");
}
return 0;
}
Ouput
Enter a11: 2;
Enter a22: 2;
Enter b12: 0;
Sum Of Matrix:
2.2 0.5
-0.9 25.0
printf("\nDisplaying values:\n");
for(i = 0; i < 2; ++i) {
for (j = 0; j < 3; ++j) {
for(k = 0; k < 2; ++k ) {
printf("test[%d][%d][%d] = %d\n", i, j, k, test[i][j][k]);
}
}
}
return 0;
}
Output
Enter 12 values:
10
11
12
Displaying Values:
test[0][0][0] = 1
test[0][0][1] = 2
test[0][1][0] = 3
test[0][1][1] = 4
test[0][2][0] = 5
test[0][2][1] = 6
test[1][0][0] = 7
test[1][0][1] = 8
test[1][1][0] = 9
test[1][1][1] = 10
test[1][2][0] = 11
test[1][2][1] = 12
Table of Contents
You can pass a single array element of an array or an entire array to a function.
int main()
{
int ageArray[] = {2, 3, 4};
display(ageArray[2]); //Passing array element ageArray[2]
return 0;
}
Output
#include <stdio.h>
float average(float age[]);
int main()
{
float avg, age[] = {23.4, 55, 22.6, 3, 40.5, 18};
avg = average(age); // Only name of an array is passed as an argument
printf("Average age = %.2f", avg);
return 0;
}
Output
To pass an entire array to a function, only the name of the array is passed as an argument.
However, notice the use of [] after argument name in float average(float age[]). This informs the
compiler that you are passing a one-dimensional array to the function.
To pass multidimensional arrays to a function, only the name of the array is passed (similar to
one dimensional array).
Output
Enter 4 numbers:
5
Displaying:
Table of Contents
What is a function?
Types of function
Standard library function
User-defined function
How user-defined function work?
Advantages of function
Suppose, a program related to graphics needs to create a circle and color it depending upon the
radius and color from the user. You can create two functions to solve this problem:
Dividing complex problem into small components makes program easy to understand and use.
Types of function
Depending on whether a function is defined by the user or already included in C compilers, there
are two types of functions in C programming
The standard library functions are built-in functions in C programming to handle tasks such as
mathematical computations, I/O processing, string handling etc.
These functions are defined in the header file. When you include the header file, these functions
are available for use. For example:
The printf() is a standard library function to send formatted output to the screen (display output
on the screen). This function is defined in "stdio.h" header file.
There are other numerous library functions defined under "stdio.h", such
as scanf(), fprintf(), getchar() etc. Once you include "stdio.h" in your program, all these functions
are available for use.
User-defined function
As mentioned earlier, C allow programmers to define functions. Such functions created by the
user are called user-defined functions.
#include <stdio.h>
void functionName()
... .. ...
... .. ...
}
int main()
... .. ...
... .. ...
functionName();
... .. ...
... .. ...
When the compiler encounters functionName(); inside the main function, control of the program
jumps to
void functionName()
And, the compiler starts executing the codes inside the user-defined function.
The control of the program jumps to statement next to functionName(); once all the codes inside
the function definition are executed.
Remember, function name is an identifier and should be unique.
This is just an overview on user-defined function. Visit these pages to learn more on:
User-defined Function
Example: User-defined-function
Function prototype
Function call
Function definition
Passing arguments to a function
Return statement
C allows you to define functions according to your need. These functions are known as user-
defined functions. For example:
Suppose, you need to create a circle and color it depending upon the radius and color. You can
create two functions to solve this problem:
createCircle() function
color() function
#include <stdio.h>
int main()
{
int n1,n2,sum;
printf("sum = %d",sum);
return 0;
}
Function prototype
A function prototype is simply the declaration of a function that specifies function's name,
parameters and return type. It doesn't contain function body.
A function prototype gives information to the compiler that the function may later be used in the
program.
In the above example, int addNumbers(int a, int b); is the function prototype which provides
following information to the compiler:
The function prototype is not needed if the user-defined function is defined before
the main() function.
Calling a function
In the above example, function call is made using addNumbers(n1,n2); statement inside
the main().
Function definition
Function definition contains the block of code to perform a specific task i.e. in this case, adding
two numbers and returning it.
When a function is called, the control of the program is transferred to the function definition.
And, the compiler starts executing the codes inside the body of a function.
In programming, argument refers to the variable passed to the function. In the above example,
two variables n1 and n2 are passed during function call.
The parameters a and b accepts the passed arguments in the function definition. These arguments
are called formal parameters of the function.
The type of arguments passed to a function and the formal parameters must match, otherwise the
compiler throws error.
If n1 is of char type, a also should be of char type. If n2 is of float type, variable b also should be
of float type.
Return Statement
The return statement terminates the execution of a function and returns a value to the calling
function. The program control is transferred to the calling function after return statement.
In the above example, the value of variable result is returned to the variable sum in
the main() function.
return (expression);
For example,
return a;
return (a+b);
Table of Contents
These 4 programs below check whether the integer entered by the user is prime number or not.
The output of all these programs below is same, and we have created a user-defined function in
each example. However, the approch we have taken in each example is different.
void checkPrimeNumber();
int main()
{
checkPrimeNumber(); // argument is not passed
return 0;
}
// return type of the function is void because function is not returning anything
void checkPrimeNumber()
{
int n, i, flag=0;
The checkPrimeNumber() function takes input from the user, checks whether it is a prime
number or not and displays it on the screen.
The empty parentheses in checkPrimeNumber(); statement inside the main() function indicates
that no argument is passed to the function.
The return type of the function is void. Hence, no value is returned from the function.
int main()
{
int n, i, flag = 0;
if (flag == 1)
printf("%d is not a prime number.", n);
else
printf("%d is a prime number.", n);
return 0;
}
return n;
}
The empty parentheses in n = getInteger(); statement indicates that no argument is passed to the
function. And, the value returned from the function is assigned to n.
Here, the getInteger() function takes input from the user and returns it. The code to check
whether a number is prime or not is inside the main() function.
int main()
{
int n;
return 0;
}
Here, the checkPrimeAndDisplay() function checks whether the argument passed is a prime
number or not and displays the appropriate message.
int main()
{
int n, flag;
if(flag == 1)
printf("%d is not a prime number",n);
else
printf("%d is a prime number",n);
return 0;
}
// integer is returned from the function
int checkPrimeNumber(int n)
{
int i;
return 0;
}
The checkPrimeNumber() function checks whether the passed argument is prime or not. If the
passed argument is a prime number, the function returns 0. If the passed argument is a non-prime
number, the function returns 1. The return value is assigned to the flag variable.
Depending on whether flag is 0 or 1, appropriate message is printed from the main () function.
Table of Contents
Recursion
How recursion works?
Example: Sum of Natural Numbers Using Recursion
Advantages and Disadvantages of Recursion
A function that calls itself is known as a recursive function. And, this technique is known as
recursion.
void recurse()
{
... .. ...
recurse();
... .. ...
int main()
... .. ...
recurse();
... .. ...
To prevent infinite recursion, if...else statement (or similar approach) can be used where one
branch makes the recursive call and other doesn't.
int main()
{
int number, result;
result = sum(number);
Output
sum = 6
Initially, the sum() is called from the main() function with number passed as an argument.
Suppose, the value of num is 3 initially. During next function call, 2 is passed to
the sum()function. This process continues until num is equal to 0.
When num is equal to 0, the if condition fails and the else part is executed returning the sum of
integers to the main() function.
Advantages and Disadvantages of Recursion
Recursion makes program elegant and more readable. However, if performance is vital
then, use loops instead as recursion is usually much slower.
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
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 value of actual parameter
s do not change by changing the formal parameters in call by value, 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
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
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
2 Changes made inside the Changes made inside the function validate outside of the
function is limited to the function also. The values of the actual parameters do
function only. The change by changing the formal parameters.
values of the actual
parameters do not
change by changing the
formal parameters.
3 Actual and formal Actual and formal arguments are created at the same
arguments are created at memory location
the different memory
location
else
{
for(i=1; i<=n; ++i)
{
factorial *= i; // factorial = factorial*i;
}
printf("Factorial of %d = %llu", n, factorial);
}
return 0;
}
Output
Enter an integer: 10
Factorial of 10 = 3628800
int main()
{
int n;
printf("Enter a positive integer: ");
scanf("%d", &n);
printf("Factorial of %d = %ld", n, multiplyNumbers(n));
return 0;
}
long int multiplyNumbers(int n)
{
if (n >= 1)
return n*multiplyNumbers(n-1);
else
return 1;
}
Output
Factorial of 6 = 720
Initially, the multiplyNumbers() is called from the main() function with 6 passed as an argument.
Then, 5 is passed to the multiplyNumbers() function from the same function (recursive call). In
each recursive call, the value of argument n is decreased by 1.
Output
nextTerm = t1 + t2;
while(nextTerm <= n)
{
printf("%d, ",nextTerm);
t1 = t2;
t2 = nextTerm;
nextTerm = t1 + t2;
}
return 0;
}
Output
Ackermann Function
The Ackermann function is the simplest example of a well-defined total function which is
computable but not primitive recursive, providing a counterexample to the belief in the early
1900’s that every computable function was also primitive recursive . It grows faster than an
exponential function, or even a multiple exponential function.
Below is the source code for C Program to implement Ackermann function using recursion
which is successfully compiled and run on Windows System to produce desired output as shown
below :
SOURCE CODE : :
3 #include<stdio.h>
6 main()
7 {
8 int m,n;
10 scanf("%d%d",&m,&n);
11 printf("\nOUTPUT :: %d\n",A(m,n));
12 }
13
15 {
16 if(m==0)
17 return n+1;
18 else if(n==0)
19 return A(m-1,1);
20 else
21 return A(m-1,A(m,n-1));
22 }
OUTPUT : :
Visual Basic
8 1
9 0
10
11 OUTPUT :: 2
12
13
15
17 0
18 5
19
20 OUTPUT :: 6