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

unit1paper2AD

The document provides an overview of programming language concepts, including basic terminology, characteristics, advantages, and disadvantages of programming languages. It also discusses flowcharts as a tool for algorithm representation, basic symbols used in flowcharts, and rules for creating them. Additionally, the document covers data types in C, including their sizes, ranges, and examples of usage.

Uploaded by

Shameem Akhtar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

unit1paper2AD

The document provides an overview of programming language concepts, including basic terminology, characteristics, advantages, and disadvantages of programming languages. It also discusses flowcharts as a tool for algorithm representation, basic symbols used in flowcharts, and rules for creating them. Additionally, the document covers data types in C, including their sizes, ranges, and examples of usage.

Uploaded by

Shameem Akhtar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 99

Paper II part 1

Unit 1:
Programing language concepts:
The basic programming concepts include variables, basic control structures, data
structures, object-oriented programming, troubleshooting and debugging, and various
programming tools. These concepts are similar across various programming languages,
such as Python, C++, C, and Java.

Introduction to Programming Languages

Introduction:

A programming language is a set of instructions and syntax used to create software


programs. Some of the key features of programming languages include:
1. Syntax: The specific rules and structure used to write code in a programming
language.
2. Data Types: The type of values that can be stored in a program, such as numbers,
strings, and booleans.
3. Variables: Named memory locations that can store values.
4. Operators: Symbols used to perform operations on values, such as addition,
subtraction, and comparison.
5. Control Structures: Statements used to control the flow of a program, such as if-
else statements, loops, and function calls.
6. Libraries and Frameworks: Collections of pre-written code that can be used to
perform common tasks and speed up development.
7. Paradigms: The programming style or philosophy used in the language, such as
procedural, object-oriented, or functional.
Examples of popular programming languages include Python, Java, C++, JavaScript,
and Ruby. Each language has its own strengths and weaknesses and is suited for
different types of projects.
Characteristics of a programming Language –

• A programming language must be simple, easy to learn and use, have good
readability, and be human recognizable.
• Abstraction is a must-have Characteristics for a programming language in which the
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 its execution 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 the development, debugging, testing, maintenance of a program
must be provided by a programming language.
• A programming language should provide a single environment known as Integrated
Development Environment(IDE).
• A programming language must be consistent in terms of syntax and semantics.
Basic Terminologies in Programming Languages:
• Algorithm: A step-by-step procedure for solving a problem or performing a task.
• Variable: A named storage location in memory that holds a value or data.
• Data Type: A classification that specifies what type of data a variable can hold, such
as integer, string, or boolean.
• Function: A self-contained block of code that performs a specific task and can be
called from other parts of the program.
• Control Flow: The order in which statements are executed in a program, including
loops and conditional statements.
• Syntax: The set of rules that govern the structure and format of a programming
language.
• Comment: A piece of text in a program that is ignored by the compiler or interpreter,
used to add notes or explanations to the code.
• Debugging: The process of finding and fixing errors or bugs in a program.
• IDE: Integrated Development Environment, a software application that provides a
comprehensive development environment for coding, debugging, and testing.
• Operator: A symbol or keyword that represents an action or operation to be
performed on one or more values or variables, such as + (addition), – (subtraction), *
(multiplication), and / (division).
• Statement: A single line or instruction in a program that performs a specific action or
operation.
Basic Example Of Most Popular Programming Languages:
Here the basic code for addition of two numbers are given in some popular languages
(like C, C++,Java, Python, C#, JavaScript etc.).

• C++
• C
• Python3
• Java
• C#
• Javascript
• PHP
• Scala
• HTML
• Cobol
• Dart
• Go
• Julia
• Kotlin
• Perl
• Swift

// C++ program for sum of 2 numbers


#include <iostream>
using namespace std;

int main()
{
int a, b, sum;
a = 10;
b = 15;
sum = a + b;
cout << "Sum of " << a << " and " << b
<< " is: " << sum; // perform addition operation
return 0;
}
// This code is contributed by Susobhan Akhuli

OutputSum of 10 and 15 is: 25

Advantages of programming languages:

8. Increased Productivity: Programming languages provide a set of abstractions that


allow developers to write code more quickly and efficiently.
9. Portability: Programs written in a high-level programming language can run on
many different operating systems and platforms.
10. Readability: Well-designed programming languages can make code more readable
and easier to understand for both the original author and other developers.
11. Large Community: Many programming languages have large communities of users
and developers, which can provide support, libraries, and tools.
Disadvantages of programming languages:

12. Complexity: Some programming languages can be complex and difficult to learn,
especially for beginners.
13. Performance: Programs written in high-level programming languages can run
slower than programs written in lower-level languages.
14. Limited Functionality: Some programming languages may not have built-in support
for certain types of tasks or may require additional libraries to perform certain
functions.
15. Fragmentation: There are many different programming languages, which can lead
to fragmentation and make it difficult to share code and collaborate with other
developers.

Tips for learning new programming language:

16. Start with the fundamentals: Begin by learning the basics of the language, such as
syntax, data types, variables, and simple statements. This will give you a strong
foundation to build upon.
17. Code daily: Like any skill, the only way to get good at programming is by practicing
regularly. Try to write code every day, even if it’s just a few lines.
18. Work on projects: One of the best ways to learn a new language is to work on a
project that interests you. It could be a simple game, a web application, or anything
that allows you to apply what you’ve learned that is the most important part.
19. Read the documentation: Every programming language has documentation that
explains its features, syntax, and best practices. Make sure to read it thoroughly to
get a better understanding of the language.
20. Join online communities: There are many online communities dedicated to
programming languages, where you can ask questions, share your code, and get
feedback. Joining these communities can help you learn faster and make
connections with other developers.
21. Learn from others: Find a mentor or someone who is experienced in the language
you’re trying to learn. Ask them questions, review their code, and try to understand
how they solve problems.
22. Practice debugging: Debugging is an essential skill for any programmer, and you’ll
need to do a lot of it when learning a new language. Make sure to practice
identifying and fixing errors in your code.

What is a Flowchart?
Flowchart is a graphical representation of an algorithm. Programmers often use it as a
program-planning tool to solve a problem. It makes use of symbols which are connected
among them to indicate the flow of information and processing.
The process of drawing a flowchart for an algorithm is known as “flowcharting”.
Basic Symbols used in Flowchart Designs
23. Terminal: The oval symbol indicates Start, Stop and Halt in a program’s logic flow.
A pause/halt is generally used in a program logic under some error conditions.
Terminal is the first and last symbols in the flowchart.

• Input/Output: A parallelogram denotes any function of input/output type. Program


instructions that take input from input devices and display output on output devices
are indicated with parallelogram in a flowchart.

• Processing: A box represents arithmetic instructions. All arithmetic processes such


as adding, subtracting, multiplication and division are indicated by action or process
symbol.

• Decision Diamond symbol represents a decision point. Decision based operations


such as yes/no question or true/false are indicated by diamond in flowchart.
• Connectors: Whenever flowchart becomes complex or it spreads over more than
one page, it is useful to use connectors to avoid any confusions. It is represented by
a circle.

• Flow lines: Flow lines indicate the exact sequence in which instructions are
executed. Arrows represent the direction of flow of control and relationship among
different symbols of flowchart.
Rules For Creating Flowchart :
A flowchart is a graphical representation of an algorithm.it should follow some rules
while creating a flowchart
Rule 1: Flowchart opening statement must be ‘start’ keyword.
Rule 2: Flowchart ending statement must be ‘end’ keyword.
Rule 3: All symbols in the flowchart must be connected with an arrow line.
Rule 4: The decision symbol in the flowchart is associated with the arrow line.

Advantages of Flowchart:

• Flowcharts are a better way of communicating the logic of the system.


• Flowcharts act as a guide for blueprint during program designed.
• Flowcharts help in debugging process.
• With the help of flowcharts programs can be easily analyzed.
• It provides better documentation.
• Flowcharts serve as a good proper documentation.
• Easy to trace errors in the software.
• Easy to understand.
• The flowchart can be reused for inconvenience in the future.
• It helps to provide correct logic.

Disadvantages of Flowchart:

• It is difficult to draw flowcharts for large and complex programs.


• There is no standard to determine the amount of detail.
• Difficult to reproduce the flowcharts.
• It is very difficult to modify the Flowchart.
• Making a flowchart is costly.
• Some developer thinks that it is waste of time.
• It makes software processes low.
• If changes are done in software, then the flowchart must be redrawn

Example : Draw a flowchart to input two numbers from the user and display the
largest of two numbers
• C++
• C
• Java
• Python3
• C#

// C++ program to find largest of two numbers


#include <iostream>
using namespace std;
int main()
{
int num1, num2, largest;

/*Input two numbers*/


cout << "Enter two numbers:\n";
cin >> num1;
cin >> num2;

/*check if a is greater than b*/


if (num1 > num2)
largest = num1;
else
largest = num2;

/*Print the largest number*/


cout << largest;

return 0;
}

Output
Enter two numbers:
10 30
30

Data Types in C

Each variable in C has an associated data type. It specifies the type of data that the
variable can store like integer, character, floating, double, etc. Each data type requires
different amounts of memory and has some specific operations which can be performed
over it. The data type is a collection of data with values having fixed values, meaning as
well as its characteristics.
The data types in C can be classified as follows:

Types Description

Primitive Primitive data types are the most basic data types that are used for
Data Types representing simple values such as integers, float, characters, etc.

User
Defined The user-defined data types are defined by the user himself.
Data Types
Derived The data types that are derived from the primitive or built-in
Types datatypes are referred to as Derived Data Types.

Different data types also have different ranges up to which they can store numbers.
These ranges may vary from compiler to compiler. Below is a list of ranges along with
the memory requirement and format specifiers on the 32-bit GCC compiler.

Data Type Size Range Format


(bytes) Specifier

short int 2 -32,768 to 32,767 %hd

unsigned short int 2 0 to 65,535 %hu

unsigned int 4 0 to 4,294,967,295 %u

-2,147,483,648 to
int 4 %d
2,147,483,647
-2,147,483,648 to
long int 4 %ld
2,147,483,647

unsigned long int 4 0 to 4,294,967,295 %lu

long long int 8 -(2^63) to (2^63)-1 %lld

0 to
unsigned long
8 18,446,744,073,709,551,61 %llu
long int
5

signed char 1 -128 to 127 %c

unsigned char 1 0 to 255 %c

float 4 %f
1.2E-38 to 3.4E+38

double 8 %lf
1.7E-308 to 1.7E+308

long double 16 %Lf


3.4E-4932 to 1.1E+4932

Note: The long, short, signed and unsigned are datatype modifier that can be used
with some primitive data types to change the size or length of the datatype.
The following are some main primitive data types in C:
Integer Data Type
The integer datatype in C is used to store the integer numbers(any number including
positive, negative and zero without decimal part). Octal values, hexadecimal values,
and decimal values can be stored in int data type in C.
• Range: -2,147,483,648 to 2,147,483,647
• Size: 4 bytes
• Format Specifier: %d

Syntax of Integer

We use int keyword to declare the integer variable:


int var_name;

The integer data type can also be used as


24. unsigned int: Unsigned int data type in C is used to store the data values from zero
to positive numbers but it can’t store negative values like signed int.
25. short int: It is lesser in size than the int by 2 bytes so can only store values from -
32,768 to 32,767.
26. long int: Larger version of the int datatype so can store values greater than int.
27. unsigned short int: Similar in relationship with short int as unsigned int with int.
Note: The size of an integer data type is compiler-dependent. We can use sizeof
operator to check the actual size of any data type.

Example of int

• C

// C program to print Integer data types.


#include <stdio.h>

int main()
{
// Integer value with positive data.
int a = 9;

// integer value with negative data.


int b = -9;

// U or u is Used for Unsigned int in C.


int c = 89U;

// L or l is used for long int in C.


long int d = 99998L;

printf("Integer value with positive data: %d\n", a);


printf("Integer value with negative data: %d\n", b);
printf("Integer value with an unsigned int data: %u\n",
c);
printf("Integer value with an long int data: %ld", d);

return 0;
}

OutputInteger value with positive data: 9


Integer value with negative data: -9
Integer value with an unsigned int data: 89
Integer value with an long int data: 99998

Character Data Type


Character data type allows its variable to store only a single character. The size of the
character is 1 byte. It is the most basic data type in C. It stores a single character and
requires a single byte of memory in almost all compilers.

• Range: (-128 to 127) or (0 to 255)


• Size: 1 byte
• Format Specifier: %c

Syntax of char

The char keyword is used to declare the variable of character type:


char var_name;

Example of char

• C

// C program to print Integer data types.


#include <stdio.h>
int main()
{
char a = 'a';
char c;

printf("Value of a: %c\n", a);

a++;
printf("Value of a after increment is: %c\n", a);

// c is assigned ASCII values


// which corresponds to the
// character 'c'
// a-->97 b-->98 c-->99
// here c will be printed
c = 99;

printf("Value of c: %c", c);

return 0;
}

OutputValue of a: a
Value of a after increment is: b
Value of c: c

Float Data Type


In C programming float data type is used to store floating-point values. Float in C is
used to store decimal and exponential values. It is used to store decimal numbers
(numbers with floating point values) with single precision.

• Range: 1.2E-38 to 3.4E+38


• Size: 4 bytes
• Format Specifier: %f

Syntax of float

The float keyword is used to declare the variable as a floating point:


float var_name;

Example of Float

• C

// C Program to demonstrate use


// of Floating types
#include <stdio.h>

int main()
{
float a = 9.0f;
float b = 2.5f;

// 2x10^-4
float c = 2E-4f;
printf("%f\n", a);
printf("%f\n", b);
printf("%f", c);

return 0;
}

Output9.000000
2.500000
0.000200

Double Data Type


A Double data type in C is used to store decimal numbers (numbers with floating point
values) with double precision. It is used to define numeric values which hold numbers
with decimal values in C.
The double data type is basically a precision sort of data type that is capable of holding
64 bits of decimal numbers or floating points. Since double has more precision as
compared to that float then it is much more obvious that it occupies twice the memory
occupied by the floating-point type. It can easily accommodate about 16 to 17 digits
after or before a decimal point.
• Range: 1.7E-308 to 1.7E+308
• Size: 8 bytes
• Format Specifier: %lf

Syntax of Double

The variable can be declared as double precision floating point using the double
keyword:
double var_name;

Example of Double

• C

// C Program to demonstrate
// use of double data type
#include <stdio.h>

int main()
{
double a = 123123123.00;
double b = 12.293123;
double c = 2312312312.123123;

printf("%lf\n", a);

printf("%lf\n", b);

printf("%lf", c);

return 0;
}

Output123123123.000000
12.293123
2312312312.123123
Void Data Type
The void data type in C is used to specify that no value is present. It does not provide a
result value to its caller. It has no values and no operations. It is used to represent
nothing. Void is used in multiple ways as function return type, function arguments as
void, and pointers to void.

Syntax:

// function return type void


void exit(int check);
// Function without any parameter can accept void.
int print(void);
// memory allocation function which
// returns a pointer to void.
void *malloc (size_t size);

Example of Void

• C

// C program to demonstrate
// use of void pointers
#include <stdio.h>

int main()
{
int val = 30;
void* ptr = &val;
printf("%d", *(int*)ptr);
return 0;
}

Output30

Size of Data Types in C


The size of the data types in C is dependent on the size of the architecture, so we
cannot define the universal size of the data types. For that, the C language provides the
sizeof() operator to check the size of the data types.
Example

• C

// C Program to print size of


// different data type in C
#include <stdio.h>

int main()
{
int size_of_int = sizeof(int);
int size_of_char = sizeof(char);
int size_of_float = sizeof(float);
int size_of_double = sizeof(double);

printf("The size of int data type : %d\n", size_of_int);


printf("The size of char data type : %d\n",
size_of_char);
printf("The size of float data type : %d\n",
size_of_float);
printf("The size of double data type : %d",
size_of_double);

return 0;
}

OutputThe size of int data type : 4


The size of char data type : 1
The size of float data type : 4
The size of double data type : 8

Derived Data Types in C

Last Updated : 06 Sep, 2023


Data types in the C language can be categorized into three types, namely primitive,
user-defined, and derived data types. In this article, we shall learn about derived data
types.
In C, the data types derived from the primitive or built-in data types are called Derived
Data Types. In other words, the derived data types are those data types that are
created by combining primitive data types and other derived data types.
There are three derived data types available in C. They are as follows:
28. Function
29. Array
30. Pointer
We shall learn about each of these data types one by one.
1. Functions
A function is called a C language construct which consists of a function-body associated
with a function-name. In every program in C language, execution begins from the main
function, which gets terminated after completing some operations which may include
invoking other functions.

Function Declaration

return_type function_name(data_type param1, data_type param2, ...);

Example

• C

// C program to illustrate derived data type - function


#include <stdio.h>

int multiply(int param1, int param2)


{
// return statement which return type int
return (param1 * param2);
}

int main()
{
// declaring parameters to be passed to the function
int param1 = 5, param2 = 3;

// calling the function and storing the return value in


// result
int result = multiply(param1, param2);

// printing the result to the console


printf("%d", result);
return 0;
}

Output15

Components of a Function in C

• Return Type: Specifies the type of the value that the function will return after its
execution.
• Function Name: It is a unique name that identifies a function. Using this unique
name, a function is called from various parts of a program.
• Function Body: A function’s body consists of the statements that define what the
function actually does. All the operations including the return of the result are done
inside the body of a function.
• Parameters: Parameters are the input values passed to the function by the caller. A
function can have none or multiple parameters.
• Return Statement: A function returns a value depending on its return type.
For more details about Functions in C, please refer to this article.
2. Arrays
Array in C is a fixed-size collection of similar data items stored in contiguous memory
locations. An array is capable of storing the collection of data of primitive, derived, and
user-defined data types.

Array Declaration

data_type array_name [size];


Example

• C

// C program to illustrate derived data type - Array


#include <stdio.h>

int main()
{
// declaring the size of the array
int N = 3;

// declaring array of type int of size N


int arrI[] = { 18, 36, 54 };
for (int i = 0; i < N; i++)
printf("%d ", arrI[i]);

printf("\n");

// declaring array of type double of size N


double arrD[] = { 3.14, 6.28, 9.42 };
for (int i = 0; i < N; i++)
printf("%lf ", arrD[i]);

return 0;
}

Output18 36 54
3.140000 6.280000 9.420000

Properties of Arrays in C

Following are some defining properties of arrays in C

• Array in C has a fixed size that should be known at compile time.


• An array can only store elements of the same type.
• Elements of the array are stored in the contiguous memory location.
• Array provides random access to its elements.
• An array can have multiple dimensions i.e. directions in which it can grow.
For more details about Arrays in C, please refer to this article.
Pointer
A pointer in C language is a data type that stores the address where data is stored.
Pointers store memory addresses of variables, functions, and even other pointers.

Pointer Declaration

data_type * ptr_name;
where,

• data_type: type of data that a pointer is pointing to.


• ptr_name: name of the pointer.
• *: dereferencing operator.

Example:

• C

// C program to illustrate derived datatype - pointers


#include <stdio.h>

int main()
{
int var = 20;

// declare pointer variable


int* myPtr;

// note that data type of ptr and var must be same

// assign the address of a variable to a pointer


myPtr = &var;

// printing myPtr to show value stored in myPtr which is


// address of var
printf("Value at myPtr = %p \n", myPtr);
// printing var variable directly
printf("Value at var = %d \n", var);

// using dereferencing operator to get the value myPtr


// is pointing at
printf("Value at *myPtr = %d \n", *myPtr);

return 0;
}

OutputValue at myPtr = 0x7ffd0850df9c


Value at var = 20
Value at *myPtr = 20

Properties of Pointers in C

• A pointer can be of any type such as an integer pointer, function pointer, etc.
• A pointer can be any level deep such as a double pointer(pointer to pointer), triple
pointer, etc.
• All types of pointers have the same size on the given platform.
• Pointers may be of different sizes on different platforms.

User-Defined Data Types In C

Last Updated : 16 Oct, 2023

Data Types are the types of data that can be stored in memory using a programming
language. Basically, data types are used to indicate the type of data that a variable can
store. These data types require different amounts of memory and there are particular
operations that can be performed on them. These data types can be broadly classified
into three types:
31. Primitive Data Types
32. Derived Types
33. User Defined Data Types
In this article, will discuss the User-Defined Data Type.
What is a user-defined Datatype in C?
The data types defined by the user themself are referred to as user-defined data types.
These data types are derived from the existing datatypes.

Need of User-Defined Datatypes

• It enables customization in the code.


• Users can write more efficient and flexible code.
• Provides abstraction.
Types of User-Defined DataTypes
There are 4 types of user-defined data types in C. They are
34. Structure
35. Union
36. Enum
37. Typedef
1. Structure
As we know, C doesn’t have built-in object-oriented features like C++ but structures can
be used to achieve encapsulation to some level. Structures are used to group items of
different types into a single type. The “struct” keyword is used to define a structure. The
size of the structure is equal to or greater than the total size of all of its members.

Syntax

struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
};

Example

• C
// C Code to implement a struct
#include <stdio.h>

// Defining a structure
struct Person {
char company[50];
int lifespan;
};

int main()
{
// Declaring a variable of the structure type
struct Person person1;

// Initializing structure members


strcpy(person1.company, "GeeksforGeeks");
person1.lifespan = 30;

// Accessing and printing structure members


printf("Name: %s\n", person1.company);
printf("Age: %d\n", person1.lifespan);
return 0;
}

OutputName: GeeksforGeeks
Age: 30

2. Union
Unions are similar to structures in many ways. What makes a union different is that all
the members in the union are stored in the same memory location resulting in only one
member containing data at the same time. The size of the union is the size of its largest
member. Union is declared using the “union” keyword.

Syntax

union union_name {
datatype member1;
datatype member2;
...
};
Example

• C

// C Code to implement Union


#include <stdio.h>

// Declaring a union
union Data {
int i;
float f;
char str[20];
};

int main()
{
// creating an instance named 'data' of union Data
union Data data;
data.i = 10;
printf("Data.i: %d\n", data.i);

data.f = 3.14;
printf("Data.f: %f\n", data.f);

strcpy(data.str, "GeeksforGeeks, C");


printf("Data.str: %s\n", data.str);
return 0;
}

OutputData.i: 10
Data.f: 3.140000
Data.str: GeeksforGeeks, C

2. Enumeration (enums)
Enum is short for “Enumeration”. It allows the user to create custom data types with a
set of named integer constants. The “enum” keyword is used to declare an
enumeration. Enum simplifies and makes the program more readable.
Syntax

enum enum_name {const1, const2, ..., constN};


Here, the const1 will be assigned 0, const2 = 1, and so on in the sequence.
We can also assign a custom integer value such as:
enum enum_name {
const1 = 8;
const2 = 4;
}

Example

• C

// C code to implement enum


#include <stdio.h>

// Declaring a enum
enum Cafes {
Dyu_Art_Cafe,
Tea_Villa_Cafe,
The_Hole_in_the_Wall_Cafe,
Cafe_Azzure,
The_Banaglore_Cafe,
Dialogues_Cafe,
Cafe_Coffee_Day
};

// driver code
int main()
{
enum Cafes today = The_Banaglore_Cafe;
printf("Today is %d\n", today);
return 0;
}

OutputToday is 4
Typedef
typedef is used to redefine the existing data type names. Basically, it is used to provide
new names to the existing data types. The “typedef” keyword is used for this purpose;

Syntax

typedef existing_name alias_name;

Example

• C

// C Code to implement Typedef


#include <stdio.h>

typedef char Company;

int main()
{
Company* name = "GeeksforGeeks";
printf("Best Tutorials on: %s \n", name);
return 0;
}

OutputBest Tutorials on: GeeksforGeeks

Definition of Algorithm
The word Algorithm means ” A set of finite rules or instructions to be followed in
calculations or other problem-solving operations ”
Or
” A procedure for solving a mathematical problem in a finite number of steps that
frequently involves recursive operations”.
Therefore Algorithm refers to a sequence of finite steps to solve a particular problem.
Use of the Algorithms:
Algorithms play a crucial role in various fields and have many applications. Some of the
key areas where algorithms are used include:
38. Computer Science: Algorithms form the basis of computer programming and are
used to solve problems ranging from simple sorting and searching to complex tasks
such as artificial intelligence and machine learning.
39. Mathematics: Algorithms are used to solve mathematical problems, such as finding
the optimal solution to a system of linear equations or finding the shortest path in a
graph.
40. Operations Research: Algorithms are used to optimize and make decisions in fields
such as transportation, logistics, and resource allocation.
41. Artificial Intelligence: Algorithms are the foundation of artificial intelligence and
machine learning, and are used to develop intelligent systems that can perform
tasks such as image recognition, natural language processing, and decision-making.
42. Data Science: Algorithms are used to analyze, process, and extract insights from
large amounts of data in fields such as marketing, finance, and healthcare.
These are just a few examples of the many applications of algorithms. The use of
algorithms is continually expanding as new technologies and fields emerge, making it a
vital component of modern society.
Algorithms can be simple and complex depending on what you want to achieve.
It can be understood by taking the example of cooking a new recipe. To cook a new
recipe, one reads the instructions and steps and executes them one by one, in the given
sequence. The result thus obtained is the new dish is cooked perfectly. Every time you
use your phone, computer, laptop, or calculator you are using Algorithms. Similarly,
algorithms help to do a task in programming to get the expected output.
The Algorithm designed are language-independent, i.e. they are just plain instructions
that can be implemented in any language, and yet the output will be the same, as
expected.
What is the need for algorithms?
43. Algorithms are necessary for solving complex problems efficiently and effectively.
44. They help to automate processes and make them more reliable, faster, and easier to
perform.
45. Algorithms also enable computers to perform tasks that would be difficult or
impossible for humans to do manually.
46. They are used in various fields such as mathematics, computer science,
engineering, finance, and many others to optimize processes, analyze data, make
predictions, and provide solutions to problems.
What are the Characteristics of an Algorithm?

As one would not follow any written instructions to cook the recipe, but only the
standard one. Similarly, not all written instructions for programming are an algorithm.
For some instructions to be an algorithm, it must have the following characteristics:

• Clear and Unambiguous: The algorithm should be unambiguous. Each of its steps
should be clear in all aspects and must lead to only one meaning.
• Well-Defined Inputs: If an algorithm says to take inputs, it should be well-defined
inputs. It may or may not take input.
• Well-Defined Outputs: The algorithm must clearly define what output will be yielded
and it should be well-defined as well. It should produce at least 1 output.
• Finite-ness: The algorithm must be finite, i.e. it should terminate after a finite time.
• Feasible: The algorithm must be simple, generic, and practical, such that it can be
executed with the available resources. It must not contain some future technology or
anything.
• Language Independent: The Algorithm designed must be language-independent,
i.e. it must be just plain instructions that can be implemented in any language, and
yet the output will be the same, as expected.
• Input: An algorithm has zero or more inputs. Each that contains a fundamental
operator must accept zero or more inputs.
• Output: An algorithm produces at least one output. Every instruction that contains a
fundamental operator must accept zero or more inputs.
• Definiteness: All instructions in an algorithm must be unambiguous, precise, and
easy to interpret. By referring to any of the instructions in an algorithm one can
clearly understand what is to be done. Every fundamental operator in instruction
must be defined without any ambiguity.
• Finiteness: An algorithm must terminate after a finite number of steps in all test
cases. Every instruction which contains a fundamental operator must be terminated
within a finite amount of time. Infinite loops or recursive functions without base
conditions do not possess finiteness.
• Effectiveness: An algorithm must be developed by using very basic, simple, and
feasible operations so that one can trace it out by using just paper and pencil.
Properties of Algorithm:
• It should terminate after a finite time.
• It should produce at least one output.
• It should take zero or more input.
• It should be deterministic means giving the same output for the same input case.
• Every step in the algorithm must be effective i.e. every step should do some work.
Types of Algorithms:
There are several types of algorithms available. Some important algorithms are:

1. Brute Force Algorithm:

It is the simplest approach to a problem. A brute force algorithm is the first approach
that comes to finding when we see a problem.

2. Recursive Algorithm:

A recursive algorithm is based on recursion. In this case, a problem is broken into


several sub-parts and called the same function again and again.

3. Backtracking Algorithm:

The backtracking algorithm builds the solution by searching among all possible
solutions. Using this algorithm, we keep on building the solution following criteria.
Whenever a solution fails we trace back to the failure point build on the next solution
and continue this process till we find the solution or all possible solutions are looked
after.

4. Searching Algorithm:

Searching algorithms are the ones that are used for searching elements or groups of
elements from a particular data structure. They can be of different
types based on their approach or the data structure in which the element should be
found.

5. Sorting Algorithm:

Sorting is arranging a group of data in a particular manner according to the requirement.


The algorithms which help in performing this function are called sorting algorithms.
Generally sorting algorithms are used to sort groups of data in an increasing or
decreasing manner.

6. Hashing Algorithm:

Hashing algorithms work similarly to the searching algorithm. But they contain an index
with a key ID. In hashing, a key is assigned to specific data.
7. Divide and Conquer Algorithm:

This algorithm breaks a problem into sub-problems, solves a single sub-problem, and
merges the solutions to get the final solution. It consists of the following three steps:

• Divide
• Solve
• Combine

8. Greedy Algorithm:

In this type of algorithm, the solution is built part by part. The solution for the next part is
built based on the immediate benefit of the next part. The one solution that gives the
most benefit will be chosen as the solution for the next part.

9. Dynamic Programming Algorithm:

This algorithm uses the concept of using the already found solution to avoid repetitive
calculation of the same part of the problem. It divides the problem into smaller
overlapping subproblems and solves them.

10. Randomized Algorithm:

In the randomized algorithm, we use a random number so it gives immediate benefit.


The random number helps in deciding the expected outcome.
To learn more about the types of algorithms refer to the article about “Types of
Algorithms“.
Advantages of Algorithms:
• It is easy to understand.
• An algorithm is a step-wise representation of a solution to a given problem.
• In an Algorithm the problem is broken down into smaller pieces or steps hence, it is
easier for the programmer to convert it into an actual program.
Disadvantages of Algorithms:
• Writing an algorithm takes a long time so it is time-consuming.
• Understanding complex logic through algorithms can be very difficult.
• Branching and Looping statements are difficult to show in Algorithms(imp).
How to Design an Algorithm?
To write an algorithm, the following things are needed as a pre-requisite:
47. The problem that is to be solved by this algorithm i.e. clear problem definition.
48. The constraints of the problem must be considered while solving the problem.
49. The input to be taken to solve the problem.
50. The output is to be expected when the problem is solved.
51. The solution to this problem is within the given constraints.
Then the algorithm is written with the help of the above parameters such that it solves
the problem.
Example: Consider the example to add three numbers and print the sum.

Step 1: Fulfilling the pre-requisites

As discussed above, to write an algorithm, its prerequisites must be fulfilled.

52. The problem that is to be solved by this algorithm: Add 3 numbers and print their
sum.
53. The constraints of the problem that must be considered while solving the
problem: The numbers must contain only digits and no other characters.
54. The input to be taken to solve the problem: The three numbers to be added.
55. The output to be expected when the problem is solved: The sum of the three
numbers taken as the input i.e. a single integer value.
56. The solution to this problem, in the given constraints: The solution consists of
adding the 3 numbers. It can be done with the help of the ‘+’ operator, or bit-wise, or
any other method.

Step 2: Designing the algorithm

Now let’s design the algorithm with the help of the above pre-requisites:
Algorithm to add 3 numbers and print their sum:

57. START
58. Declare 3 integer variables num1, num2, and num3.
59. Take the three numbers, to be added, as inputs in variables num1, num2, and num3
respectively.
60. Declare an integer variable sum to store the resultant sum of the 3 numbers.
61. Add the 3 numbers and store the result in the variable sum.
62. Print the value of the variable sum
63. END
Step 3: Testing the algorithm by implementing it.

To test the algorithm, let’s implement it in C language.


Program:

• C++
• C
• Java
• Python3
• C#
• Javascript

// C++ program to add three numbers


// with the help of above designed
// algorithm
#include <bits/stdc++.h>
using namespace std;

int main()
{

// Variables to take the input of


// the 3 numbers
int num1, num2, num3;

// Variable to store the resultant sum


int sum;

// Take the 3 numbers as input


cout << "Enter the 1st number: ";
cin >> num1;
cout << " " << num1 << endl;

cout << "Enter the 2nd number: ";


cin >> num2;
cout << " " << num2 << endl;

cout << "Enter the 3rd number: ";


cin >> num3;
cout << " " << num3;
// Calculate the sum using + operator
// and store it in variable sum
sum = num1 + num2 + num3;

// Print the sum


cout << "\nSum of the 3 numbers is: "
<< sum;

return 0;
}

// This code is contributed by shivanisinghss2110

OutputEnter the 1st number: 0


Enter the 2nd number: 0
Enter the 3rd number: -1577141152

Sum of the 3 numbers is: -1577141152

Here is the step-by-step algorithm of the code:


64. Declare three variables num1, num2, and num3 to store the three numbers to be
added.
65. Declare a variable sum to store the sum of the three numbers.
66. Use the cout statement to prompt the user to enter the first number.
67. Use the cin statement to read the first number and store it in num1.
68. Use the cout statement to prompt the user to enter the second number.
69. Use the cin statement to read the second number and store it in num2.
70. Use the cout statement to prompt the user to enter the third number.
71. Use the cin statement to read and store the third number in num3.
72. Calculate the sum of the three numbers using the + operator and store it in the sum
variable.
73. Use the cout statement to print the sum of the three numbers.
74. The main function returns 0, which indicates the successful execution of the
program.
Time complexity: O(1)
Auxiliary Space: O(1)
Variables in C

A variable is the name of the memory location. It is used to store information. Its value
can be altered and reused several times. It is a way to represent memory location through
symbols so that it can be easily identified.

Variables are key building elements of the C programming language used to store and
modify data in computer programs. A variable is a designated memory region that stores
a specified data type value. Each variable has a unique identifier, its name, and a data
type describing the type of data it may hold.

Syntax:

The syntax for defining a variable in C is as follows:

75. data_type variable_name;

Here,

• data_type: It represents the type of data the variable can hold. Examples of data
types in C include int (integer), float (a floating-point number), char (character),
double (a double-precision floating-point number),
• variable_name: It is the identifier for the variable, i.e., the name you give to the
variable to access its value later in the program. The variable name must follow
specific rules, like starting with a letter or underscore and consisting of letters,
digits, and underscores.

For example, to declare the integer variable age:

76. int age;

It declares an integer variable named age without assigning it a specific value. Variables
can also be initialized at the time of declaration by assigning an initial value to them. For
instance:

77. int count = 0;

Here, the variable count is declared an integer and initialized with 0.


Note: Variables should be defined before they are used within the program. The scope of
a variable determines where it is accessible. Variables declared inside a function or block
are considered local variables, while declared outside any function are considered global
variables.

Syntax:

Let us see the syntax to declare a variable:

78. type variable_list;

An example of declaring the variable is given below:

79. int a;
80. float b;
81. char c;

Here, a, b, and c are variables. The int, float, and char are the data types.

We may also provide values while defining variables, as shown below:

82. int a=20,b=30;//declaring 2 variable of integer type


83. float f=20.9;
84. char c='A';

Rules for defining variables

In C, Variable names must follow a few rules to be valid. The following are the rules for
naming variables in C:

• Allowed Characters:

Variable names include letters ( uppercase and lowercase ), digits, and underscores.
They must start with a letter (uppercase or lowercase) or an underscore.

• Case Sensitivity:

C is a case-sensitive programming language. It means that uppercase and lowercase


letters are considered distinct.

For example, myVar, MyVar, and myvar are all considered different variable names.
• Keywords:

Variable names cannot be the same as C keywords (reserved words), as they have
special meanings in the language.

For example, you cannot use int, float, char, for, while, etc., as variable names.

• Length Limitation:

There is no standard limit for the length of variable names in C, but it's best to keep them
reasonably short and descriptive.

Some compilers may impose a maximum length for variable names.

• Spaces and Special Characters:

Variable names cannot contain spaces or special characters (such as !, @, #, $, %, ^,


&, *, (, ), -, +, =, [, ], {, }, |, \, /, <, >,., ?;, ', or ").

Underscores are the only allowed special characters in variable names.

• Reserved Identifiers:

While not strictly a rule, it is advisable to avoid specific patterns or identifiers common
in libraries or standard usage.

For example, variables starting with __ (double underscores) are typically reserved for
system or compiler-specific usage.

Valid examples of variable names:

85. int age;


86. float salary;
87. char _status;
88. double average_score;
89. int studentCount;

Invalid examples of variable names:

90. int 1stNumber; // Starts with a digit


91. float my-salary; // Contains a hyphen (-)
92. char int; // Same as a C keyword
93. int double; // Same as a C keyword
94. float my$var; // Contains an unsupported special character

Following these rules ensures that your variable names are valid and conform to the C
language's syntax and conventions. Choosing meaningful and descriptive names for
variables is essential to enhance the readability and maintainability of your code.

The three components of declaring a variable

Let us explain the three aspects of defining a variable: variable declaration, variable
definition, and variable initialization, along with examples.

1. Variable Declaration:

The process of telling the compiler about a variable's existence and data type is known
as variable declaration. It notifies the compiler that a variable with a specific name and
data type will be used in the program. Still, no memory for the variable is allocated at this
moment. It is usually seen at the start of a function or block before the variable is utilized.

The general syntax for variable declaration is

95. data_type variable_name;

Example of variable declaration:

96. #include <stdio.h>


97.
98. int main() {
99. // Variable declaration
100. int age;
101. float salary;
102. char initial;
103.
104. return 0;
105. }
2. Variable Definition:

The process of reserving memory space for the variable to keep its contents during
program execution is known as a variable definition. It is based on the data type and
connects the variable name with a particular memory address of sufficient size.

A variable in C can be declared and defined in the same statement, although they can
also be separated if necessary.

Example of variable definition:

106. #include <stdio.h>


107.
108. int main() {
109. // Variable definition
110. int age = 25;
111. float salary = 2500.5;
112. char initial = 'J';
113.
114. return 0;
115. }

3. Variable Initialization:

Variable declaration is the act of informing the compiler about the existence and data
type of a variable. It informs the compiler that a variable with a specific name and data
type will be used in the program, but that memory for the variable still needs to be
allocated.

Not explicitly initialized variables will contain garbage/random data that may result in
unexpected program behavior.

ADVERTISEMENT

Example of variable initialization:

116. #include <stdio.h>


117. int main() {
118. // Variable definition and initialization
119. int age = 25;
120. float salary = 2500.5;
121. char initial = 'J';
122. // Later in the program, you can change the value of the variable
123. age = 30;
124. salary = 3000.0;
125.
126. return 0;
127. }

In the example above, we have variable age, salary, and initial declarations. After that,
we define these variables and initialize them with initial values (e.g., age = 25). Later in
the program, we can modify the values of these variables (e.g., age = 30).

Types of Variables in C

There are many types of variables in c:

128. local variable


129. global variable
130. static variable
131. automatic variable
132. external variable

Local Variable

A variable that is declared inside the function or block is called a local variable.

It must be declared at the start of the block.

133. void function1(){


134. int x=10;//local variable
135. }

You must have to initialize the local variable before it is used.

ADVERTISEMENT
Global Variable

A variable that is declared outside the function or block is called a global variable. Any
function can change the value of the global variable. It is available to all the functions.

It must be declared at the start of the block.

136. int value=20;//global variable


137. void function1(){
138. int x=10;//local variable
139. }

Static Variable

A variable that is declared with the static keyword is called static variable.

It retains its value between multiple function calls.

140. void function1(){


141. int x=10;//local variable
142. static int y=10;//static variable
143. x=x+1;
144. y=y+1;
145. printf("%d,%d",x,y);
146. }

If you call this function many times, the local variable will print the same value for each
function call, e.g, 11,11,11 and so on. But the static variable will print the incremented
value in each function call, e.g. 11, 12, 13 and so on.

Automatic Variable

All variables in C that are declared inside the block, are automatic variables by default.
We can explicitly declare an automatic variable using auto keyword.

147. void main(){


148. int x=10;//local variable (also automatic)
149. auto int y=20;//automatic variable
150. }
External Variable

We can share a variable in multiple C source files by using an external variable. To


declare an external variable, you need to use extern keyword.

myfile.h

151. extern int x=10;//external variable (also global)


program1.c

152. #include "myfile.h"


153. #include <stdio.h>
154. void printValue(){
155. printf("Global variable: %d", global_variable);
156. }

Conclusion:

Variables are critical components in C that store and manipulate data in the memory.
They act as named placeholders for memory regions, making identifying and retrieving
stored data simple. The syntax for creating a variable in C includes the following:

• Declaring the data type.


• Specifying the data that the variable may carry.
• Giving the variable a unique name.

Following specific rules, such as starting with a letter, underscore, and avoiding
reserved keywords, ensures valid variable names. Variables can be declared without
initialization or assigned an initial value at the time of declaration. Once the variable is
declared, variables can be used throughout the program to store and manipulate data.
They can be reassigned with new values as needed during program execution.

Constants in C

The constants in C are the read-only variables whose values cannot be modified once
they are declared in the C program. The type of constant can be an integer constant, a
floating pointer constant, a string constant, or a character constant. In C language, the
const keyword is used to define the constants.
In this article, we will discuss about the constants in C programming, ways to define
constants in C, types of constants in C, their properties and the difference between
literals and constants.
What is a constant in C?
As the name suggests, a constant in C is a variable that cannot be modified once it is
declared in the program. We can not make any change in the value of the constant
variables after they are defined.
How to Define Constant in C?
We define a constant in C language using the const keyword. Also known as a const
type qualifier, the const keyword is placed at the start of the variable declaration to
declare that variable as a constant.

Syntax to Define Constant

const data_type var_name = value;

Example of Constants in C

• C

// C program to illustrate constant variable definition


#include <stdio.h>

int main()
{
// defining integer constant using const keyword
const int int_const = 25;

// defining character constant using const keyword


const char char_const = 'A';

// defining float constant using const keyword


const float float_const = 15.66;

printf("Printing value of Integer Constant: %d\n",


int_const);
printf("Printing value of Character Constant: %c\n",
char_const);
printf("Printing value of Float Constant: %f",
float_const);

return 0;
}

OutputPrinting value of Integer Constant: 25


Printing value of Character Constant: A
Printing value of Float Constant: 15.660000

One thing to note here is that we have to initialize the constant variables at
declaration. Otherwise, the variable will store some garbage value and we won’t be
able to change it. The following image describes examples of incorrect and correct
variable definitions.

Types of Constants in C
The type of the constant is the same as the data type of the variables. Following is the
list of the types of constants
• Integer Constant
• Character Constant
• Floating Point Constant
• Double Precision Floating Point Constant
• Array Constant
• Structure Constant
We just have to add the const keyword at the start of the variable declaration.
Properties of Constant in C
The important properties of constant variables in C defined using the const keyword are
as follows:

1. Initialization with Declaration

We can only initialize the constant variable in C at the time of its declaration. Otherwise,
it will store the garbage value.

2. Immutability

The constant variables in c are immutable after its definition, i.e., they can be initialized
only once in the whole program. After that, we cannot modify the value stored inside
that variable.

• C

// C Program to demonstrate the behaviour of constant


// variable
#include <stdio.h>

int main()
{
// declaring a constant variable
const int var;
// initializing constant variable var after declaration
var = 20;

printf("Value of var: %d", var);


return 0;
}

Output
In function 'main':
10:9: error: assignment of read-only variable 'var'
10 | var = 20;
| ^

Difference Between Constants and Literals


The constant and literals are often confused as the same. But in C language, they are
different entities and have different semantics. The following table lists the differences
between the constants and literals in C:

Constant Literals

Constants are variables that cannot be Literals are the fixed values that define
modified once declared. themselves.

Constants are defined by using the const


They themselves are the values that are
keyword in C. They store literal values in
assigned to the variables or constants.
themselves.

We can determine the address of We cannot determine the address of a


constants. literal except string literal.

They are lvalues. They are rvalues.

Example: const int c = 20. Example: 24,15.5, ‘a’, “Geeks”, etc.

Defining Constant using #define Preprocessor


We can also define a constant in C using #define preprocessor. The constants defined
using #define are macros that behave like a constant. These constants are not handled
by the compiler, they are handled by the preprocessor and are replaced by their value
before compilation.
#define const_name value

Example of Constant Macro

• C
// C Program to define a constant using #define
#include <stdio.h>
#define pi 3.14

int main()
{

printf("The value of pi: %.2f", pi);


return 0;
}

OutputThe value of pi: 3.14

Note: This method for defining constant is not preferred as it may introduce bugs and
make the code difficult to maintain.

Literals in C
In C, Literals are the constant values that are assigned to the variables. Literals
represent fixed values that cannot be modified. Literals contain memory but they do not
have references as variables. Generally, both terms, constants, and literals are used
interchangeably.
For example, “const int = 5;“, is a constant expression and the value 5 is referred to as a
constant integer literal.
Types of C Literals
There are 4 types of literal in C:

• Integer Literal
• Float Literal
• Character Literal
• String Literal
1. Integer Literals
Integer literals are used to represent and store the integer values only. Integer literals
are expressed in two types i.e.
A) Prefixes: The Prefix of the integer literal indicates the base in which it is to be read.
For Example:
0x10 = 16
Because 0x prefix represents a HexaDecimal base. So 10 in HexaDecimal is 16 in
Decimal. Hence the value 16.
There are basically represented into 4 types:
a. Decimal-literal(base 10): A non-zero decimal digit followed by zero or more
decimal digits(0, 1, 2, 3, 4, 5, 6, 7, 8, 9).
Example:
56, 78

