unit1paper2AD
unit1paper2AD
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:
• 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
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
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.
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.
• 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:
Disadvantages of Flowchart:
Example : Draw a flowchart to input two numbers from the user and display the
largest of two numbers
• C++
• C
• Java
• Python3
• C#
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.
-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
0 to
unsigned long
8 18,446,744,073,709,551,61 %llu
long int
5
float 4 %f
1.2E-38 to 3.4E+38
double 8 %lf
1.7E-308 to 1.7E+308
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
Example of int
• C
int main()
{
// Integer value with positive data.
int a = 9;
return 0;
}
Syntax of char
Example of char
• C
a++;
printf("Value of a after increment is: %c\n", a);
return 0;
}
OutputValue of a: a
Value of a after increment is: b
Value of c: c
Syntax of float
Example of Float
• C
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
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:
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
• C
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);
return 0;
}
•
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
Example
• C
int main()
{
// declaring parameters to be passed to the function
int param1 = 5, param2 = 3;
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
• C
int main()
{
// declaring the size of the array
int N = 3;
printf("\n");
return 0;
}
Output18 36 54
3.140000 6.280000 9.420000
Properties of Arrays in C
Pointer Declaration
data_type * ptr_name;
where,
Example:
• C
int main()
{
int var = 20;
return 0;
}
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.
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.
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;
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
// 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);
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
Example
• C
// 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
Example
• C
int main()
{
Company* name = "GeeksforGeeks";
printf("Best Tutorials on: %s \n", name);
return 0;
}
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:
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:
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:
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.
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.
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.
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.
• C++
• C
• Java
• Python3
• C#
• Javascript
int main()
{
return 0;
}
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:
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.
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:
Syntax:
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.
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:
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.
• 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.
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.
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 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.
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
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
Local Variable
A variable that is declared inside the function or block is called a local variable.
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.
Static Variable
A variable that is declared with the static keyword is called static variable.
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.
myfile.h
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:
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.
Example of Constants in C
• C
int main()
{
// defining integer constant using const keyword
const int int_const = 25;
return 0;
}
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:
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
int main()
{
// declaring a constant variable
const int var;
// initializing constant variable var after declaration
var = 20;
Output
In function 'main':
10:9: error: assignment of read-only variable 'var'
10 | var = 20;
| ^
Constant Literals
Constants are variables that cannot be Literals are the fixed values that define
modified once declared. themselves.
• C
// C Program to define a constant using #define
#include <stdio.h>
#define pi 3.14
int main()
{
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) 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.
• C
#include <stdio.h>
int main()
{
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
Example:
• C
#include <stdio.h>
int main()
{
// constant float literal
const float floatVal = 4.14;
printf("Floating point literal: %.2f\n",
floatVal);
return 0;
}
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';
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.
The value variable will contain 210 because * (multiplicative operator) is evaluated before
+ (additive operator).
Arithmetic Operators:
Addition Operator (+): The addition operator adds two operands together.
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:
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:
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:
Example:
Output:
result = 5
Modulus Operator (%): The modulus operator determines the remainder of the division
between two operands.
ADVERTISEMENT
Syntax:
Example:
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
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:
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:
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:
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:
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
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:
Example:
Output:
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:
Example:
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:
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:
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:
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:
Example:
Output:
Syntax:
Example:
Output:
Bitwise XOR Operator (^): The bitwise XOR operator performs a bitwise exclusive OR
operation on the corresponding bits of the operands.
Syntax:
Example:
Output:
result = 6 // 0000 0110 in binary
Bitwise NOT Operator (~): The bitwise NOT operator flips each bit of the operand.
Syntax:
Example:
Output:
Syntax:
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:
Example:
239. int a;
240. a = 5;
Output:
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:
Example:
242. int a;
243. int size = sizeof(a);
Output:
Comma Operator (,): The comma operator evaluates multiple expressions and returns
the value of the last expression.
Syntax:
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:
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.
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)
• Floating expressions: Float Expressions are which produce floating point results
after implementing all the automatic and explicit type conversions.
Examples:x + y, 10.75
• Bitwise expressions: Bitwise Expressions are used to manipulate data at bit level.
They are basically used for testing or shifting bits.
Examples:x << 3
y >> 1
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 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)
Implementation:
Implementation:
Implementation:
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:
Repeat-For Flow
Implementation:
Implementation:
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:
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:
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.
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.
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 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;
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 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];
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 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);
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
Example
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
// Driver code
int main()
{
// Calling sum function and
// storing its value in add variable
int add = sum(10, 30);
OutputSum is: 40
As we noticed, we have not used explicit function declaration. We simply defined and
called the function.
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
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;
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>
// Driver code
int main()
{
int a = 30, b = 40;
// function call
int res = sum(a, b);
OutputSum is: 70
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.
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
// 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;
}
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
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;
}
return res;
}
int main()
{
int n = 5;
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.
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:
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:
1st way:
Let's see the example to declare the structure variable by struct keyword. It should be
declared within the main function.
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.
C Structure example
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
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.
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:
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.
• 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.
Mode Description
r opens a text file in read 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
#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 );
}
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: