C-Programming Fundamentals

Download as pdf or txt
Download as pdf or txt
You are on page 1of 179

KONERU LAKSHMAIAH EDUCATION FOUNDATION

(Deemed to be University estd, u/s, 3 of the UGC Act, 1956)


(NAAC Accredited “A++” Grade University)
Green Fields, Guntur District, A.P., India – 522502

Department of School of Competitive Coding

Introduction to C Program:
C language Tutorial with programming approach for beginners and
professionals helps you to understand the C language tutorial easily. Our C
tutorial explains each topic with programs.

The C Language is developed by Dennis Ritchie for creating system


applications that directly interact with the hardware devices such as drivers,
kernels, etc.

C programming is considered as the base for other programming languages, that


is why it is known as mother language.

It can be defined by the following ways:

1. Mother language
2. System programming language
3. Procedure-oriented programming language
4. Structured programming language
5. Mid-level programming language

1) C as a mother language

C language is considered as the mother language of all the modern


programming languages because most of the compilers, JVMs, Kernels, etc. are
written in C language, and most of the programming languages follow C syntax,
for example, C++, Java, C#, etc.

It provides the core concepts like the array, strings, functions, file handling, etc.
that are being used in many languages like C++, Java, C#, etc.

2) C as a system programming language

A system programming language is used to create system software. C language


is a system programming language because it can be used to do low-level
programming (for example driver and kernel). It is generally used to create
hardware devices, OS, drivers, kernels, etc. For example, Linux kernel is
written in C.

It can't be used for internet programming like Java, .Net, PHP, etc.

3) C as a procedural language

A procedure is known as a function, method, routine, subroutine, etc. A


procedural language specifies a series of steps for the program to solve the
problem.

A procedural language breaks the program into functions, data structures, etc.

C is a procedural language. In C, variables and function prototypes must be


declared before being used.

4) C as a structured programming language

A structured programming language is a subset of the procedural


language. Structure means to break a program into parts or blocks so that it may
be easy to understand.

In the C language, we break the program into parts using functions. It makes the
program easier to understand and modify.

5) C as a mid-level programming language

C is considered as a middle-level language because it supports the feature of


both low-level and high-level languages. C language program is converted into
assembly code, it supports pointer arithmetic (low-level), but it is machine
independent (a feature of high-level).

A Low-level language is specific to one machine, i.e., machine dependent. It is


machine dependent, fast to run. But it is not easy to understand.

A High-Level language is not specific to one machine, i.e., machine


independent. It is easy to understand.
Environment setup:
There are many compilers available for c and c++. You need to download any
one. Here, we are going to use Turbo C++. It will work for both C and C++. To
install the Turbo C software, you need to follow following steps.

1. Download Turbo C++


2. Create turboc directory inside c drive and extract the tc3.zip inside
c:\turboc
3. Double click on install.exe file
4. Click on the tc application file located inside c:\TC\BIN to write the c
program

1) Download Turbo C++ software

You can download turbo c++ from many sites. download Turbo c++

2) Create turboc directory in c drive and extract the tc3.zip

Now, you need to create a new directory turboc inside the c: drive. Now extract
the tc3.zip file in c:\truboc directory.

3) Double click on the install.exe file and follow steps

Now, click on the install icon located inside the c:\turboc


It will ask you to install c or not, press enter to install.

Change your drive to c, press c.

Press enter, it will look inside the c:\turboc directory for the required files.

Select Start installation by the down arrow key then press enter.

Now C is installed, press enter to read documentation or close the software.

4) Click on the tc application located inside c:\TC\BIN


Now double click on the tc icon located in c:\TC\BIN directory to write the c
program.

In windows 7 or window 8, it will show a dialog block to ignore and close the
application because fullscreen mode is not supported. Click on Ignore button.

Now it will showing following console.


Structure of a C program:
The structure of a C program means the specific structure to start the
programming in the C language. Without a proper structure, it becomes difficult
to analyze the problem and the solution. It also gives us a reference to write
more complex programs.

Let's first discuss about C programming.

C programming

C language combines the power of a low-level language and a high-level


language. The low-level languages are used for system programming, while the
high-level languages are used for application programming. It is because such
languages are flexible and easy to use. Hence, C language is a widely used
computer language.

It supports various operators, constructors, data structures, and loop constructs.


The features of C programming make it possible to use the language for system
programming, development of interpreters, compilers, operating systems,
graphics, general utilities, etc. C is also used to write other applications, such
as databases, compilers, word processors, and spreadsheets.

The essential features of a C program are as follows:

Pointers: it allows reference to a memory location by the name assigned to it in


a program.

Memory allocation: At the time of definition, memory is assigned to a variable


name, allowing dynamic allocation of the memory. It means that the program
itself can request the operating system to release memory for use at the
execution time.

Recursion: When a function calls itself, it is known as recursion.

Bit-manipulation: It refers to the manipulation of data in its lowest form. It is


also known as bits. The computer stores the information in binary format (0 and
1).

Let's start with the importance of specifying the structure of a C program.


Importance of structure of a C program

Sometimes, when we begin with a new programming language, we are not


aware about the basic structure of a program. The sections of a program usually
get shuffled and the chance of omission of error rises. The structure of a
language gives us a basic idea of the order of the sections in a program. We get
to know when and where to use a particular statement, variable, function,
curly braces, parentheses, etc. It also increases our interest in that
programming language.

Thus, the structure helps us analyze the format to write a program for the least
errors. It gives better clarity and the concept of a program.

Here, we will discuss the sections of a C program, some practical examples


with explanations, steps to compile and execute a C program.

Let's start.

Sections of a C program
The sections of a C program are listed below:

1. Documentation section
2. Preprocessor section
3. Definition section
4. Global declaration
5. Main function
6. User defined functions

Let's discuss it in detail.

Documentation section

It includes the statement specified at the beginning of a program, such as a


program's name, date, description, and title. It is represented as:

1. //name of a program

Or

1. /*
2. Overview of the code
3. .
4. */

Both methods work as the document section in a program. It provides an


overview of the program. Anything written inside will be considered a part of
the documentation section and will not interfere with the specified code.

Preprocessor section

The preprocessor section contains all the header files used in a program. It
informs the system to link the header files to the system libraries. It is given by:

1. #include<stdio.h>
2. #include<conio.h>

The #include statement includes the specific file as a part of a function at the
time of the compilation. Thus, the contents of the included file are compiled
along with the function being compiled. The #include<stdio.h> consists of the
contents of the standard input output files, which contains the definition of
stdin, stdout, and stderr. Whenever the definitions stdin, stdout, and stderr are
used in a function, the statement #include<stdio.h> need to be used.

There are various header files available for different purposes. For example, #
include <math.h>. It is used for mathematic functions in a program.

Define section

The define section comprises of different constants declared using the define
keyword. It is given by:

1. #define a = 2
Global declaration

The global section comprises of all the global declarations in the program. It is
given by:

1. float num = 2.54;


2. int a = 5;
3. char ch ='z';

The size of the above global variables is listed as follows:

char = 1 byte

float = 4 bytes

int = 4 bytes

We can also declare user defined functions in the global variable section.

Main function

main() is the first function to be executed by the computer. It is necessary for a


code to include the main(). It is like any other function available in the C
library. Parenthesis () are used for passing parameters (if any) to a function.
The main function is declared as:

 main()

We can also use int or main with the main (). The void main() specifies that the
program will not return any value. The int main() specifies that the program can
return integer type data.int main()

Or

 void main()

Main function is further categorized into local declarations,


statements, and expressions.

Local declarations

The variable that is declared inside a given function or block refers to as local
declarations.

1. main()
2. {
3. int i = 2;
4. i++;
5. }

Statements

The statements refers to if, else, while, do, for, etc. used in a program within
the main function.

Expressions

An expression is a type of formula where operands are linked with each other
by the use of operators. It is given by:

1. a - b;
2. a +b;
User defined functions

The user defined functions specified the functions specified as per the
requirements of the user. For example, color(), sum(), division(), etc.

The program (basic or advance) follows the same sections as listed above.

Return function is generally the last section of a code. But, it is not necessary
to include. It is used when we want to return a value. The return function returns
a value when the return type other than the void is specified with the function.

Return type ends the execution of the function. It further returns control to the
specified calling function. It is given by:

 return;

