0% found this document useful (0 votes)
20 views

6. Fundamentals of C Programming

This document provides an introduction to programming languages, focusing on high-level languages, algorithms, and the C programming language. It discusses the characteristics of programming languages, the importance of algorithms in problem-solving, and the structure and types of C, including data types and variable definitions. Additionally, it covers flowcharts as a visual representation of algorithms and the significance of pseudocode in algorithm design.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

6. Fundamentals of C Programming

This document provides an introduction to programming languages, focusing on high-level languages, algorithms, and the C programming language. It discusses the characteristics of programming languages, the importance of algorithms in problem-solving, and the structure and types of C, including data types and variable definitions. Additionally, it covers flowcharts as a visual representation of algorithms and the significance of pseudocode in algorithm design.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 88

UNIT 2

Introduction to Programming Languages

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.

Hierarchy of Computer language –

Most Popular Programming Languages –


 C
 Python
 C++
 Java
 SCALA
 C#
 R
 Ruby
 Go
 Swift
 JavaScript
Characteristics of a programming Language –
 A programming language must be simple, easy to learn and use, have good readability and
human recognizable.
 Abstraction is a must-have Characteristics for a programming language in which ability to
define the complex structure and then its degree of usability comes.
 A portable programming language is always preferred.
 Programming language’s efficiency must be high so that it can be easily converted into a
machine code and executed consumes little space in memory.
 A programming language should be well structured and documented so that it is suitable
for application development.
 Necessary tools for development, debugging, testing, maintenance of a program must be
provided by a programming language.
 A programming language should provide single environment known as Integrated
Development Environment (IDE).
 A programming language must be consistent in terms of syntax and semantics.

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 must have a unique name

 Algorithms should have explicitly defined set of inputs and outputs

 Algorithms are well-ordered with unambiguous operations

 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.

Difference between Algorithm and Pseudocode


An algorithm is a formal definition with some specific characteristics that describes a process,
which could be executed by a Turing-complete computer machine to perform a specific task.
Generally, the word "algorithm" can be used to describe any high level task in computer
science.
On the other hand, pseudocode is an informal and (often rudimentary) human readable
description of an algorithm leaving many granular details of it. Writing a pseudocode has no
restriction of styles and its only objective is to describe the high level steps of algorithm in a
much realistic manner in natural language.

For example, following is an algorithm for Insertion Sort.

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.

for i <- 1 to length(A)


x <- A[i]
j <- i
while j > 0 and A[j-1] > x
A[j] <- A[j-1]
j <- j - 1
A[j] <- x
In this tutorial, algorithms will be presented in the form of pseudocode, that is similar in many
respects to C, C++, Java, Python, and other programming languages.

Flowchart is a diagrammatic representation of sequence of logical steps of a program.


Flowcharts use simple geometric shapes to depict processes and arrows to show relationships
and process/data flow.

Flowchart Symbols
Here is a chart for some of the common symbols used in drawing flowcharts.

Symbol Symbol Name Purpose

Used at the beginning and end of the algorithm


Start/Stop
to show start and end of the program.
Indicates processes like mathematical
Process operations.

Input/ Output Used for denoting program inputs and outputs.

Stands for decision statements in a program,


where answer is usually Yes or No.
Decision

Shows relationships between different shapes.


Arrow

Connects two or more parts of a flowchart,


On-page Connector which are on the same page.

Connects two parts of a flowchart which are


Off-page Connector spread over different pages.

Guidelines for Developing Flowcharts


These are some points to keep in mind while developing a flowchart −

 Flowchart can have only one start and one stop symbol

 On-page connectors are referenced using numbers

 Off-page connectors are referenced using alphabets

 General flow of processes is top to bottom or left to right

 Arrows should not cross each other


Example Flowcharts
Here is the flowchart for going to the market to purchase a pen.

Here is a flowchart to calculate the average of two numbers.


C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie
to develop the UNIX operating system at Bell Labs. C was originally first implemented on the
DEC PDP-11 computer in 1972.

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.

 C is a successor of B language which was introduced around the early 1970s.

 The language was formalized in 1988 by the American National Standard Institute
(ANSI).

 The UNIX OS was totally written in C.

 Today C is the most widely used and popular System Programming Language.

 Most of the state-of-the-art software have been implemented using C.

 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.

auto else long switch

break enum register typedef

case extern return union