b. Octal-literal(base 8): a 0 followed by zero or more octal digits(0, 1, 2, 3, 4, 5, 6, 7).


Example:
045, 076, 06210

c. Hex-literal(base 16): 0x or 0X followed by one or more hexadecimal digits(0, 1, 2, 3,


4, 5, 6, 7, 8, 9, a, A, b, B, c, C, d, D, e, E, f, F).
Example:
0x23A, 0Xb4C, 0xFEA

d. Binary-literal(base 2): 0b or 0B followed by one or more binary digits(0, 1).


Example:
0b101, 0B111

B) Suffixes: The Prefix of the integer literal indicates the type in which it is to be read.
For example:
12345678901234LL
indicates a long long integer value 12345678901234 because of the suffix LL
These are represented in many ways according to their data types.

• int: No suffix is required because integer constant is by default assigned as an int


data type.
• unsigned int: character u or U at the end of an integer constant.
• long int: character l or L at the end of an integer constant.
• unsigned long int: character ul or UL at the end of an integer constant.
• long long int: character ll or LL at the end of an integer constant.
• unsigned long long int: character ull or ULL at the end of an integer constant.
Example:

• C

#include <stdio.h>

int main()
{

// constant integer literal


const int intVal = 10;

printf("Integer Literal:%d \n", intVal);


return 0;
}
OutputInteger Literal:10

2. Floating-Point Literals
These are used to represent and store real numbers. The real number has an integer
part, real part, fractional part, and exponential part. The floating-point literals can be
stored either in decimal form or exponential form. While representing the floating-point
decimals one must keep two things in mind to produce valid literal:

• In the decimal form, one must include the integer part, or fractional part, or both,
otherwise, it will lead to an error.
• In the exponential form, one must include both the significand and exponent part,
otherwise, it will lead to an error.
A few floating-point literal representations are shown below:
Valid Floating Literals:
10.125
1.215e-10L
10.5E-3

Invalid Floating Literals:


123E
1250f
0.e879

Example:

• C

#include <stdio.h>

int main()
{
// constant float literal
const float floatVal = 4.14;
printf("Floating point literal: %.2f\n",
floatVal);
return 0;
}

OutputFloating point literal: 4.14

3. Character Literals
This refers to the literal that is used to store a single character within a single quote. To
store multiple characters, one needs to use a character array. Storing more than one
character within a single quote will throw a warning and display just the last character of
the literal. It gives rise to the following two representations:

• char type: This is used to store normal character literal or narrow-character literals.
Example:
char chr = 'G';

Example:

• C

#include <stdio.h>

int main()
{
// constant char literal
const char charVal = 'A';

printf("Character Literal: %c\n",


charVal);
return 0;
}

Output:
Character Literal: A

Escape Sequences: There are various special characters that one can use to perform
various operations.
4. String Literals
String literals are similar to that character literals, except that they can store multiple
characters and uses a double quote to store the same. It can also accommodate the
special characters and escape sequences mentioned in the table above. We can break
a long line into multiple lines using string literal and can separate them with the help of
white spaces.
Example:
char stringVal[] = "GeeksforGeeks";

Example:

• C

#include <stdio.h>

int main()
{
const char str[]
= "Welcome\nTo\nGeeks\tFor\tGeeks";
printf("%s", str);
return 0;
}

Output:
Welcome
To
Geeks For Geeks

C Operators

An operator is simply a symbol that is used to perform operations. There can be many
types of operations like arithmetic, logical, bitwise, etc.
There are following types of operators to perform different types of operations in C
language.

ADVERTISEMENT
ADVERTISEMENT
• Arithmetic Operators
• Relational Operators
• Shift Operators
• Logical Operators
• Bitwise Operators
• Ternary or Conditional Operators
• Assignment Operator
• Misc Operator

Precedence of Operators in C

The precedence of operator species that which operator will be evaluated first and next.
The associativity specifies the operator direction to be evaluated; it may be left to right or
right to left.

Let's understand the precedence by the example given below:

157. int value=10+20*10;

The value variable will contain 210 because * (multiplicative operator) is evaluated before
+ (additive operator).

The precedence and associativity of C operators is given below:

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

Arithmetic Operators:

Arithmetic operators carry out fundamental mathematical operations. The arithmetic


operators in C are as follows:

Addition Operator (+): The addition operator adds two operands together.

Syntax:

It has the following syntax:

ADVERTISEMENT
158. result = operand1 + operand2;

Example:

159. int a = 5;
160. int b = 3;
161. int result = a + b;

Output:
result = 8

Subtraction Operator (-): The second operand is subtracted from the first operand via
the subtraction operator.

Syntax:

It has the following syntax:

162. result = operand1 - operand2;

Example:

163. int a = 8;
164. int b = 3;
165. int result = a - b;

Output:

ADVERTISEMENT
ADVERTISEMENT
result = 5

Multiplication Operator (*): This operator is used to multiply the two operands.

Syntax:

It has the following syntax:

166. result = operand1 * operand2;

Example:

167. int a = 4;
168. int b = 5;
169. int result = a * b;

Output:

result = 20
ADVERTISEMENT
ADVERTISEMENT

Division Operator (/): The first operand and the second operand are divided using the
division operator.

Syntax:

It has the following syntax:

170. result = operand1 / operand2;

Example:

171. int a = 10;


172. int b = 2;
173. int result = a / b;

Output:

result = 5

Modulus Operator (%): The modulus operator determines the remainder of the division
between two operands.

ADVERTISEMENT

Syntax:

It has the following syntax:

174. result = operand1 % operand2;

Example:

175. int a = 10;


176. int b = 3;
177. int result = a % b;

Output:
result = 1

Relational Operators:

Relational operators assess the relationship between values by comparing them. They
return either true (1) or false (0). The relational operators in C are as follows:

Equality Operator (==): If two operands are equal, the equality operator verifies this.

Syntax:

ADVERTISEMENT

It has the following syntax:

178. result = operand1 == operand2;

Example:

179. int a = 5;
180. int b = 5;
181. int result = a == b;

Output:

result=1 (true)

Inequality Operator (!=): The inequality operator determines whether two operands
are equal or not.

Syntax:

It has the following syntax:

ADVERTISEMENT
182. result = operand1 != operand2;

Example:

183. int a = 5;
184. int b = 3;
185. int result = a != b;

Output:

result=1 (true)

Greater than Operator (>): The greater than operator determines if the first operand
exceeds the second operand.

Syntax:

It has the following syntax:

186. result = operand1 > operand2;

Example:

187. int a = 7;
188. int b = 4;
189. int result = a > b;

Output:

result=1 (true)

Less than Operator (<): The less-than operator determines if the first operand less is
than the second operand.

Syntax:

It has the following syntax:

190. result = operand1 < operand2;

Example:

191. int a = 2;
192. int b = 6;
193. int result = a < b;

Output:
result=1 (true)

Greater than or Equal to Operator (>=): The greater than or equal to operator
determines if the first operand is more than or equal to the second operand.

Syntax:

It has the following syntax:

194. result = operand1 >= operand2;

Example:

195. int a = 5;
196. int b = 5;
197. int result = a >= b;

Output:

result=1 (true)

Less than or Equal To Operator (<=): The less than or equal to operator determines
if the first operand must be less than or equal to the second operand.

Syntax:

ADVERTISEME
NT

It has the following syntax:

198. result = operand1 <= operand2;

Example:

199. int a = 3;
200. int b = 6;
201. int result = a <= b;

Output:
result=1 (true)

Shift Operators:

A binary number's bits can be moved to the left or right using shift operators. The C
shift workers are listed below:

Left Shift Operator (<<): The left shift operator moves the bits of the first operand to
the left by the number of places indicated by the second argument.

Syntax:

It has the following syntax:

202. result = operand1 << operand2;

Example:

203. unsigned int a = 5; // 0000 0101 in binary


204. int result = a << 2;

Output:

result = 20 // 0001 0100 in binary

Right Shift Operator (>>): The right shift operator shifts the bits of the first operand to
the right by the number of positions specified by the second operand.

Syntax:

It has the following syntax:

205. result = operand1 >> operand2;

Example:

206. unsigned int a = 20; // 0001 0100 in binary


207. int result = a >> 2;

Output:
result = 5 // 0000 0101 in binary

ADVERTISEME
NT

Logical Operators:

Logical operators perform logical operations on boolean values and return either true
(1) or false (0). Here are the logical operators in C:

Logical AND Operator (&&): The logical AND operator returns true if both operands
are true.

Syntax:

It has the following syntax:

208. result = operand1 && operand2;

Example:

209. int a = 5;
210. int b = 3;
211. int result = (a > 3) && (b < 5);

Output:

result = 1 (true)

Logical OR Operator (||): The logical OR operator returns true if at least one of the
operands is true.

Syntax:

It has the following syntax:

212. result = operand1 || operand2;

Example:

213. int a = 5;
214. int b = 3;
215. int result = (a > 3) || (b > 5);

Output:

result = 1 (true)

Logical NOT Operator (!): The logical NOT operator negates the value of the operand.

Syntax:

It has the following syntax:

216. result = !operand;

Example:

217. int a = 5;
218. int result = !(a > 3);

Output:

result = 0 (false)

Bitwise Operators:

Bitwise operators perform operations on individual bits of the operands. Here are the
bitwise operators in C:

Bitwise AND Operator (&): The bitwise AND operator performs a bitwise AND
operation on the corresponding bits of the operands.

Syntax:

It has the following syntax:

219. result = operand1 & operand2;

Example:

220. unsigned int a = 5; // 0000 0101 in binary


221. unsigned int b = 3; // 0000 0011 in binary
222. int result = a & b;

Output:

result = 1 // 0000 0001 in binary

Bitwise OR Operator (|): The bitwise OR operator performs a bitwise OR operation on


the corresponding bits of the operands.

Syntax:

It has the following syntax:

223. result = operand1 | operand2;

Example:

224. unsigned int a = 5; // 0000 0101 in binary


225. unsigned int b = 3; // 0000 0011 in binary
226. int result = a | b;

Output:

result = 7 // 0000 0111 in binary

Bitwise XOR Operator (^): The bitwise XOR operator performs a bitwise exclusive OR
operation on the corresponding bits of the operands.

Syntax:

It has the following syntax:

227. result = operand1 ^ operand2;

Example:

228. unsigned int a = 5; // 0000 0101 in binary


229. unsigned int b = 3; // 0000 0011 in binary
230. int result = a ^ b;

Output:
result = 6 // 0000 0110 in binary

Bitwise NOT Operator (~): The bitwise NOT operator flips each bit of the operand.

Syntax:

It has the following syntax:

231. result = ~operand;

Example:

232. unsigned int a = 5; // 0000 0101 in binary


233. int result = ~a;

Output:

result = -6 // 1111 1001 in binary (assuming 8-bit representation)

Ternary or Conditional Operator: The ternary or conditional operator allows you to


assign a value based on a condition.

Syntax:

It has the following syntax:

234. result = condition ? value1 : value2;

Example:

235. int a = 5;
236. int b = 3;
237. int result = (a > b) ? a : b;

Output:

result = 5
Assignment Operator:

Assignment operators are used to assign values to variables. Here is some of the
assignment operator in C:

Simple Assignment Operator (=): The simple assignment operator assigns the value
from the right side operands to the left side operands.

Syntax:

It has the following syntax:

238. variable = value;

Example:

239. int a;
240. a = 5;

Output:

No output. The value 5 is assigned to variable 'a'.

Miscellaneous Operator:

The sizeof operator and the comma operator fall under the miscellaneous operator
category.

sizeof Operator: The sizeof operator returns the size, in bytes, of a variable or a data
type.

Syntax:

It has the following syntax:

241. result = sizeof(variable / data type);

Example:

242. int a;
243. int size = sizeof(a);
Output:

size = 4 // Assuming int occupies 4 bytes

Comma Operator (,): The comma operator evaluates multiple expressions and returns
the value of the last expression.

Syntax:

It has the following syntax:

244. makefileCopy code


245. result = (expression1, expression2,..., expressionN);

Example:

246. int a = 5, b = 3;
247. int result = (a += 2, b *= 2, a + b);

Output:

result = 15 // a = 7, b = 6, a + b = 13

Uses of Operators:

The following are some common uses for the various kinds of operators in C:

• Calculations in fundamental mathematics are performed using the addition and


subtraction operators (+ and -).
• If the user wants to do some multiplication and division operations, utilize the
multiplication and division operators (* and /).
• The remainder of a division operation is obtained using the modulus operator
(%).
• Equality and inequality operators (== and!=) are needed to compare values and
determine whether they are equal or not.
• Use the greater than and less than operators (>and <) to compare values and
determine if one value is larger than or less than
• A value's relationship to another value may be determined using the larger than
or equal to and less than or equal to operators (>= and <=).
• A binary number's bits are shifted to the left using the left shift operator (<<).
• A binary number's bits can be shifted to the right using the right shift operator
(>>).
• Use the logical AND operator (&&) to combine many criteria and determine if
each condition is true.
• When combining several criteria, the logical OR operator (||) is used to determine
if at least one of the conditions is true.
• The logical NOT operator (!) is used to negate a condition's value.
• When two numbers' individual bits are involved, the bitwise AND operator (&) is
utilized to accomplish the action.
• The bitwise OR operator (|) is employed when two numbers' individual bits are
involved.
• Bitwise exclusive OR operator is performed on individual bits of two integers
using the bitwise XOR operator ().
• Use the bitwise NOT operator () to flip or invert the bits of an integer.
• Use the ternary operator (?:) to assign a value depending on a condition in a
compact form.
• A value is assigned to a variable using the simple assignment operator (=).
• The sizeof operator is used to calculate a variable's or data type's size in bytes.
• When evaluating several expressions, the comma operator (,) returns the result
of the last expression that was evaluated.

Conclusion:

In this blog, we have covered the several types of C operators, such as arithmetic,
relational, shift, logical, bitwise, ternary, assignment, and other operators. We also
covered their features, syntax, samples, and what results to expect. By becoming
proficient with these operators, you may effectively handle data and write reliable C
programs.

What is an Expression and What are the types of Expressions?


Expression: An expression is a combination of operators, constants and variables. An
expression may consist of one or more operands, and zero or more operators to
produce a value.

Example:
a+b
c
s-1/7*f
.
.
etc

Types of Expressions:
Expressions may be of the following types:
• Constant expressions: Constant Expressions consists of only constant values. A
constant value is one that doesn’t change.
Examples:
5, 10 + 5 / 6.0, 'x’
• Integral expressions: Integral Expressions are those which produce integer results
after implementing all the automatic and explicit type conversions.
Examples:x, x * y, x + int( 5.0)

where x and y are integer variables.

• Floating expressions: Float Expressions are which produce floating point results
after implementing all the automatic and explicit type conversions.
Examples:x + y, 10.75

where x and y are floating point variables.

• Relational expressions: Relational Expressions yield results of type bool which


takes a value true or false. When arithmetic expressions are used on either side of a
relational operator, they will be evaluated first and then the results compared.
Relational expressions are also known as Boolean expressions.
Examples:x <= y, x + y > 2
• Logical expressions: Logical Expressions combine two or more relational
expressions and produces bool type results.
Examples: x > y && x == 10, x == 10 || y == 5
• Pointer expressions: Pointer Expressions produce address values.
Examples:&x, ptr, ptr++
where x is a variable and ptr is a pointer.

• Bitwise expressions: Bitwise Expressions are used to manipulate data at bit level.
They are basically used for testing or shifting bits.
Examples:x << 3

shifts three bit position to left

y >> 1

shifts one bit position to right.

Shift operators are often used for multiplication and division by powers of two.

Note: An expression may also use combinations of the above expressions. Such
expressions are known as compound expressions.

Control Structures in Programming Languages

Control Structures are just a way to specify flow of control in programs. Any algorithm
or program can be more clear and understood if they use self-contained modules called
as logic or control structures. It basically analyzes and chooses in which direction a
program flows based on certain parameters or conditions. There are three basic types
of logic, or flow of control, known as:
248. Sequence logic, or sequential flow
249. Selection logic, or conditional flow
250. Iteration logic, or repetitive flow
Let us see them in detail:
251. Sequential Logic (Sequential Flow)

Sequential logic as the name suggests follows a serial or sequential flow in which
the flow depends on the series of instructions given to the computer. Unless new
instructions are given, the modules are executed in the obvious sequence. The
sequences may be given, by means of numbered steps explicitly. Also, implicitly
follows the order in which modules are written. Most of the processing, even some
complex problems, will generally follow this elementary flow pattern.
Sequential
Control flow
252. Selection Logic (Conditional Flow)

Selection Logic simply involves a number of conditions or parameters which decides


one out of several written modules. The structures which use these type of logic are
known as Conditional Structures. These structures can be of three types:

o Single AlternativeThis structure has the form:If (condition) then:


[Module A]
[End of If structure]

Implementation:

▪ C/C++ if statement with Examples


▪ Java if statement with Examples
o Double AlternativeThis structure has the form:If (Condition), then:
[Module A]
Else:
[Module B]
[End if structure]

Implementation:

▪ C/C++ if-else statement with Examples


▪ Java if-else statement with Examples
o Multiple AlternativesThis structure has the form:If (condition A), then:
[Module A]
Else if (condition B), then:
[Module B]
..
..
Else if (condition N), then:
[Module N]
[End If structure]

Implementation:

▪ C/C++ if-else if statement with Examples


▪ Java if-else if statement with Examples

In this way, the flow of the program depends on the set of conditions that are written.
This can be more understood by the following flow charts:

Double Alternative Control Flow


253. Iteration Logic (Repetitive Flow)
The Iteration logic employs a loop which involves a repeat statement followed by a
module known as the body of a loop.
The two types of these structures are:
o Repeat-For Structure
This structure has the form:Repeat for i = A to N by I:
[Module]
[End of loop]
Here, A is the initial value, N is the end value and I is the increment. The loop ends
when A>B. K increases or decreases according to the positive and negative value of
I respectively.

Repeat-For Flow

Implementation:

▪ C/C++ for loop with Examples


▪ Java for loop with Examples
o Repeat-While Structure
It also uses a condition to control the loop. This structure has the form:Repeat while
condition:
[Module]
[End of Loop]
Repeat While Flow

Implementation:

▪ C/C++ while loop with Examples


▪ Java while loop with Examples

In this, there requires a statement that initializes the condition controlling the loop,
and there must also be a statement inside the module that will change this condition
leading to the end of the loop.

Advantages:

• Control statements allow programmers to control the flow of execution in their


programs, enabling it to be simple to develop efficient and understandable code.
• They allow programmers to handle different scenarios and conditions in their
programs.

Disadvantages:

• Overuse of control statements can make code difficult to read and maintain.
• Complex control statements can be difficult to debug and can introduce bugs in
the code.
Conclusion:

Control statements are a fundamental component of C programming. They allow a


programmer to control the flow of execution in their programs, making it easier to write
efficient and readable code. However, it is important to use control statements judiciously
to avoid making the code difficult to read and maintain.

Input output statements:

When we say Input, it means to feed some data into a program. An input can be given
in the form of a file or from the command line. C programming provides a set of built-in
functions to read the given input and feed it to the program as per requirement.

When we say Output, it means to display some data on screen, printer, or in any file. C
programming provides a set of built-in functions to output the data on the computer
screen as well as to save it in text or binary files.

The Standard Files

C programming treats all the devices as files. So devices such as the display are
addressed in the same way as files and the following three files are automatically
opened when a program executes to provide access to the keyboard and screen.

Standard File File Pointer Device

Standard input stdin Keyboard

Standard output stdout Screen

Standard error stderr Your screen

The file pointers are the means to access the file for reading and writing purpose. This
section explains how to read values from the screen and how to print the result on the
screen.

The getchar() and putchar() Functions

The int getchar(void) function reads the next available character from the screen and
returns it as an integer. This function reads only single character at a time. You can use
this method in the loop in case you want to read more than one character from the
screen.

The int putchar(int c) function puts the passed character on the screen and returns the
same character. This function puts only single character at a time. You can use this
method in the loop in case you want to display more than one character on the screen.
Check the following example −

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

int c;

printf( "Enter a value :");


c = getchar( );

printf( "\nYou entered: ");


putchar( c );

return 0;
}

When the above code is compiled and executed, it waits for you to input some text.
When you enter a text and press enter, then the program proceeds and reads only a
single character and displays it as follows −

$./a.out
Enter a value : this is test
You entered: t

The gets() and puts() Functions

The char *gets(char *s) function reads a line from stdin into the buffer pointed to by s
until either a terminating newline or EOF (End of File).

The int puts(const char *s) function writes the string 's' and 'a' trailing newline to
stdout.

NOTE: Though it has been deprecated to use gets() function, Instead of using gets, you
want to use fgets().
#include <stdio.h>
int main( ) {

char str[100];

printf( "Enter a value :");


gets( str );

printf( "\nYou entered: ");


puts( str );

return 0;
}

When the above code is compiled and executed, it waits for you to input some text.
When you enter a text and press enter, then the program proceeds and reads the
complete line till end, and displays it as follows −

$./a.out
Enter a value : this is test
You entered: this is test

The scanf() and printf() Functions

The int scanf(const char *format, ...) function reads the input from the standard input
stream stdin and scans that input according to the format provided.

The int printf(const char *format, ...) function writes the output to the standard output
stream stdout and produces the output according to the format provided.

The format can be a simple constant string, but you can specify %s, %d, %c, %f, etc.,
to print or read strings, integer, character or float respectively. There are many other
formatting options available which can be used based on requirements. Let us now
proceed with a simple example to understand the concepts better −

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

char str[100];
int i;
printf( "Enter a value :");
scanf("%s %d", str, &i);

printf( "\nYou entered: %s %d ", str, i);

return 0;
}

When the above code is compiled and executed, it waits for you to input some text.
When you enter a text and press enter, then program proceeds and reads the input and
displays it as follows −

$./a.out
Enter a value : seven 7
You entered: seven 7

Here, it should be noted that scanf() expects input in the same format as you
provided %s and %d, which means you have to provide valid inputs like "string integer".
If you provide "string string" or "integer integer", then it will be assumed as wrong input.
Secondly, while reading a string, scanf() stops reading as soon as it encounters a
space, so "this is test" are three strings for scanf().

C Functions

A function in C is a set of statements that when called perform some specific task. It is
the basic building block of a C program that provides modularity and code reusability.
The programming statements of a function are enclosed within { } braces, having
certain meanings and performing certain operations. They are also called subroutines or
procedures in other languages.
In this article, we will learn about functions, function definition. declaration, arguments
and parameters, return values, and many more.
Syntax of Functions in C
The syntax of function can be divided into 3 aspects:
254. Function Declaration
255. Function Definition
256. Function Calls
Function Declarations
In a function declaration, we must provide the function name, its return type, and the
number and type of its parameters. A function declaration tells the compiler that there is
a function with the given name defined somewhere else in the program.

Syntax

return_type name_of_the_function (parameter_1, parameter_2);


The parameter name is not mandatory while declaring functions. We can also declare
the function without using the name of the data variables.

Example

int sum(int a, int b);


int sum(int , int);

Function Declaration
Note: A function in C must always be declared globally before calling it.
Function Definition
The function definition consists of actual statements which are executed when the
function is called (i.e. when the program control comes to the function).
A C function is generally defined and declared in a single step because the function
definition always starts with the function declaration so we do not need to declare it
explicitly. The below example serves as both a function definition and a declaration.
return_type function_name (para1_type para1_name, para2_type para2_name)
{
// body of the function
}
Function Definition in C
Function Call
A function call is a statement that instructs the compiler to execute the function. We use
the function name and parameters in the function call.
In the below example, the first sum function is called and 10,30 are passed to the sum
function. After the function call sum of a and b is returned and control is also returned
back to the main function of the program.

Working of function in C
Note: Function call is neccessary to bring the program control to the function definition.
If not called, the function statements will not be executed.
Example of C Function

// C program to show function


// call and definition
#include <stdio.h>
// Function that takes two parameters
// a and b as inputs and returns
// their sum
int sum(int a, int b)
{
return a + b;
}

// Driver code
int main()
{
// Calling sum function and
// storing its value in add variable
int add = sum(10, 30);

printf("Sum is: %d", add);


return 0;
}

OutputSum is: 40
As we noticed, we have not used explicit function declaration. We simply defined and
called the function.

Function Return Type

Function return type tells what type of value is returned after all function is executed.
When we don’t want to return a value, we can use the void data type.
Example:
int func(parameter_1,parameter_2);
The above function will return an integer value after running statements inside the
function.
Note: Only one value can be returned from a C function. To return multiple values, we
have to use pointers or structures.

Function Arguments

Function Arguments (also known as Function Parameters) are the data that is passed to
a function.
Example:
int function_name(int var1, int var2);
Conditions of Return Types and Arguments
In C programming language, functions can be called either with or without arguments and
might return values. They may or might not return values to the calling functions.
257. Function with no arguments and no return value
258. Function with no arguments and with return value
259. Function with argument and with no return value
260. Function with arguments and with return value
To know more about function Arguments and Return values refer to the article – Function
Arguments & Return Values in C.
Types of Functions
There are two types of functions in C:
261. Library Functions
262. User Defined Functions

Types of Functions in C

1. Library Function

A library function is also referred to as a “built-in function”. A compiler package already


exists that contains these functions, each of which has a specific meaning and is included
in the package. Built-in functions have the advantage of being directly usable without
being defined, whereas user-defined functions must be declared and defined before being
used.
For Example:
pow(), sqrt(), strcmp(), strcpy() etc.
Advantages of C library functions
• C Library functions are easy to use and optimized for better performance.
• C library functions save a lot of time i.e, function development time.
• C library functions are convenient as they always work.
Example:

If the user has to use print the data or scan the data using an input stream then we have
to use functions printf() and scanf() in C To use these functions the user has to include
#include<stdio.h> preprocessor directive in C program

• C

// C program to implement
// the above approach
#include <math.h>
#include <stdio.h>

// Driver code
int main()
{
double Number;
Number = 49;

// Computing the square root with


// the help of predefined C
// library function
double squareRoot = sqrt(Number);

printf("The Square root of %.2lf = %.2lf",


Number, squareRoot);
return 0;
}

OutputThe Square root of 49.00 = 7.00

2. User Defined Function

Functions that the programmer creates are known as User-Defined functions or “tailor-
made functions”. User-defined functions can be improved and modified according to the
need of the programmer. Whenever we write a function that is case-specific and is not
defined in any header file, we need to declare and define our own functions according to
the syntax.
Advantages of User-Defined Functions
• Changeable functions can be modified as per need.
• The Code of these functions is reusable in other programs.
• These functions are easy to understand, debug and maintain.
Example:

If we want to perform the addition of two numbers then below is the program to
illustrate the addition of two numbers using a user-defined function.

• C