Or

 return expression ;

For example,

return 0;

Examples

Let's begin with a simple program in C language.

Example 1: To find the sum of two numbers given by the user

It is given by:

/* Sum of the two It is the comment section. Any statement described in it is not
numbers */ considered as a code. It is a part of the description section in a code.
The comment line is optional. It can be in a separate line or part of an
executable line.

#include<stdio.h> It is the standard input-output header file. It is a command of the


preprocessor section.
int main() main() is the first function to be executed in every program. We have
used int with the main() in order to return an integer value.

{… The curly braces mark the beginning and end of a function. It is


} mandatory in all the functions.

printf() The printf() prints text on the screen. It is a function for displaying
constant or variables data. Here, 'Enter two numbers to be added' is the
parameter passed to it.

scanf() It reads data from the standard input stream and writes the result into the
specified arguments.

sum = a + b The addition of the specified two numbers will be passed to the sum
parameter in the output.

return 0 A program can also run without a return 0 function. It simply states that
a program is free from error and can be successfully exited.

1. /* Sum of two numbers */


2. #include<stdio.h>
3. int main()
4. {
5. int a, b, sum;
6. printf("Enter two numbers to be added ");
7. scanf("%d %d", &a, &b);
8. // calculating sum
9. sum = a + b;
10. printf("%d + %d = %d", a, b, sum);
11. return 0; // return the integer value in the sum
12.}
Output

Compile and execution of a C program

Here, we will discuss the method to compile and run the C program with the
help of the command prompt.

The steps involved in a complete program execution are as follows:

1. Create a program
2. Compile a program
3. Run or execute a program
4. Output of the program

Create a program

It refers to the code created in any text editor. We can also compile and run the
C code in any software, such as Visual studio.

Compile a program

If refers to the process of checking the errors in the code. The computer displays
all the errors (if any) found in our specified C code. We can make further
changes to correct those errors.

Run or execute a program

The next step is the run or execution part. A program is assembled and linked
without any error. The computer performs different operations, such as
decoding, ALU operations to run a program.

Output of the program

It is the last part of the program where the output of the specified code is
produced as the result.
But, where to write a program and how to open a command prompt to run that
program. Do not worry; it is very easy to do all these steps. Let's start with the
step to compile and run a C program.

Step to compile and run a C program

We need first to ensure that the gcc compiler is already present on our PC or
not. If it is not installed, we need first to install the gcc compiler. We can also
try other methods to run a C program. But here, we have used the gcc compiler.

Step: 1 - gcc complier installation

We can directly install the latest gcc complier through the


link: https://jmeubank.github.io/tdm-gcc/

Complete all the steps during the installation till the process gets completed.

Step: 2 - creating a C program

Create a C program using the simple text editor. Here, we have used notepad. It
is shown below:

1. #include<stdio.h>
2. main()
3. {
4. printf("Hello, Welcome to the C programming \n");
5. return;
6. }

Now, save the file in any directory with the extension (.c). For example, we
have saved the file with the name 'welcome.c' on the desktop.

Step: 3 - Opening the command prompt

Open the cmd or command prompt on our computer. We can simply type cmd
on the search or the run option. The Command prompt will appear.

Step: 4 - rechecking the gcc complier

After the command prompt opens, type 'gcc -v' and press Enter. It will appear
as the image shown below:
It shows that gcc is successfully installed on our PC.

Step: 5 - go to the source directory

We now need to specify the source directory on the cmd. Type 'cd space source
directory' and press Enter. Since, we have saved our text editor file on the
desktop, so we will specify the source directory as desktop. It is given by:

 cd desktop
Step: 6 - compile the source code

Run the command 'gcc space full name of the file saved with the extension (.c)'
and press Enter, as shown below:

 gcc welcome.c

If there is any error in our file, it will appear. Otherwise, move on to the step 7.
Step: 7 - Compile the source code

The executable file is not yet named because we have not told the compiler to
perform any such task. So, we will first name the executable file by running the
command 'gcc space -o space (name of executable file) space (name of the
original file with the extension)' and press Enter. It is given by:

 gcc -o hello welcome.c

Here, we have given the executable name as hello. We can define the name as
per our convenience.

Step: 8 - Run the program

It is the last step to run a program. We will run the program in the command
prompt only. Here, we will type the name of the executable file without any
extension. The executable name will be the same as specified in step 7. It is
given by:

 hello

Press Enter. The output will appear on the command prompt, as shown below:

Similarly, we can run multiple C programs using the same steps, as discussed
above.
C Program

In this tutorial, all C programs are given with C compiler so that you can
quickly change the C program code.

File: main.c

1. #include <stdio.h>
2. int main() {
3. printf("Hello C Programming\n");
4. return 0;
5. }

Tokens in C:
Tokens in C is the most important element to be used in creating a program in
C. We can define the token as the smallest individual element in C. For
`example, we cannot create a sentence without using words; similarly, we
cannot create a program in C without using tokens in C. Therefore, we can say
that tokens in C is the building block or the basic component for creating
a program in C language.

Classification of tokens in C

Tokens in C language can be divided into the following categories:

o Keywords in C
o Identifiers in C

Let's understand each token one by one.

Keywords in C:
Keywords in C can be defined as the pre-defined or the reserved words having
its own importance, and each keyword has its own functionality. Since
keywords are the pre-defined words used by the compiler, so they cannot be
used as the variable names. If the keywords are used as the variable names, it
means that we are assigning a different meaning to the keyword, which is not
allowed. C language supports 32 keywords given below:
Auto double int Struct

Break else long Switch

Case enum register Typedef

Char extern return Union

Const float short Unsigned

Continue for signed Void

Default goto Sizeof Volatile

Do If Static While

Identifiers in C:
Identifiers in C are used for naming variables, functions, arrays, structures, etc.
Identifiers in C are the user-defined words. It can be composed of uppercase
letters, lowercase letters, underscore, or digits, but the starting letter should be
either an underscore or an alphabet. Identifiers cannot be used as keywords.
Rules for constructing identifiers in C are given below:

o The first character of an identifier should be either an alphabet or an


underscore, and then it can be followed by any of the character, digit, or
underscore.
o It should not begin with any numerical digit.
o In identifiers, both uppercase and lowercase letters are distinct. Therefore,
we can say that identifiers are case sensitive.
o Commas or blank spaces cannot be specified within an identifier.
o Keywords cannot be represented as an identifier.
o The length of the identifiers should not be more than 31 characters.
o Identifiers should be written in such a way that it is meaningful, short,
and easy to read.
Data Types:
In C, data types specify the type of data that a variable can hold. The basic data types in C are:

int: Integer data type, used for whole numbers.


int age = 25;
short int: Typically 16 bits.
int: Minimum 16 bits, usually 32 bits.
long int: Minimum 32 bits.
long long int: Minimum 64 bits.
long long int bigNumber = 1234567890123456LL;

float: Floa ng-point data type, used for numbers with decimal points.
float price = 19.99;
double: Double-precision floa ng-point data type, provides more precision than float.
double pi = 3.14159265359;
float: 32-bit floa ng-point.
double: 64-bit double-precision floa ng-point.
long double: Extended precision.
double price = 99.99;

char: Character data type, used for single characters.


char grade = 'A';
char: Typically 8 bits.
signed char: Can represent both posi ve and nega ve values.
unsigned char: Represents only non-nega ve values.

_Bool: Boolean data type, represents true or false values.


_Bool isPassed = 1; // true

void: Represents the absence of a type or no value.


void func onWithoutReturnValue() {
// Some code here

Variables:
Variables are used to store and manipulate data in a program. They must be declared before
use, specifying their data type.
int main() {
int x; // Declara on

x = 10; // Ini aliza on


return 0;
}

Constants:
Constants are values that do not change during the execu on of a program. They can be
defined using the const keyword.
const float PI = 3.1415;

Literals:
Literals are constant values that are used directly in the program. For example:
Integer literals: 10, 20
Floa ng-point literals: 3.14, 2.0
Character literals: 'A', 'b'

Storage Classes:
Storage classes in C determine the scope and life me of variables. The main storage classes
are:
auto: The default storage class for local variables. The variable is automa cally created and
destroyed.
register: Similar to auto, but suggests the compiler to store the variable in a register for faster
access.
sta c: The variable retains its value between func on calls. It has a file scope if declared
outside a func on.
extern: Informs the compiler that the variable is defined elsewhere. Used for global variables.

Operators:
Operators in C are symbols that perform opera ons on variables and values. They can be
categorized as:

Arithme c Operators: +, -, *, /, %
int result = 10 + 5; // result is 15

Rela onal Operators: ==, !=, <, >, <=, >=


int x = 5, y = 10;
if (x < y) {
// Code executes if x is less than y
}

Logical Operators: && (AND), || (OR), ! (NOT)


int a = 1, b = 0;
if (a && b) {

// Code executes if both a and b are true


}

Assignment Operators: =, +=, -=, *=, /=


x += 5; // Equivalent to x = x + 5

Increment/Decrement Operators: ++, --


int count = 10;
count++; // Increment by 1
Bitwise Operators: &, |, ^, <<, >>
int a = 5, b = 3;
int result = a & b; // Bitwise AND

Condi onal (Ternary) Operator: condi on ? expr1 : expr2


int max = (a > b) ? a : b; // If a is greater than b, max is a; otherwise, max is b.

sizeof Operator: Returns the size of a data type or object.


int size = sizeof(int); // size is the size of an integer in bytes

Programming ques ons:


1. Write a program to swap the values of two variables without using a third variable.
#include <stdio.h>

int main() {
int a = 5, b = 10;
prin ("Before Swap: a = %d, b = %d\n", a, b);

a = a + b;
b = a - b;
a = a - b;

prin ("A er Swap: a = %d, b = %d\n", a, b);


return 0;
}

2. Write a program to check if a given integer is even or odd


#include <stdio.h>

int main() {
int num;
prin ("Enter an integer: ");
scanf("%d", &num);

if (num % 2 == 0)
prin ("%d is even.\n", num);
else
prin ("%d is odd.\n", num);
return 0;
}

3. Write a program to calculate the area of a circle using the radius.


#include <stdio.h>

int main() {
float radius, area;
prin ("Enter the radius of the circle: ");
scanf("%f", &radius);

area = 3.14 * radius * radius;

prin ("Area of the circle: %f\n", area);


return 0;
}

4. Declare a constant named PI and a variable named radius. Calculate the circumference
using the formula: circumference = 2 * PI * radius.
#include <stdio.h>

int main() {
const float PI = 3.14;
float radius, circumference;

prin ("Enter the radius of the circle: ");


scanf("%f", &radius);

circumference = 2 * PI * radius;

prin ("Circumference of the circle: %f\n", circumference);


return 0;
}

5. Write a program to perform bitwise AND, OR, and XOR opera ons on two integers.
#include <stdio.h>

int main() {
int a = 12, b = 25;

prin ("Bitwise AND: %d\n", a & b);


prin ("Bitwise OR: %d\n", a | b);
prin ("Bitwise XOR: %d\n", a ^ b);
return 0;
}

6. Write a program to check whether a given year is a leap year or not.


#include <stdio.h>

int main() {
int year;
prin ("Enter a year: ");
scanf("%d", &year);

if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))


prin ("%d is a leap year.\n", year);
else
prin ("%d is not a leap year.\n", year);

return 0;
}

7. Write a program to calculate the sum of digits of a posi ve integer.


#include <stdio.h>

int main() {
int num, sum = 0;
prin ("Enter a posi ve integer: ");
scanf("%d", &num);

while (num > 0) {


sum += num % 10;
num /= 10;
}

prin ("Sum of digits: %d\n", sum);


return 0;
}

8. Write a program to calculate the factorial of a given number.


#include <stdio.h>

int factorial(int n) {
if (n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1);
}

int main() {
int num;
prin ("Enter a number: ");
scanf("%d", &num);

prin ("Factorial of %d: %d\n", num, factorial(num));


return 0;
}

9. Write a program that ini alizes an array of integers and finds the sum and average of
its elements.
#include <stdio.h>

int main() {
int numbers[] = {2, 4, 6, 8, 10};
int sum = 0, size = sizeof(numbers) / sizeof(numbers[0]);

for (int i = 0; i < size; ++i) {


sum += numbers[i];
}

float average = (float)sum / size;

prin ("Sum: %d\n", sum);


prin ("Average: %f\n", average);

return 0;
}

10. Write a program to simulate a basic login system using logical operators.
#include <stdio.h>

int main() {
char username[] = "user123";
char password[] = "pass456";

char inputUsername[20];
char inputPassword[20];

prin ("Enter username: ");


scanf("%s", inputUsername);
prin ("Enter password: ");
scanf("%s", inputPassword);

if (strcmp(username, inputUsername) == 0 && strcmp(password, inputPassword) ==


0)
prin ("Login successful!\n");
else
prin ("Login failed!\n");

return 0;
}

11. Write a program to find the maximum of two numbers using the condi onal (ternary)
operator.
#include <stdio.h>

int main() {
int a, b;
prin ("Enter two numbers: ");
scanf("%d %d", &a, &b);

int max = (a > b) ? a : b;

prin ("Maximum: %d\n", max);


return 0;
}

12. Write a program to find the length of a string without using the `strlen` func on.
#include <stdio.h>

int stringLength(char str[]) {


int length = 0;
while (str[length] != '\0') {
length++;
}
return length;
}

int main() {
char text[] = "Hello, World!";
prin ("Length of the string: %d\n", stringLength(text));
return 0;
}
13. Write a program to le -shi and right-shi an integer by a specified number of
posi ons.
#include <stdio.h>

int main() {
int num, shi ;

prin ("Enter an integer: ");


scanf("%d", &num);

prin ("Enter the number of posi ons to shi : ");


scanf("%d", &shi );

prin ("Le -shi ed result: %d\n", num << shi );


prin ("Right-shi ed result: %d\n", num >> shi );

return 0;
}

14. Define a structure called `Person` with a ributes `name` and `age`. Create an array of
persons and print their details.
#include <stdio.h>

struct Person {
char name[50];
int age;
};

int main() {
struct Person people[3] = {{"Alice", 25}, {"Bob", 30}, {"Charlie", 22}};

for (int i = 0; i < 3; ++i) {


prin ("Person %d: %s, %d years old\n", i + 1, people[i].name, people[i].age);
}

return 0;
}

15. Create a union called `Value` that can store either an integer or a float. Write a
program to demonstrate its usage.
#include <stdio.h>

union Value {
int intValue;
float floatValue;
};

int main() {
union Value data;
data.intValue = 10;

prin ("Integer Value: %d\n", data.intValue);

data.floatValue = 3.14;
prin ("Float Value: %f\n", data.floatValue);

return 0;
}
Decision Making (if, if - else, else if, Switch statements)
C is consider as a structure programming language. One of the reason for this is having
various program control structures.
C process the decision making capabilities and supports the statements known as control
statements.
There are 3 types of control statements supported by C…
1. Condition control statements
2. Un condition control statements
3. Loop control statements.

Conditional Statements in C programming are used to make decisions based on the


conditions. These conditions are specified by a set of conditional statements having boolean
expressions which are evaluated to a boolean value true or false. This process is called decision
making or Conditional Execution in ‘C’.

1. Condition control statements:- C supports five types of condition control statements.


 Simple if statement
 If else statement
 Nested if else statement
 If Else if ladder
 Switch statement

i. Simple if statement:- It is a decision making statements and is used to control the


flow of execution.
ii.
Syntax:- if (expression)
{
Statements;

Entry

False
Expr
True

Statements

Next Statements

If the expression is true, then the statement block will be executed and the statement block
will be executed and the control transfer to the next statement. Otherwise, if the expression
is false then the control directly goes to the next statement.
Example 1:
#include<stdio.h>
int main()
{
int num1=15;
int num2=29;
if(num1<num2) //test-condition
{
printf("num1 is smaller than num2");
}
return 0;
}

Output

num1 is smaller than num2

Note:- In any control statement the statement block contains only a single statement, braces are
not necessary.

Example 2:
Write a program to find the max value of given three numbers using simple if statements.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,max;
clrscr();
printf("Enter any three numbers:");
scanf("%d%d%d",&a,&b,&c);
max=a;
if(max<b)
max=b;
if(max<c)
max=c;
printf("Max value:%d",max);
getch();

Example 3:
Write a program to enter any date in date format and display given date.
#include<stdio.h>
#include<conio.h>
void main()
{
int d,m,y;
clrscr();
printf("Enter any date (dd-mm-yyyy):");
scanf("%d-%d-%d",&d,&m,&y);
printf("Given date:%.2d-%.2d-%d",d,m,y);
getch();
}

ii. If else statements:- It is an extension of simple if statement. if-else Statement in C allows


two-way selection. If the given condition is true, then program control goes inside the if block
and executes the Statement.

The condition is false, then program control goes inside the else block and executes the
corresponding Statement.

Syntax: -
if(expression)
{
statement-1;
}
else
{
Statement-2;
}

Example 4:
#include<stdio.h>
int main()
{
int num=57;
if(num<20)
{
printf("The value is less than 20");
}
else
{
printf("The value is greater than 20");
}
return 0;
}

Output

The value is greater than 20

Example 5:

Write a program to check whether the given no. is even or odd.


#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf("Enter any number:");
scanf("%d",&n);
if(n%2==0)
printf("Given number is even");
else
printf("Given number is odd");

getch();

Example 6:

#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

iii.Nested if statement:- Using a if statement within another if is called nested if statement. If


a series of decisions are involved we use nested if statement.
Syntax:- if(expression-1)
{
If(expression-2)
{
------------
------------
{
Statements;
}
}
}
Syntax-2
if(expression-1)
{
if(expression-2)
{
statements-1;
}
else
{
statements-2;
}
}
else
{
if(expression-3)
{
statements-3;
}
else
{
statements-4;
}
}

Example 7:
Write a program to find the maximum value of given 3 no's using nested if.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,max;

clrscr();

printf("Enter any three numbers:");

scanf("%d%d%d",&a,&b,&c);
if(a>b)
{
if(a>c)
max=a;
else
max=c;
}
else
{
if(b>c)
max=b;
else
max=c;
}
printf("Max Value for given 3 numbers:%d",max);
getch();

Example 8:

#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

Example 9:

Write a program to accept any character and check whether the given character is vowel or
consonant or not an alphabet.

#include<stdio.h>
#include<conio.h>
void main()
{

char ch;

clrscr();
printf("Enter any character:");
scanf("%c",&ch);
if((ch>=65 && ch<=90) || (ch>=97 && ch<=122))
{
if(ch=='A' || ch=='a' || ch=='E'|| ch=='e' || ch=='I' || ch=='i' || ch=='O' || ch=='o' || ch=='U' ||
ch=='u')
printf("Given character is vowel");
else
printf("Given character is consonant");
}
else
printf("Given character is not an alphabet");
getch();

iv. If else if ladder:- It is also used for a serried of decisions are involved.
Syntax:-if(expression-1)
{
stataement-1;
}
else if (expression-2)
{
statements-2;
}
--------------
--------------
--------------
else if (expression-n)
{
statements-n;
}
else
{
statements;
}
In this statement expression are evaluated top to bottom. If the condition true, the statements
associated that blocks is executed and the control transfer to the next statement. When all
expressions are false, then the final else block statements will be executed.

Example 10:

Write a program to accept any character and check whether the given character is alphabet or
digit or a special character.
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
printf("Enter any character:");
scanf("%c",&ch);
if((ch>=65 && ch<=90) || (ch>=97 && ch<=122))
printf("Given character is alphabet");
else if(ch>=48 && ch<=57)
printf("Given character is digit");
else
printf("Given character is a special character");
getch();
}

Example 11:

#include <stdio.h>

int main()
{
int num1, num2;
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
//checks if the two integers are equal.
if(num1 == num2)
{
printf("Result is %d = %d",num1,num2);
}
//checks if number1 is greater than number2.
else if (num1 > num2)
{
printf("Result is %d > %d", num1, num2);
}
//checks if both conditions are false
else
{
printf("Result: %d < %d",num1, num2);
}
return 0;
}
Output 1

Enter two numbers: 10 20


Result: 10 < 20

Output 2

Enter two numbers: 10 10


Result is 10 = 10

Output 3

Enter two numbers: 20 12


Result is 20 > 12

Example 12:

#include<stdio.h>
int main()
{
int temperature = 35;
if(marks>40)
{
printf("Extremely hot");
}
else if(marks>30)
{
printf("Mildly hot");
}
else if(marks>20)
{
printf("Comfortable");
}
else
{
printf("Cold");
}
return 0;
}

Output

Mildly hot

Example 13:

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
V. Switch Statement:- It is a multi way conditional statement used in c language. It is mainly
used in situations where there is need to pick one alternate among many alternates.
Syntax:-
Switch (expression or variable)
{
Case value 1;
Statement1;
Break;
----------------------

----------------------
Case value n;
Statements n;
Break;
Default;
Default statement;
}
The switch statement tests the value of the given variable or expression against a list of case
values and
when a match is found, a block of statements associated that case is executed. Otherwise the
default block
statements will be executed.
Break:- It is unconditional control statement and is used to terminate a switch statement.
Syntax :- break;
Note:- i) In switch statement the variable or expression is an integral value.(int & char).
ii) It cannot pass string and floating values.
iii) In switch statement the default block is optional.

Example 14:
Write a program to test all arithmetic operations using switch statement
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,opt;
clrscr();
printf("Enter any two numbers:");
scanf("%d%d",&a,&b);
printf("1.Addition\n2.Subtraction\n3.Multiplication\n4.Division\n5.Enter Option");
scanf("%d",&opt);
switch(opt)
{
case1 :
printf("\nAddition %d and %d is %d",a,b,a+b);
break;
case2 :
printf("\nSubtraction %d and %d is %d",a,b,a-b);
break;
case3 :
printf("\nMultiplication %d and %d is %d",a,b,a*b);
break;
case4 :
printf("\nDivision %d and %d is %d",a,b,a-b);
break;
case5 :
printf("\nModulus %d and %d is %d",a,b,a%b);
break;
default :
printf("\nInvalid Region:");
}
getch();
}
Example 15:

#include <stdio.h>
int main() {
int num = 8;
switch (num) {
case 7:
printf("Value is 7");
break;
case 8:
printf("Value is 8");
break;
case 9:
printf("Value is 9");
break;
default:
printf("Out of range");
break;
}
return 0;
}

Output
Value is 8

lets write the same code without the break statement.

#include <stdio.h>
int main() {
int num = 8;
switch (num) {
case 7:
printf("Value is 7");
case 8:
printf("Value is 8");
case 9:
printf("Value is 9");
default:
printf("Out of range");
}
return 0;
}

Output

Value is 8

Value is 9

Out of range
Functions
In c, we can divide a large program into the basic building blocks known as function. The
function contains the set of programming statements enclosed by {}. A function can be called
multiple times to provide reusability and modularity to the C program. Every ‘C’ program has at
least one function which is the main function, but a program can have any number of functions.
The main () function in C is a starting point of a program.

Advantages of Functions in C
Functions in C is a highly useful feature of C with many advantages as mentioned below:
1. The function can reduce the repetition of the same statements in the program.
2. The function makes code readable by providing modularity to our program.
3. There is no fixed number of calling functions it can be called as many times as you
want.
4. The function reduces the size of the program.
5. Once the function is declared you can just use it without thinking about the internal
working of the function.

Disadvantages of Functions in C
The following are the major disadvantages of functions in C:
1. Cannot return multiple values.
2. Memory and time overhead due to stack frame allocation and transfer of program
control.

Function Types

In ‘C’ programming, functions are divided into two types:


1. Library functions
2. User-defined functions
The difference between the library and user-defined functions in C is that we do not need to
write a code for a library function. It is already present inside the header file which we always
include at the beginning of a program. You just have to type the name of a function and use it
along with the proper syntax. The printf, scanf are the examples of a library function.
Whereas, a user-defined function is a type of function in which we have to write a body of a
function and call the function whenever we require the function to perform some operation in our
program.
A user-defined function in C is always written by the user, but later it can be a part of ‘C’ library.
C programming functions are divided into three activities such as,
1. Function declaration
2. Function definition
3. Function call
 Function Declaration
In a function declaration, we just specify the name of a function that we are going to use in our
program like a variable declaration. We cannot use a function unless it is declared in a program.
A function declaration is also called “Function prototype.”
The function declarations (called prototype) are usually done above the main () function and take
the general form:

return_data_type function_name (data_type arguments);

The return_data_type: is the data type of the value function returned back to the calling
statement.
The function_name: is followed by parentheses
Arguments names with their data type declarations optionally are placed inside the parentheses.
We consider the following program that shows how to declare a cube function to calculate the
cube value of an integer variable
#include <stdio.h>
/*Function declaration*/
int add(int a,b);
/*End of Function declaration*/
Note: A function does not necessarily return a value. In this case, the keyword void is used.
For example, the output_message function declaration indicates that the function does not return
a value:
void output_message();

 Function Definition
Function definition means just writing the body of a function. A body of a function consists of
statements which are going to perform a specific task. A function body consists of a single or a
block of statements. It is also a mandatory part of a function.
int add(int a,int b) //function body
{
int c;
c=a+b;
return c;
}

 Function call
A function call means calling a function whenever it is required in a program. Whenever we call
a function, it performs an operation for which it was designed. A function call is an optional part
of a program.
result = add(4,5);

Here, is th complete code:


#include <stdio.h>
int add(int a, int b); //function declaration
int main()
{
int a=10,b=20;
int c=add(10,20); //function call
printf("Addition:%d\n",c);
getch();
}
int add(int a,int b) //function body
{
int c;
c=a+b;
return c;
}

 Function Arguments
A function’s arguments are used to receive the necessary values by the function call. They are
matched by position; the first argument is passed to the first parameter, the second to the second
parameter and so on.
By default, the arguments are passed by value in which a copy of data is given to the called
function. The actually passed variable will not change.
We consider the following program which demonstrates parameters passed by value:
int add (int x, int y);
int main() {
int a, b, result;
a = 5;
b = 10;
result = add(a, b);
printf("%d + %d\ = %d\n", a, b, result);
return 0;}
int add (int x, int y) {
x += y;
return(x);}
The program output is:
5 + 10 = 15
Note: The values of a and b were passed to add function were not changed because only its value
was passed into the parameter x.
While calling a function, there are two ways in which arguments can be passed to a function −
Sr.No. Call Type & Description
Call by value
This method copies the actual value of an argument into the formal parameter of the
1
function. In this case, changes made to the parameter inside the function have no
effect on the argument.
Call by reference
This method copies the address of an argument into the formal parameter. Inside the
2
function, the address is used to access the actual argument used in the call. This
means that changes made to the parameter affect the argument.
By default, C uses call by value to pass arguments. In general, it means the code within a
function cannot alter the arguments used to call the function.
The call by value method of passing arguments to a function copies the actual value of an
argument into the formal parameter of the function. In this case, changes made to the parameter
inside the function have no effect on the argument.

By default, C programming uses call by value to pass arguments. In general, it means the code
within a function cannot alter the arguments used to call the function. Consider the function
swap() definition as follows.
#include <stdio.h>
/* function declaration */
void swap(int x, int y);
int main () {
/* local variable definition */
int a = 100;
int b = 200;
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
/* calling a function to swap the values */
swap(a, b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
return 0;
}
void swap(int x, int y) {
int temp;
temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put temp into y */
return;
}

it will produce the following result −


Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 100
After swap, value of b : 200
It shows that there are no changes in the values, though they had been changed inside the
function.

The call by reference method of passing arguments to a function copies the address of an
argument into the formal parameter. Inside the function, the address is used to access the actual
argument used in the call. It means the changes made to the parameter affect the passed
argument.
To pass a value by reference, argument pointers are passed to the functions just like any other
value. So accordingly you need to declare the function parameters as pointer types as in the
following function swap(), which exchanges the values of the two integer variables pointed to,
by their arguments.
Call the function swap() by passing values by reference as in the following example −
#include <stdio.h>
int main () {
/* local variable definition */
int a = 100;
int b = 200;
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
/* calling a function to swap the values */
swap(&a, &b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
return 0;
}
void swap(int *x, int *y) {
int temp;
temp = *x; /* save the value of x */
*x = *y; /* put y into x */
*y = temp; /* put temp into y */
return;
}

produce the following result −

Before swap, value of a : 100


Before swap, value of b : 200
After swap, value of a : 200
After swap, value of b : 100
It shows that the change has reflected outside the function as well, unlike call by value where the
changes do not reflect outside the function.

 Return Value
A C function may or may not return a value from the function. If you don't have to return any
value from the function, use void for the return type.
Let's see a simple example of C function that doesn't return any value from the function.
Example without return value:
void test(){
printf("hi");
}

If you want to return any value from the function, you need to use any data type such as int, long,
char, etc. The return type depends on the value to be returned from the function.
Let's see a simple example of C function that returns int value from the function.
Example with return value:
int get(){
return 10;
}

In the above example, we have to return 10 as a value, so the return type is int. If you want to
return floating-point value (e.g., 10.2, 3.1, 54.5, etc), you need to use float as the return type of
the method.
float get(){
return 10.2;
}

Function categories
There are 4 types of functions:

1. Functions with arguments and return values


This function has arguments and returns a value:
#include <stdio.h>
void main()
{
int sub(int,int); //function with return value and arguments
int x=10,y=7;
int res = sub(x,y);
printf("x-y = %d",res);
}
int sub(int a,int b) //function with return value and arguments
{
return(a-b); // return value
}

2. Functions with arguments and without return values


This function has arguments, but it does not return a value:
#include <stdio.h>
int main()
{
void sum(float,float); //function with arguments and no return value
float x=10.56,y=7.22;
sum(x,y);
}
void sum(float a,float b) //function with arguments and no return value
{
float z = a+b;
printf("x + y = %f",z);
}

3. Functions without arguments and with return values


This function has no arguments, but it has a return value:
#include<stdio.h>
int main()
{
int sum();
int c = sum();
printf("Sum = %d",c);
}
int sum() //function with no arguments and return data type
{
int x=10,y=20,z=5;
printf("x = %d ; y = %d ; z = %d \n",x,y,z);
int sum = x+y+z;
return(sum);
}

4. Functions without arguments and without return values


This function has no arguments and no return value:
#include<stdio.h>
int main()
{
void sum();
sum();
}
void sum() //function with no arguments and return data type
{
int x=15,y=35,z=5;
printf("x = %d ; y = %d ; z = %d \n",x,y,z);
int sum = x+y+z;
printf("Sum = %d",sum);
}

Recursion:
Recursion is the technique of making a function call itself. This technique provides a way to
break complicated problems down into simple problems which are easier to solve.
Example
In the following example, recursion is used to add a range of numbers together by breaking it
down into the simple task of adding two numbers:

int sum(int k);


int main() {
int result = sum(10);
printf("%d", result);
return 0;
}
int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else {
return 0;
}
}
When the sum() function is called, it adds parameter k to the sum of all numbers smaller than k
and returns the result. When k becomes 0, the function just returns 0. When running, the program
follows these steps:

10 + sum(9)
10 + ( 9 + sum(8) )
10 + ( 9 + ( 8 + sum(7) ) )
...
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0
Since the function does not call itself when k is 0, the program stops there and returns the result.

Scope of variables:
By scope of a variable we mean which part of the code a variable is accessible (visible) to .A
variable can have many scopes in c let’s discuss some of them .
According to Scope, variables is divided into two categories:-

1. Local Variables
2. Global Variables

 Local Variable
Local variables are those variables that are defined in a small block of the program such as
function, control statement block etc. Such variables are used only by the same block.
A variable inside the function/block is a local variable. The default value of the Local variables
is ‘garbage value’.
Example :
#include<stdio.h>
int main()
{
int a,b,c; // local variables
a =10;
b = 30;
c = a + b;
printf("%d",c);
}
Here a, b, c all are local variables and can not be used by any other function except main. On
execution of the program the compiler prints 40

 Global variable
As oppose to local variable a global variable is out side every function and is accessible to all the
functions and the value of a global variable can be changed by any function. Global variables are
those variable whose scope is in whole program. These variables are defined at the beginning of
the program. The default value of ‘Global Variables’ is ‘0’.
#include<stdio.h>
int d=20; // global variable
int main()
{
int a,b,c; // local variables
a = 10;
b = 30;
d = d + 10;
c = a + b + d;
printf("%d",c);
return c;
}

On execution of the program the compiler prints 70 .

Exercise
 Program-1
C Program to Display Prime Numbers Between Intervals Using Function
#include <stdio.h>
int checkPrimeNumber(int n);
int main() {
int n1, n2, i, flag;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);
if (n1 > n2) {
n1 = n1 + n2;
n2 = n1 - n2;
n1 = n1 - n2;
}
printf("Prime numbers between %d and %d are: ", n1, n2);
for (i = n1 + 1; i < n2; ++i) {
flag = checkPrimeNumber(i);
if (flag == 1) {
printf("%d ", i);
}
}
return 0;
}
int checkPrimeNumber(int n) {
int j, flag = 1;
for (j = 2; j <= n / 2; ++j) {
if (n % j == 0) {
flag = 0;
break;
}
}
return flag;
}

 Program-2
C Program to Check Prime or Armstrong Number Using User-defined Function
#include <math.h>
#include <stdio.h>
int checkPrimeNumber(int n);
int checkArmstrongNumber(int n);
int main() {
int n, flag;
printf("Enter a positive integer: ");
scanf("%d", &n);
flag = checkPrimeNumber(n);
if (flag == 1)
printf("%d is a prime number.\n", n);
else
printf("%d is not a prime number.\n", n);
flag = checkArmstrongNumber(n);
if (flag == 1)
printf("%d is an Armstrong number.", n);
else
printf("%d is not an Armstrong number.", n);
return 0;
}
int checkPrimeNumber(int n) {
int i, flag = 1, squareRoot;
squareRoot = sqrt(n);
for (i = 2; i <= squareRoot; ++i) {
if (n % i == 0) {
flag = 0;
break;
}
}
return flag;
}
int checkArmstrongNumber(int num) {
int originalNum, remainder, n = 0, flag;
double result = 0.0;
for (originalNum = num; originalNum != 0; ++n) {
originalNum /= 10;
}
for (originalNum = num; originalNum != 0; originalNum /= 10) {
remainder = originalNum % 10;
result += pow(remainder, n);
}
if (round(result) == num)
flag = 1;
else
flag = 0;
return flag;
}

 Program-3
C Program to Check Whether a Number can be Expressed as Sum of Two Prime Numbers
#include <stdio.h>
int checkPrime(int n);
int main() {
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
for (i = 2; i <= n / 2; ++i) {
if (checkPrime(i) == 1) {
if (checkPrime(n - i) == 1) {
printf("%d = %d + %d\n", n, i, n - i);
flag = 1;
}
}
}
if (flag == 0)
printf("%d cannot be expressed as the sum of two prime numbers.", n);
return 0;
}
int checkPrime(int n) {
int i, isPrime = 1;
if (n == 0 || n == 1) {
isPrime = 0;
}
else {
for(i = 2; i <= n/2; ++i) {
if(n % i == 0) {
isPrime = 0;
break;
}
}
}
return isPrime;
}

 Program-4
C Program to Find the Sum of Natural Numbers using Recursion
#include <stdio.h>
int addNumbers(int n);
int main() {
int num;
printf("Enter a positive integer: ");
scanf("%d", &num);
printf("Sum = %d", addNumbers(num));
return 0;
}
int addNumbers(int n) {
if (n != 0)
return n + addNumbers(n - 1);
else
return n;
}

 Program-5
C Program to Find 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;
}

 Program-6
C Program to Find G.C.D Using Recursion
#include <stdio.h>
int hcf(int n1, int n2);
int main() {
int n1, n2;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);
printf("G.C.D of %d and %d is %d.", n1, n2, hcf(n1, n2));
return 0;
}
int hcf(int n1, int n2) {
if (n2 != 0)
return hcf(n2, n1 % n2);
else
return n1;
}

 Program-7
C Program to Reverse a Sentence Using Recursion
#include <stdio.h>
void reverseSentence();
int main() {
printf("Enter a sentence: ");
reverseSentence();
return 0;
}
void reverseSentence() {
char c;
scanf("%c", &c);
if (c != '\n') {
reverseSentence();
printf("%c", c);
}
}

 Program-8
C program to calculate the power using recursion
#include <stdio.h>
int power(int n1, int n2);
int main() {
int base, a, result;
printf("Enter base number: ");
scanf("%d", &base);
printf("Enter power number(positive integer): ");
scanf("%d", &a);
result = power(base, a);
printf("%d^%d = %d", base, a, result);
return 0;
}
int power(int base, int a) {
if (a != 0)
return (base * power(base, a - 1));
else
return 1;
}

 Program-9
C Program to Convert Binary Number to Decimal and vice-versa
#include <stdio.h>
#include <math.h>
int convert(long long);
int main() {
long long n;
printf("Enter a binary number: ");
scanf("%lld", &n);
printf("%lld in binary = %d in decimal", n, convert(n));
return 0;
}
int convert(long long n) {
int dec = 0, i = 0, rem;
while (n != 0) {
rem = n % 10;
n /= 10;
dec += rem * pow(2, i);
++i;
}
return dec;
}

 Program-10
C Program to Convert Octal Number to Decimal and vice-versa
#include <stdio.h>
#include <math.h>
int convertDecimalToOctal(int decimalNumber);
int main() {
int decimalNumber;
printf("Enter a decimal number: ");
scanf("%d", &decimalNumber);
printf("%d in decimal = %d octal", decimalNumber, convertDecimalToOctal(decimalNumber));
return 0;
}
int convertDecimalToOctal(int decimalNumber) {
int octalNumber = 0, i = 1;
while (decimalNumber != 0) {
octalNumber += (decimalNumber % 8) * i;
decimalNumber /= 8;
i *= 10;
}
return octalNumber;
}

 Program-11
C Program to Convert Binary Number to Octal and vice-versa
#include <math.h>
#include <stdio.h>
int convert(long long bin);
int main() {
long long bin;
printf("Enter a binary number: ");
scanf("%lld", &bin);
printf("%lld in binary = %d in octal", bin, convert(bin));
return 0;
}
int convert(long long bin) {
int oct = 0, dec = 0, i = 0;
while (bin != 0) {
dec += (bin % 10) * pow(2, i);
++i;
bin /= 10;
}
i = 1;
while (dec != 0) {
oct += (dec % 8) * i;
dec /= 8;
i *= 10;
}
return oct;
}

 Program-12
Write a program in C to find the square of any number using the function.
#include <stdio.h>
double square(double num)
{
return (num * num);
}
int main()
{
int num;
double n;
printf("\n\n Function : find square of any number :\n");
printf("Input any number for square : ");
scanf("%d", &num);
n = square(num);
printf("The square of %d is : %.2f\n", num, n);
return 0;
}

 Program-13
Write a program in C to check if a given number is even or odd using the function.
#include <stdio.h>
int checkOddEven(int n1)
{
return (n1 & 1);
}
int main()
{
int n1;
printf("\n\n Function : check the number is even or odd:\n");
printf("Input any number : ");
scanf("%d", &n1);
if(checkOddEven(n1))
{
printf("The entered number is odd.\n\n");
}
else
{
printf("The entered number is even.\n\n");
}
return 0;
}

 Program-14
Write a program in C to get the largest element of an array using the function.
#include<stdio.h>
#define MAX 100
int findMaxElem(int []);
int n;
int main()
{
int arr1[MAX],mxelem,i;
printf("\n\n Function : get largest element of an array :\n");
printf(" Input the number of elements to be stored in the array :");
scanf("%d",&n);
printf(" Input %d elements in the array :\n",n);
for(i=0;i<n;i++)
{
printf(" element - %d : ",i);
scanf("%d",&arr1[i]);
}
mxelem=findMaxElem(arr1);
printf(" The largest element in the array is : %d\n\n",mxelem);
return 0;
}
int findMaxElem(int arr1[])
{
int i=1,mxelem;
mxelem=arr1[0];
while(i < n)
{
if(mxelem<arr1[i])
mxelem=arr1[i];
i++;
}
return mxelem;
}

 Program-15
Write a program in C to find the sum of the series 1!/1+2!/2+3!/3+4!/4+5!/5 using the function.
#include <stdio.h>
int fact(int);
void main()
{
int sum;
sum=fact(1)/1+fact(2)/2+fact(3)/3+fact(4)/4+fact(5)/5;
printf("\n\n Function : find the sum of 1!/1+2!/2+3!/3+4!/4+5!/5 :\n");
printf("The sum of the series is : %d\n\n",sum);
}
int fact(int n)
{
int num=0,f=1;
while(num<=n-1)
{
f =f+f*num;
num++;
}
return f;
}
‘C’ LANGUAGE

POINTERS

What is Pointer? How pointers are defined in ‘c’ and


Explain uses of Pointers

Pointer:

A pointer is a variable that holds the address of


another variable; a pointer is said to "point to" the
variable whose address it holds. A pointer is declared like
an ordinary variable and its name is prefixed with ‘*’.

The two operators needed with pointers are the address-


of operator (&) and the indirection operator (*). When
placed before a variable name, the address-of operator
returns the variable's address. When placed before a
pointer name, the indirection operator returns the contents
of the pointed-to variable.

Syntax:
<Datatype> *<ptr_variable> [= &variable];

Ex:
int a=10;
int *p = &a;

printf(“address is %u”,p);
printf(“value is %d”,*p;

Uses:

 Pointers provide a powerful and flexible method for


manipulating the data of the variables.
 Pointer is more efficient in handling arrays and
different types of data.
 Pointers can be used to return multiple values from a
function via function arguments.
 Pointers permit references to functions and they’re by
facilitating passing of functions as arguments to
other functions.
 Pointers allow C to support dynamic memory management.
 Pointers reduce length and complexity of programs.
 They increase the execution speed and thus reduce the
program execution time.

-1-
‘C’ LANGUAGE

What is indirection?

Accessing the contents of a variable by using a pointer


to the variable is called indirect access or indirection.
‘*’ refers to indirection operator.

How can U declare pointer to a variable:

We can define the pointer to any type of variables.

Syntax:
<datatype> *<pointer_var> [= &variable];
Ex:
int a=10;
int *p = &a;

1. EXAMPLE TO POINTER TO A VARIABLE

#include<stdio.h>

int main()
{

int a=10;

int *p;

p = &a;

printf("address is %u\n",p);
printf("value is %d\n",*p);

(*p)++;

printf("value is %d\n",*p); //value in *p=11


printf("value is %d\n",a); //value in a=11

return 0;
}

Pointer to Pointer (Double Pointer):

The pointer to a pointer in C is used when we want to


store the address of another pointer. The first pointer is
used to store the address of the variable. And the second
pointer is used to store the address of the first pointer.
That is why they are also known as double-pointers. We can
-2-
‘C’ LANGUAGE

use a pointer to a pointer to change the values of normal


pointers or create a variable-sized 2-D array. A double
pointer occupies the same amount of space in the memory
stack as a normal pointer.

Syntax:
data_type_of_pointer **name_of_variable = &
normal_pointer_variable;

Example 2:

#include<stdio.h>
int main()
{
int a=10;
int *p,**q;
p=&a;
q=&p;
printf("%d %d %d\n",*(&a),a,*p,**q);
printf("%u %u %u\n",&a,p,*q);
printf("%u %u %u",&p,q,&q);
printf("\n%d",sizeof(p));
return 0;
}

NULL Pointer:

The Null Pointer is the pointer that does not point to any
location but NULL.
Syntax of Null Pointer Declaration in C
type pointer_name = NULL;
type pointer_name = 0;

Uses of NULL Pointer:

1. To initialize a pointer variable when that pointer


variable hasn’t been assigned any valid memory address
yet.
2. To check for a null pointer before accessing any pointer
variable. By doing so, we can perform error handling in
pointer-related code, e.g., dereference a pointer
variable only if it’s not NULL.
3. To pass a null pointer to a function argument when we
don’t want to pass any valid memory address.
4. A NULL pointer is used in data structures like trees,
linked lists, etc. to indicate the end.
-3-
‘C’ LANGUAGE

Example 3:

#include <stdio.h>

int main()
{

int* ptr = NULL; // declaring null pointer

if (ptr == NULL)
{
printf("Pointer does not point to anything");
}
else
{
printf("Value pointed by pointer: %d", *ptr);
}
return 0;
}

void pointer:

A void pointer is a pointer that has no associated data


type with it. A void pointer can hold an address of any
type and can be typecasted to any type.

Advantages of Void Pointers:

 malloc() and calloc() return void * type and this allows


these functions to be used to allocate memory of any
data type (just because of void *).
 void pointers in C are used to implement generic
functions in C. For example,

Example 4:

#include<stdio.h>
int main(void)
{
int a=10;
float b=3.14;
void *p;
p=&a;
printf("%d\n",*(int *)p);
p=&b;

-4-
‘C’ LANGUAGE

printf("%f",*(float *)p);
return 0;
}

How can U declare pointer to an Array:

Syntax:
<datatype> *<ptr_var> [= array_name];

<datatype> *<ptr_var> [=&array_name[0]];

Ex:
int a[5]={1,2,3,4,5};

int *p = &a[0]; //int *p=a;

6. W.A.P TO ACCESS THE ARRAY ELEMENTS USING POINTERS

#include<stdio.h>

int main()
{
int a[5]={1,2,3,4,5};
int *p,i;

p=a; // p=&a[0]

for(i=0;i<5;i++)
printf("%d ",*(p+i));

return 0;
}

7. W.A.P TO SORT THE ARRAY VALUES IN ASCENDING ORDER


USING POINTERS and functions?

#include<stdio.h>

void read( int *p, int n);


void print( int *p, int n);
void sort( int *p, int n);

int main()
{

int a[10], i, n;

printf("How many values do u want to read : ");


scanf("%d",&n);

-5-
‘C’ LANGUAGE

read(a,n);

printf("\n Before sorting Array \n");


print(a,n);

sort(a,n);

printf("\n After sorting Array \n");


print(a,n);

return 0;
}

void read( int *p, int n )


{
int i;

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


{
printf("\nEnter a[%d] value : ",i);
scanf("%d",&(p+i));
}
}

void print( int *p, int n )


{
int i;

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


printf("%3d",*(p+i));

printf("\n");
}

void sort( int *p, int n )


{
int i, j, temp;

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


{
for( j=0; j<n-i-1; j++ )
{
if( *(p+j) > *(p+j+1) )
{
temp = *(p+j);
*(p+i) = *(p+j+1);
*(p+j+1) = temp;
}
}
}
}
-6-
‘C’ LANGUAGE

How can U declare pointer to double dimension Array:

Syntax:
<datatype> *<ptr_var> [= array_name];

<datatype> (*<ptr_var>[size]) [=&array_name[0][0]];

Ex:
int a[3][3]={{1,2,3},{4,5,6},{7,8,9}};

int (*p)[3] = &a[0][0]; //int (*p)[3]=a;

8.EXAMPLE FOR POINTER TO DD-ARRAYS

#include<stdio.h>
int main()
{

int a[3][3]={{1,2,3},{4,5,6},{7,8,9}};

int (*p)[3] = &a[0][0]; // int (*p)[3] = a;

int i, j;

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


{
for( j=0; j<3; j++ )
{
printf("%3d",*(*(p+i)+j));
}
printf("\n");
}
return 0;
}

How can U declare pointer to strings:

Syntax:
char *ptr_var [= &str_variable];
-7-
‘C’ LANGUAGE

Ex:
Char st[]=”hello”;
char *ptr = st;

9. W.A.P TO COUNT THE NO. OF WORDS, SPACES, CHARACTERS


IN THE GIVEN STRING USING POINTERS

#include<stdio.h>

void count( char * );

int main()
{

char st[80];
int len;

clrscr();

printf("Enter the Sentence :: ");


gets(st);

count( st );

return 0;
}

void count( char *p )


{
int i, now, nos, noc;

now = 1;
nos = noc = 0;

for( i=0; *(p+i)!=NULL ; i++ )


{

if( ( *(p+i) >= 'a' && *(p+i) <= 'z' ) ||


( *(p+i) >= 'A' && *(p+i) <= 'Z') )

noc++;

else if( *(p+i) == ' ' )


{
now++;
nos++;
}

}
-8-
‘C’ LANGUAGE

printf("No of words is :: %d\n", now);


printf("No of spaces is :: %d\n", nos);
printf("No of characters is :: %d", noc);

10. W.A.P TO SORT THE STRINGS USING POINTERS

#include<stdio.h>
#include<string.h>

#define line(col) for(i=0;i<col;i++) printf("-");


printf("\n")

void read( char(*)[20], int );


void print( char(*)[20], int );
void sort( char(*)[20], int );

int main()
{
char st[10][20];
int n, i;

printf("How many strings do U want to read ::");


scanf("%d",&n);

printf("Enter the %d strings :: \n",n);


read( st, n );

line(40);
printf("Before Sorting Strings are ::\n");
line(40);
print( st, n );

sort( st, n );

line(40);
printf("After sorting String are :: \n");
line(40);

print( st[0], n );
retun 0;

void read( char (*p)[20], int n )


{
int i;

-9-
‘C’ LANGUAGE

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


{
fflush(stdin);
gets( *(p+i) );
}
}

void print( char (*p)[20], int n )


{
int i;

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


printf("%s\n", *(p+i) );
}

void sort( char (*p)[20], int n )


{
int i, j;
char temp[80];

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


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

if( strcmp( *(p+i), *(p+j) ) > 0 )


{
strcpy( temp, *(p+i) );
strcpy( *(p+i), *(p+j) );
strcpy( *(p+j), temp);
}
}
}
}

How can U declare pointer to structures:

Syntax:

struct <struct_type> *<ptr_var> [= &struct_variable];


Ex:
struct student
{
int sno;
char sname[20];
char group[5];
};

- 10 -
‘C’ LANGUAGE

struct student s = {1,”srikanth”,”MSCs”};


struct student *p = &s;

11. w.a.p to access the structure elements using pointers

#include<stdio.h>

typedef struct
{
int sid;
char sna[20];
char course[10];

}Student;

void read( Student *p );


void print( Student *p );

int main()
{
Student s;

read(&s);
print(&s);
return 0;
}

void read( Student *p )


{
printf("Enter the student id : ");
scanf("%d",&p->sid); //scanf("%d",&(*p).sno);

printf("Enter the student name : ");


scanf("%s",p->sna);

printf("Enter the course : ");


scanf("%s",p->course);

void print( Student *p )


{
printf("\n Student info \n");
printf("sid=%d, sname=%s, course=%s\n",
p->sid, p->sna, p->course);
}

- 11 -
‘C’ LANGUAGE

12. W.A.P TO SWAP THE TWO VARIABLE VALUES USING POINTERS

#include<stdio.h>

void swap( int *p1, int *p2 )


{
int temp;

temp = *p1;
*p1 = *p2;
*p2 = temp;
}

int main()
{
int a=10, b=20;

printf("\n before swapping a=%d, b=%d\n",a,b);

swap(&a,&b);

printf("\n after swapping a=%d, b=%d\n",a,b);

return 0;
}

Dynamic Memory Allocation in C using malloc(), calloc(),


free() and realloc():

malloc():

The “malloc” or “memory allocation” method in C is used to


dynamically allocate a single large block of memory with
the specified size. It returns a pointer of type void
which can be cast into a pointer of any form. It doesn’t
Initialize memory at execution time so that it has
initialized each block with the default garbage value
initially.

Syntax:

ptr = (cast-type*) malloc(byte-size)

13. Write a program to read and print the array elements


by using dynamic memory allocation

#include<stdio.h>
#include<stdlib.h>

void read(int *);


void print(int *);
- 12 -
‘C’ LANGUAGE

int n;

int main()
{
int *a;
printf("Enter array size...");
scanf("%d",&n);

a=(int *)malloc(sizeof(int)*n);

read(a);
print(a);
return 0;
}

void read(int *a)


{
int i;

printf("\n Enter elements in the array:");


for(i=0;i<n;i++)
scanf("%d",(a+i));
}

void print(int *a)


{
int i;

for(i=0;i<n;i++)
printf("%d ",*(a+i));
}

calloc():
1. “calloc” or “contiguous allocation” method in C is used
to dynamically allocate the specified number of blocks of
memory of the specified type. it is very much similar to
malloc() but has two different points and these are:

2. It initializes each block with a default value ‘0’.

3. It has two parameters or arguments as compare to


malloc().

Syntax :

ptr = (cast-type*)calloc(n, element-size);

here, n is the no. of elements and element-size is the


size of each element.

- 13 -
‘C’ LANGUAGE

14. Write a program to searching an element in the array


elements by using dynamic memory allocation

#include<stdlib.h>
#include<stdio.h>

int bs(int *a,int s,int l,int h)


{
int m;
while(l<=h){
m=(l+h)/2;
if(*(a+m)>s) h=m-1;
else if(*(a+m)<s) l=m+1;
else return 1;
}
return 0;
}

int main(void)
{
int *a,s,n;
printf("enter the size of array: ");
scanf("%d",&n);
a=(int *)calloc(n,sizeof(int));
if(a==NULL)
{
printf("\a\a\a\aerror!!!");
exit(0);
}
printf("enter the elements in arr:");
for(int i=0;i<n;i++) scanf("%d",(a+i));
printf("enter element need to find: ");
scanf("%d",&s);
if(bs(a,s,0,n-1)) printf("element found");
else printf("element not found");
return 0;
}

15. Write a program to read and print of a given matrix by


using dynamic memory allocation

#include<stdio.h>
#include<stdlib.h>

void read(int **a,int r,int c)


{
int i,j;
for(i=0;i<r;i++)
for(j=0;j<c;j++)
scanf("%d",(*(a+i)+j));
}
void display(int **a,int r, int c)
{
- 14 -
‘C’ LANGUAGE

int i,j;
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
printf("%d ",*(*(a+i)+j));
printf("\n");
}
}
int main(void)
{
int **a,i,j,r,c;
printf("enter the size of matrix: ");
scanf("%d%d",&r,&c);
a=(int **)malloc(r*sizeof(int));
for(i=0;i<r;i++)
{
*(a+i)=(int *)malloc(c*sizeof(int));
}
read(a,r,c);
display(a,r,c);
return 0;
}

free():

“free” method in C is used to dynamically de-allocate the


memory. The memory allocated using functions malloc() and
calloc() is not de-allocated on their own. Hence the
free() method is used, whenever the dynamic memory
allocation takes place. It helps to reduce wastage of
memory by freeing it.

Syntax :

free(ptr);

Example 16:

#include <stdio.h>
#include <stdlib.h>

int main()
{

int *ptr, *ptr1;


int n, i;
n = 5;
printf("Enter number of elements: %d\n", n);

ptr = (int*)malloc(n * sizeof(int));

ptr1 = (int*)calloc(n, sizeof(int));

if (ptr == NULL || ptr1 == NULL) {


- 15 -
‘C’ LANGUAGE

printf("Memory not allocated.\n");


exit(0);
}
else {
printf("Memory successfully allocated using
malloc.\n");
free(ptr);
printf("Malloc Memory successfully freed.\n");

printf("\nMemory successfully allocated using


calloc.\n");

free(ptr1);
printf("Calloc Memory successfully freed.\n");
}

return 0;
}

realloc():

“realloc” or “re-allocation” method in C is used to


dynamically change the memory allocation of a previously
allocated memory. In other words, if the memory previously
allocated with the help of malloc or calloc is
insufficient, realloc can be used to dynamically re-
allocate memory. re-allocation of memory maintains the
already present value and new blocks will be initialized
with the default garbage value.

Syntax :

ptr = realloc(ptr, newSize);

where ptr is reallocated with new size 'newSize'.

Example 17:

#include <stdio.h>
#include <stdlib.h>

int main()
{

int* ptr;
int n, i;

n = 5;
printf("Enter number of elements: %d\n", n);

ptr = (int*)calloc(n, sizeof(int));

if (ptr == NULL) {
- 16 -
‘C’ LANGUAGE

printf("Memory not allocated.\n");


exit(0);
}
else {

printf("Memory successfully allocated using


calloc.\n");

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


ptr[i] = i + 1;
}

printf("The elements of the array are: ");


for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}

n = 10;
printf("\n\nEnter the new size of the array:
%d\n", n);

ptr = (int*)realloc(ptr, n * sizeof(int));

printf("Memory successfully re-allocated using


realloc.\n");

for (i = 5; i < n; ++i) {


ptr[i] = i + 1;
}

printf("The elements of the array are: ");


for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}

free(ptr);
}

return 0;
}

- 17 -

You might also like