char float short unsigned

const for signed void

continue goto sizeof volatile

default if static while

do int struct _Packed

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.

The types in C can be classified as follows −

Sr.No. Types & Description

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.

3 The type void

The type specifier void indicates that no value is available.

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

char 1 byte -128 to 127 or 0 to 255

unsigned char 1 byte 0 to 255

signed char 1 byte -128 to 127

-32,768 to 32,767 or -2,147,483,648 to


int 2 or 4 bytes
2,147,483,647

unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295

short 2 bytes -32,768 to 32,767

unsigned short 2 bytes 0 to 65,535

long 4 bytes -2,147,483,648 to 2,147,483,647

unsigned long 4 bytes 0 to 4,294,967,295

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() {

printf("Storage size for int : %d \n", sizeof(int));


return 0;

When you compile and execute the above program, it produces the following result on Linux −

Storage size for int : 4

Floating-Point Types
The following table provide the details of standard floating-point types with storage sizes and
value ranges and their precision −

Type Storage size Value range Precision

float 4 byte 1.2E-38 to 3.4E+38 6 decimal places

double 8 byte 2.3E-308 to 1.7E+308 15 decimal places

long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places

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() {

printf("Storage size for float : %d \n", sizeof(float));

printf("Minimum float positive value: %E\n", FLT_MIN );

printf("Maximum float positive value: %E\n", FLT_MAX );

printf("Precision value: %d\n", FLT_DIG );


return 0;

When you compile and execute the above program, it produces the following result on Linux −

Storage size for float : 4


Minimum float positive value: 1.175494E-38
Maximum float positive value: 3.402823E+38
Precision value: 6

The void Type


The void type specifies that no value is available. It is used in three kinds of situations −

Sr.No. Types & Description

1 Function returns as void

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);

2 Function arguments as void

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 −

Sr.No. Type & Description

1 char

Typically a single octet(one byte). This is an integer type.

2 int

The most natural size of integer for the machine.

3 float

A single-precision floating point value.

4 double

A double-precision floating point value.

5 void

Represents the absence of type.

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 −

type variable_name = value;


Some examples are −

extern int d = 3, f = 5; // declaration of d and f.


int d = 3, f = 5; // definition and initializing d and f.
byte z = 22; // definition and initializes z.
char x = 'x'; // the variable x has the value 'x'.
For definition without an initializer: variables with static storage duration are implicitly
initialized with NULL (all bytes have the value 0); the initial value of all other variables are
undefined.

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;

printf("value of c : %d \n", c);

f = 70.0/3.0;

printf("value of f : %f \n", f);

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 −

 Using #define preprocessor.

 Using const keyword.

The #define Preprocessor


Given below is the form to use #define preprocessor to define a constant −

#define identifier value


The following example explains it in detail −

#include <stdio.h>

#define LENGTH 10

#define WIDTH 5

#define NEWLINE '\n'

int main() {

int area;

area = LENGTH * WIDTH;

printf("value of area : %d", area);

printf("%c", NEWLINE);
return 0;

When the above code is compiled and executed, it produces the following result −

value of area : 50

The const Keyword


You can use const prefix to declare constants with a specific type as follows −

const type variable = value;


The following example explains it in detail −

#include <stdio.h>

int main() {

const int LENGTH = 10;

const int WIDTH = 5;

const char NEWLINE = '\n';

int area;

area = LENGTH * WIDTH;

printf("value of area : %d", 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.

C Input and Output


Input means to provide the program with some data to be used in the program
and Output means to display data on screen or write the data to a printer or a file.
C programming language provides many built-in functions to read any given input and to display
data on screen when there is a need to output the result.
In this tutorial, we will learn about such functions, which can be used in our program to take
input from user and to output the result on screen.
All these built-in functions are present in C header files, we will also specify the name of header
files in which a particular function is defined while discussing about it.

scanf() and printf() functions


The standard input-output header file, named stdio.h contains the definition of the
functions printf() and scanf(), which are used to display output on screen and to take input from
user respectively.
When you will compile the above code, it will ask you to enter a value. When you will enter the
value, it will display the value you have entered on screen.
You must be wondering what is the purpose of %d inside the scanf() or printf() functions. It is
known as format string and this informs the scanf() function, what type of input to expect and
in printf() it is used to give a heads up to the compiler, what type of output to expect.

Format String Meaning

%d Scan or print an integer as signed decimal number

%f Scan or print a floating point number

%c To scan or print a character

%s To scan or print a character string. The scanning ends at whitespace.

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.

getchar() & putchar() functions


The getchar() function reads a character from the terminal and returns it as an integer. This
function reads only single character at a time. You can use this method in a loop in case you
want to read more than one character. The putchar() function displays the character passed to it
on the screen and returns the same character. This function too displays only a single character at
a time. In case you want to display more than one characters, use putchar() method in a loop.
Errors in C/C++

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;

printf("%d", (x, y)) // semicolon missed


}
Error:

error: expected ';' before '}' token


 Syntax of a basic construct is written wrong. For example : while loop

// 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;

printf("resut = %d", div);


}
Error:
warning: division by zero [-Wdiv-by-zero]
div = n/0;
In the given example, there is Division by zero error. This is an example of run-time error
i.e errors occurring while running the program.
3. Linker Errors: These error occurs when after compilation we link the different object files
with main’s object using Ctrl+F9 key(RUN). These are errors generated when the
executable of the program cannot be generated. This may be due to wrong function
prototyping, incorrect header files. One of the most common linker error is
writing Main() instead of main().

// 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;

// logical error : a semicolon after loop


for(i = 0; i < 3; i++);
{
printf("loop ");
continue;
}
getchar();
return 0;
}
No output
5. Semantic errors : This error occurs when the statements written in the program are not
meaningful to the compiler.

// 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.

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right


Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

The Programming Process

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.

Compiled languages (e.g. C, C++)

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

What is a Conditional Statement?

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.

In this tutorial, you will learn-

 What is a Conditional Statement?


 If statement
 Relational Operators
 The If-Else statement
 Conditional Expressions
 Nested If-else Statements
 Nested Else-if statements

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 { }.

Following program illustrates the use of if construct in 'C' programming:


#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:

num1 is smaller than num2

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 :

< less than


<= less than or equal to

> greater than

>= greater than or equal to

== 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 :

There is someone present in the classroom

The If-Else statement

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.

Following programs illustrate the use of the if-else construct:

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:

The value is greater than 10


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

There is another way to express an if-else statement is by introducing the ?: operator. In a


conditional expression the ?: operator has only one statement associated with the if and the else.

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.

Let's write a program to illustrate the use of nested if-else.

#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 value is:1

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.

Nested Else-if statements

Nested else-if is used when multipath decisions are required.

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.

Let us see the actual working with the help of a program.

#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.

Sr.No. Loop Type & Description

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

C supports the following control statements.

Sr.No. Control Statement & Description

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

Transfers control to the labeled statement.

The Infinite Loop


A loop becomes an infinite loop if a condition never becomes false. The forloop is traditionally
used for this purpose. Since none of the three expressions that form the 'for' loop are required,
you can make an endless loop by leaving the conditional expression empty.

#include <stdio.h>

int main () {

for( ; ; ) {

printf("This loop will run forever.\n");

}
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.

NOTE − You can terminate an infinite loop by pressing Ctrl + C keys.


Unit 4

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.

Arrays are of two types:


1. One-dimensional arrays
2. Multidimensional arrays (will be discussed in next chapter)

How to declare arrays?

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.

Elements of an Array and How to access them?

You can access elements of an array by indices.

Suppose you declared an array mark as above. The first element is mark[0], second element
is mark[1] and so on.

Few key notes:

 Arrays have 0 as the first index not 1. In this example, mark[0]


 If the size of an array is n, to access the last element, (n-1) index is used. In this
example, mark[4]
 Suppose the starting address of mark[0] is 2120d. Then, the next address, a[1], will be
2124d, address of a[2] will be 2128d and so on. It's because the size of a float is 4 bytes.
How to initialize an array?

It's possible to initialize an array during declaration. For example,

int mark[5] = {19, 10, 8, 17, 9};

Another method to initialize array during declaration:

int mark[] = {19, 10, 8, 17, 9};

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

How to insert and print array elements?


int mark[5] = {19, 10, 8, 17, 9}

// insert different value to third element

mark[3] = 9;

// take input from the user and insert in third element

scanf("%d", &mark[2]);

// take input from the user and insert in (i+1)th element

scanf("%d", &mark[i]);

// print first element of an array

printf("%d", mark[0]);

// print ith element of an array

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;

printf("Average = %d", average);

return 0;
}

Output

Enter n: 5

Enter number1: 45

Enter number2: 35

Enter number3: 38

Enter number4: 31
Enter number5: 49

Average = 39

Important thing to remember when working with C arrays

Suppose you declared an array of 10 elements. Let's say,

int testArray[10];

You can use the array members from testArray[0] to testArray[9].

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];

Here,The array y can hold 24 elements.

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.

How to initialize a multidimensional array?

There is more than one way to initialize a multidimensional array.

Initialization of a two dimensional array

// Different ways to initialize two dimensional array

int c[2][3] = {{1, 3, 0}, {-1, 5, 9}};

int c[][3] = {{1, 3, 0}, {-1, 5, 9}};


int c[2][3] = {1, 3, 0, -1, 5, 9};

Above code are three different ways to initialize a two dimensional arrays.

Initialization of a three dimensional array.

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] = {

{ {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} },

{ {13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9} }

};

Example 1: Two Dimensional Array to store and print values


// C program to store temperature of two cities for a week and display it.

#include <stdio.h>

const int CITY = 2;


const int WEEK = 7;

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]);
}
}

printf("\nDisplaying values: \n\n");


for (int i = 0; i < CITY; ++i) {
for(int j = 0; j < WEEK; ++j)
{
printf("City %d, Day %d = %d\n", i+1, j+1, temperature[i][j]);
}
}
return 0;
}

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

Example 2: Sum of two matrices using Two dimensional arrays

// C program to find the sum of two matrices of order 2*2

#include <stdio.h>
int main()
{
float a[2][2], b[2][2], c[2][2];
int i, j;

// Taking input using nested for loop


printf("Enter elements of 1st matrix\n");
for(i=0; i<2; ++i)
for(j=0; j<2; ++j)
{
printf("Enter a%d%d: ", i+1, j+1);
scanf("%f", &a[i][j]);
}
// Taking input using nested for loop
printf("Enter elements of 2nd matrix\n");
for(i=0; i<2; ++i)
for(j=0; j<2; ++j)
{
printf("Enter b%d%d: ", i+1, j+1);
scanf("%f", &b[i][j]);
}

// adding corresponding elements of two arrays


for(i=0; i<2; ++i)
for(j=0; j<2; ++j)
{
c[i][j] = a[i][j] + b[i][j];
}

// Displaying the sum


printf("\nSum Of Matrix:");

for(i=0; i<2; ++i)


for(j=0; j<2; ++j)
{
printf("%.1f\t", c[i][j]);

if(j==1)
printf("\n");
}
return 0;
}
Ouput

Enter elements of 1st matrix

Enter a11: 2;

Enter a12: 0.5;

Enter a21: -1.1;

Enter a22: 2;

Enter elements of 2nd matrix

Enter b11: 0.2;

Enter b12: 0;

Enter b21: 0.23;

Enter b22: 23;

Sum Of Matrix:

2.2 0.5

-0.9 25.0

Example 3: Three-Dimensional Array

// C Program to store and print 12 values entered by the user


#include <stdio.h>
int main()
{
int i, j, k, test[2][3][2];

printf("Enter 12 values: \n");

for(i = 0; i < 2; ++i) {


for (j = 0; j < 3; ++j) {
for(k = 0; k < 2; ++k ) {
scanf("%d", &test[i][j][k]);
}
}
}

// Printing values with proper index.

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

 Passing One-dimensional Array


o Example 1: Passing single element of an array
o Example 2: Passing an entire array
 Passing multidimensional array to a function
o Example 3: Passing 2d array to a function

You can pass a single array element of an array or an entire array to a function.

Passing One-dimensional Array to a Function

Passing a single element of an array to a function is similar to passing variable to a function.

Example 1: Passing single element of an array to function


#include <stdio.h>
void display(int age)
{
printf("%d", age);
}

int main()
{
int ageArray[] = {2, 3, 4};
display(ageArray[2]); //Passing array element ageArray[2]
return 0;
}

Output

Example 2: Passing an entire array to a function


// Program to calculate average by passing an array to a function

#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;
}

float average(float age[])


{
int i;
float avg, sum = 0.0;
for (i = 0; i < 6; ++i) {
sum += age[i];
}
avg = (sum / 6);
return avg;
}

Output

Average age = 27.08

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.

Passing Multi-dimensional Arrays to Function

To pass multidimensional arrays to a function, only the name of the array is passed (similar to
one dimensional array).

Example 3: Passing two-dimensional array to a function


#include <stdio.h>
void displayNumbers(int num[2][2]);
int main()
{
int num[2][2], i, j;
printf("Enter 4 numbers:\n");
for (i = 0; i < 2; ++i)
for (j = 0; j < 2; ++j)
scanf("%d", &num[i][j]);

// passing multi-dimensional array to a function


displayNumbers(num);
return 0;
}

void displayNumbers(int num[2][2])


{
int i, j;
printf("Displaying:\n");
for (i = 0; i < 2; ++i)
for (j = 0; j < 2; ++j)
printf("%d\n", num[i][j]);
}

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

A function is a block of code that performs a specific task.

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:

 create a circle function


 color function

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

There are two types of function in C programming:

 Standard library functions


 User defined functions
Standard library functions

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.

Learn more about standard library functions in C programming

User-defined function

As mentioned earlier, C allow programmers to define functions. Such functions created by the
user are called user-defined functions.

You can create as many user-defined functions as you want.

How user-defined function works?

#include <stdio.h>

void functionName()

... .. ...

... .. ...

}
int main()

... .. ...

... .. ...

functionName();

... .. ...

... .. ...

The execution of a C program begins from the main() function.

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 in C programming


 Types of user-defined Functions

Advantages of user-defined function

1. The program will be easier to understand, maintain and debug.


2. Reusable codes that can be used in other programs
3. A large program can be divided into smaller modules. Hence, a large project can be
divided among many programmers.
Table of Contents

 User-defined Function
 Example: User-defined-function
 Function prototype
 Function call
 Function definition
 Passing arguments to a function
 Return statement

A function is a block of code that performs a specific task.

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

Example: User-defined function

Here is an example to add two integers. To perform this task, an user-defined


function addNumbers() is defined.

#include <stdio.h>

int addNumbers(int a, int b); // function prototype

int main()
{
int n1,n2,sum;

printf("Enters two numbers: ");


scanf("%d %d",&n1,&n2);
sum = addNumbers(n1, n2); // function call

printf("sum = %d",sum);

return 0;
}

int addNumbers(int a,int b) // function definition


{
int result;
result = a+b;
return result; // return statement
}

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.

Syntax of function prototype

returnType functionName(type1 argument1, type2 argument2,...);

In the above example, int addNumbers(int a, int b); is the function prototype which provides
following information to the compiler:

1. name of the function is addNumbers()


2. return type of the function is int
3. two arguments of type int are passed to the function

The function prototype is not needed if the user-defined function is defined before
the main() function.
Calling a function

Control of the program is transferred to the user-defined function by calling it.

Syntax of function call

functionName(argument1, argument2, ...);

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.

Syntax of function definition

returnType functionName(type1 argument1, type2 argument2, ...)

//body of the function

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.

Passing arguments to 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.

A function can also be called without passing an argument.

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.

Syntax of return statement

return (expression);

For example,

return a;

return (a+b);
Table of Contents

 Example: Function with no arguments and no return value


 Example: Function with no arguments and a return value
 Example: Function with arguments and no return value
 Example: Function with arguments and a return value
 Which approach is better?

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.

Example 1: No arguments passed and no return Value


#include <stdio.h>

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;

printf("Enter a positive integer: ");


scanf("%d",&n);

for(i=2; i <= n/2; ++i)


{
if(n%i == 0)
{
flag = 1;
}
}
if (flag == 1)
printf("%d is not a prime number.", n);
else
printf("%d is a prime number.", n);
}

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.

Example 2: No arguments passed but a return value


#include <stdio.h>
int getInteger();

int main()
{
int n, i, flag = 0;

n = getInteger(); // no argument is passed

for(i=2; i<=n/2; ++i)


{
if(n%i==0){
flag = 1;
break;
}
}

if (flag == 1)
printf("%d is not a prime number.", n);
else
printf("%d is a prime number.", n);

return 0;
}

int getInteger() // returns integer entered by the user


{
int n;

printf("Enter a positive integer: ");


scanf("%d",&n);

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.

Example 3: Argument passed but no return value


#include <stdio.h>
void checkPrimeAndDisplay(int n);

int main()
{
int n;

printf("Enter a positive integer: ");


scanf("%d",&n);

// n is passed to the function


checkPrimeAndDisplay(n);

return 0;
}

// void indicates that no value is returned from the function


void checkPrimeAndDisplay(int n)
{
int i, flag = 0;

for(i=2; i <= n/2; ++i)


{
if(n%i == 0){
flag = 1;
break;
}
}
if(flag == 1)
printf("%d is not a prime number.",n);
else
printf("%d is a prime number.", n);
}

The integer value entered by the user is passed to checkPrimeAndDisplay() function.

Here, the checkPrimeAndDisplay() function checks whether the argument passed is a prime
number or not and displays the appropriate message.

Example 4: Argument passed and a return value


#include <stdio.h>
int checkPrimeNumber(int n);

int main()
{
int n, flag;

printf("Enter a positive integer: ");


scanf("%d",&n);

// n is passed to the checkPrimeNumber() function


// the value returned from the function is assigned to flag variable
flag = checkPrimeNumber(n);

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;

for(i=2; i <= n/2; ++i)


{
if(n%i == 0)
return 1;
}

return 0;
}

The input from the user is passed to checkPrimeNumber() function.

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.

How recursion works?

void recurse()
{

... .. ...

recurse();

... .. ...

int main()

... .. ...

recurse();

... .. ...

The recursion continues until some condition is met to prevent it.

To prevent infinite recursion, if...else statement (or similar approach) can be used where one
branch makes the recursive call and other doesn't.

Example: Sum of Natural Numbers Using Recursion


#include <stdio.h>
int sum(int n);

int main()
{
int number, result;

printf("Enter a positive integer: ");


scanf("%d", &number);

result = sum(number);

printf("sum = %d", result);


return 0;
}

int sum(int num)


{
if (num!=0)
return num + sum(num-1); // sum() function calls itself
else
return num;
}

Output

Enter a positive integer:3

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.

Call by value and Call by reference in C

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

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 = 10, b = 20

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.

Consider the following example for the call by reference.

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
Difference between call by value and call by reference in c

No. Call by value Call by reference

1 A copy of the value is An address of value is passed into the function


passed into the function

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

Example: Factorial of a Number


#include <stdio.h>
int main()
{
int n, i;
unsigned long long factorial = 1;

printf("Enter an integer: ");


scanf("%d",&n);
// show error if the user enters a negative integer
if (n < 0)
printf("Error! Factorial of a negative number doesn't exist.");

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

Example: Factorial of a Number Using Recursion


#include <stdio.h>
long int multiplyNumbers(int n);

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

Enter a positive integer: 6

Factorial of 6 = 720

Suppose the user entered 6.

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.

When the value of n is less than 1, there is no recursive call.

Example #1: Fibonacci Series up to n number of terms


#include <stdio.h>
int main()
{
int i, n, t1 = 0, t2 = 1, nextTerm;
printf("Enter the number of terms: ");
scanf("%d", &n);

printf("Fibonacci Series: ");

for (i = 1; i <= n; ++i)


{
printf("%d, ", t1);
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
return 0;
}

Output

Enter the number of terms: 10

Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,

Example #2: Fibonacci Sequence Up to a Certain Number


#include <stdio.h>
int main()
{
int t1 = 0, t2 = 1, nextTerm = 0, n;

printf("Enter a positive number: ");


scanf("%d", &n);

// displays the first two terms which is always 0 and 1


printf("Fibonacci Series: %d, %d, ", t1, t2);

nextTerm = t1 + t2;

while(nextTerm <= n)
{
printf("%d, ",nextTerm);
t1 = t2;
t2 = nextTerm;
nextTerm = t1 + t2;
}

return 0;
}

Output

Enter a positive integer: 100

Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,

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

1 /* C Program to implement Ackermann function using recursion */

3 #include<stdio.h>

4 int A(int m, int n);

6 main()

7 {

8 int m,n;

9 printf("Enter two numbers :: \n");

10 scanf("%d%d",&m,&n);

11 printf("\nOUTPUT :: %d\n",A(m,n));
12 }

13

14 int A(int m, int n)

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

1 ************* OUTPUT **************


2

4 ************* FIRST RUN ***********

7 Enter two numbers ::

8 1

9 0

10

11 OUTPUT :: 2

12

13

14 ************* SECOND RUN ***********

15

16 Enter two numbers ::

17 0

18 5

19
20 OUTPUT :: 6

You might also like