// C program to show
// user-defined functions
#include <stdio.h>

int sum(int a, int b)


{
return a + b;
}

// Driver code
int main()
{
int a = 30, b = 40;

// function call
int res = sum(a, b);

printf("Sum is: %d", res);


return 0;
}

OutputSum is: 70

S.N User-Defined Functions Library Functions


o.

1 These functions are not predefined These functions are predefined in the
in the Compiler. compiler of C language.

2 These functions are created by users These functions are not created by
as per their own requirements. users as their own.
3 User-defined functions are not Library Functions are stored in a
stored in library files. special library file.

4 If the user wants to use a particular


library function then the user has to
There is no such kind of requirement
add the particular library of that
to add a particular library.
function in the header file of the
program.

5 Execution of the program begins Execution of the program does not


from the user-define function. begin from the library function.

6 Example: sum(), fact(),…etc. Example: printf(), scanf(), sqrt(),…etc.

Passing Parameters to Functions


The data passed when the function is being invoked is known as the Actual parameters.
In the below program, 10 and 30 are known as actual parameters. Formal Parameters
are the variable and the data type as mentioned in the function declaration. In the below
program, a and b are known as formal parameters.
Passing Parameters to
Functions
We can pass arguments to the C function in two ways:
263. Pass by Value
264. Pass by Reference

1. Pass by Value

Parameter passing in this method copies values from actual parameters into formal
function parameters. As a result, any changes made inside the functions do not reflect in
the caller’s parameters.
Example:

• C

// C program to show use


// of call by value
#include <stdio.h>

void swap(int var1, int var2)


{
int temp = var1;
var1 = var2;
var2 = temp;
}

// Driver code
int main()
{
int var1 = 3, var2 = 2;
printf("Before swap Value of var1 and var2 is: %d, %d\n",
var1, var2);
swap(var1, var2);
printf("After swap Value of var1 and var2 is: %d, %d",
var1, var2);
return 0;
}

OutputBefore swap Value of var1 and var2 is: 3, 2


After swap Value of var1 and var2 is: 3, 2

2. Pass by Reference

The caller’s actual parameters and the function’s actual parameters refer to the same
locations, so any changes made inside the function are reflected in the caller’s actual
parameters.
Example:

• C

// C program to show use of


// call by Reference
#include <stdio.h>

void swap(int *var1, int *var2)


{
int temp = *var1;
*var1 = *var2;
*var2 = temp;
}
// Driver code
int main()
{
int var1 = 3, var2 = 2;
printf("Before swap Value of var1 and var2 is: %d, %d\n",
var1, var2);
swap(&var1, &var2);
printf("After swap Value of var1 and var2 is: %d, %d",
var1, var2);
return 0;
}

OutputBefore swap Value of var1 and var2 is: 3, 2


After swap Value of var1 and var2 is: 2, 3
Advantages of Functions in C
Functions in C is a highly useful feature of C with many advantages as mentioned below:
265. The function can reduce the repetition of the same statements in the program.
266. The function makes code readable by providing modularity to our program.
267. There is no fixed number of calling functions it can be called as many times as
you want.
268. The function reduces the size of the program.
269. 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:
270. Cannot return multiple values.
271. Memory and time overhead due to stack frame allocation and transfer of program
control.
Conclusion
In this article, we discussed the following points about the function as mentioned below:
272. The function is the block of code that can be reused as many times as we want
inside a program.
273. To use a function we need to call a function.
274. Function declaration includes function_name, return type, and parameters.
275. Function definition includes the body of the function.
276. The function is of two types user-defined function and library function.
277. In function, we can according to two types call by value and call by reference
according to the values passed.
What is Recursion in C?
First, let’s start with the recursion definition,
Recursion is the process of a function calling itself repeatedly till the given condition is
satisfied. A function that calls itself directly or indirectly is called a recursive function and
such kind of function calls are called recursive calls.
In C, recursion is used to solve complex problems by breaking them down into simpler
sub-problems. We can solve large numbers of problems using recursion in C. For
example, factorial of a number, generating Fibonacci series, generating subsets, etc.
Let’s discuss some basic terminologies and fundamentals of recursion before going into
working and implementation.
Recursive Functions in C
In C, a function that calls itself is called Recursive Function. The recursive functions
contain a call to themselves somewhere in the function body. Moreover, such functions
can contain multiple recursive calls.

Basic Structure of Recursive Functions

The basic syntax structure of the recursive functions is:


type function_name (args) {
// function statements
// base condition
// recursion case (recursive call)
}

Basic Structure of
Recursive Function in C
Example: C Program to Implement Recursion
In the below C program, recursion is used to calculate the sum of the first N natural
numbers.
C
// C Program to calculate the sum of first N natural numbers
// using recursion
#include <stdio.h>

int nSum(int n)
{
// base condition to terminate the recursion when N = 0
if (n == 0) {
return 0;
}

// recursive case / recursive call


int res = n + nSum(n - 1);

return res;
}

int main()
{
int n = 5;

// calling the function


int sum = nSum(n);

printf("Sum of First %d Natural Numbers: %d", n, sum);


return 0;
}

OutputSum of First 5 Natural Numbers: 15

B
What is Structure

Structure in c is a user-defined data type that enables us to store the collection of different
data types. Each element of a structure is called a member. Structures can simulate the
use of classes and templates as it can store various information

The ,struct keyword is used to define the structure. Let's see the syntax to define the
structure in c.

278. struct structure_name


279. {
280. data_type member1;
281. data_type member2;
282. .
283. .
284. data_type memeberN;
285. };

Let's see the example to define a structure for an entity employee in c.

286. struct employee


287. { int id;
288. char name[20];
289. float salary;
290. };

The following image shows the memory allocation of the structure employee that is
defined in the above example.
Here, struct is the keyword; employee is the name of the structure; id, name, and salary
are the members or fields of the structure. Let's understand it by the diagram given below:

Declaring structure variable

We can declare a variable for the structure so that we can access the member of the
structure easily. There are two ways to declare structure variable:

291. By struct keyword within main() function


292. By declaring a variable at the time of defining the structure.

1st way:

Let's see the example to declare the structure variable by struct keyword. It should be
declared within the main function.

293. struct employee


294. { int id;
295. char name[50];
296. float salary;
297. };

Now write given code inside the main() function.

298. struct employee e1, e2;

The variables e1 and e2 can be used to access the values stored in the structure. Here,
e1 and e2 can be treated in the same way as the objects in C++ and Java.

2nd way:

Let's see another way to declare variable at the time of defining the structure.

299. struct employee


300. { int id;
301. char name[50];
302. float salary;
303. }e1,e2;

C Structure example

Let's see a simple example of structure in C language.

304. #include<stdio.h>
305. #include <string.h>
306. struct employee
307. { int id;
308. char name[50];
309. }e1; //declaring e1 variable for structure
310. int main( )
311. {
312. //store first employee information
313. e1.id=101;
314. strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
315. //printing first employee information
316. printf( "employee 1 id : %d\n", e1.id);
317. printf( "employee 1 name : %s\n", e1.name);
318. return 0;
319. }

Output:

employee 1 id : 101
employee 1 name : Sonoo Jaiswal

File Handling in C

In programming, we may require some specific input data to be generated several


numbers of times. Sometimes, it is not enough to only display the data on the console.
The data to be displayed may be very large, and only a limited amount of data can be
displayed on the console, and since the memory is volatile, it is impossible to recover the
programmatically generated data again and again. However, if we need to do so, we may
store it onto the local file system which is volatile and can be accessed every time. Here,
comes the need of file handling in C.

File handling in C enables us to create, update, read, and delete the files stored on the
local file system through our C program. The following operations can be performed on a
file.

• Creation of the new file


• Opening an existing file
• Reading from the file
• Writing to the file
• Deleting the file

Functions for file handling

There are many functions in the C library to open, read, write, search and close the file.
A list of file functions are given below:

No. Function Description


1 fopen() opens new or existing file

2 fprintf() write data into the file

3 fscanf() reads data from the file

4 fputc() writes a character into the file

5 fgetc() reads a character from file

6 fclose() closes the file

7 fseek() sets the file pointer to given position

8 fputw() writes an integer to file

9 fgetw() reads an integer from file

10 ftell() returns current position

11 rewind() sets the file pointer to the beginning of the file

Opening File: fopen()

We must open a file before it can be read, write, or update. The fopen() function is used
to open a file. The syntax of the fopen() is given below.

320. FILE *fopen( const char * filename, const char * mode );

The fopen() function accepts two parameters:

• The file name (string). If the file is stored at some specific location, then we must
mention the path at which the file is stored. For example, a file name can be like
"c://some_folder/some_file.ext".
• The mode in which the file is to be opened. It is a string.

We can use one of the following modes in the fopen() function.

Mode Description
r opens a text file in read mode

w opens a text file in write mode

a opens a text file in append mode

r+ opens a text file in read and write mode

w+ opens a text file in read and write mode

a+ opens a text file in read and write mode

rb opens a binary file in read mode

wb opens a binary file in write mode

ab opens a binary file in append mode

rb+ opens a binary file in read and write mode

wb+ opens a binary file in read and write mode

ab+ opens a binary file in read and write mode

The fopen function works in the following way.

• Firstly, It searches the file to be opened.


• Then, it loads the file from the disk and place it into the buffer. The buffer is used
to provide efficiency for the read operations.
• It sets up a character pointer which points to the first character of the file.

Consider the following example which opens a file in write mode.

321. #include<stdio.h>
322. void main( )
323. {
324. FILE *fp ;
325. char ch ;
326. fp = fopen("file_handle.c","r") ;
327. while ( 1 )
328. {
329. ch = fgetc ( fp ) ;
330. if ( ch == EOF )
331. break ;
332. printf("%c",ch) ;
333. }
334. fclose (fp ) ;
335. }

Output

The content of the file will be printed.

#include;
void main( )
{
FILE *fp; // file pointer
char ch;
fp = fopen("file_handle.c","r");
while ( 1 )
{
ch = fgetc ( fp ); //Each character of the file is read and stored in the character file.
if ( ch == EOF )
break;
printf("%c",ch);
}
fclose (fp );
}

Closing File: fclose()

The fclose() function is used to close a file. The file must be closed after performing all
the operations on it. The syntax of fclose() function is given below:

336. int fclose( FILE *fp );


C fprintf() and fscanf()

C fprintf() and fscanf() example

C fputc() and fgetc()

C fputc() and fgetc() example

C fputs() and fgets()

C fputs() and fgets() example


Graphics features in C
Online

You might also like