Unit 1 - 1
Unit 1 - 1
WHAT IS AN ALGORITHM :
● Clear and Unambiguous: Algorithms should be clear and 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.
● Well-Defined Outputs: The algorithm must clearly define what output will be yielded
and it should be well-defined as well.
● Finite-ness: The algorithm must be finite, i.e. it should not end up in an infinite loops or
similar.
● Feasible: The algorithm must be simple, generic and practical, such that it can be
executed upon 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.
Example
Let’s try to learn algorithm-writing by using an example.
PROBLEM − Design an algorithm to add two numbers and display the result.
Step 1 − START
C= a+b
Step 6 − print c
Step 7 − STOP
Step 3 − c ← a + b
Step 4 − display c
Step 5 − STOP
History of C Language
● C programming language was developed in 1972 by Dennis Ritchie at bell laboratories
of AT&T (American Telephone & Telegraph), located in the U.S.A.
● Dennis Ritchie is known as the founder of the C language.
● It was developed to overcome the problems of previous languages such as B, BCPL, etc.
● Initially, C language was developed to be used in UNIX operating system. It inherits
many features of previous languages such as B and BCPL.
● Let's see the programming languages that were developed before C language.
Features of C Language
1) Simple
C is a simple language in the sense that it provides a structured approach (to break the problem
into parts), the rich set of library functions, data types, etc.
Unlike assembly language, c programs can be executed on different machines with some
machine specific changes. Therefore, C is a machine independent language.
C is a structured programming language in the sense that we can break the program into parts
using functions. So, it is easy to understand and modify. Functions also provide code reusability.
5) Rich Library
6) Memory Management
It supports the feature of dynamic memory allocation. In C language, we can free the allocated
memory at any time.
7) Speed
The compilation and execution time of C language is fast since there are lesser inbuilt functions.
8) Pointer
C provides the feature of pointers. We can directly interact with the memory by using the
pointers.
9) Recursion:
In C, we can call the function within the function. It provides code reusability for every function.
Recursion enables us to use the approach of backtracking.
10) Extensible
Structure of a C program
The structure of a C program means the specific structure to start the programming in the C
language.
Without a proper structure, it becomes difficult to analyze the problem and the solution.
Sometimes, when we begin with a new programming language, we are not aware about the basic
structure of a program. The structure of a language gives us a basic idea of the order of the
sections in a program. We get to know when and where to use a particular statement, variable,
function, curly braces, parentheses, etc. It also increases our interest in that programming
language.
Thus, the structure helps us analyze the format to write a program for the least errors. It gives
better clarity and the concept of a program.
Sections of a C program
i. Documentation section
ii. Preprocessor section/Link Section
iii. Definition section
iv. Global declaration
v. Main function
vi. SubProgram section/User defined functions
Output
DOCUMENTATION SECTION
It includes the statement specified at the beginning of a program, such as a program's name,
date, description, and title. It is represented as:
//name of a program OR
/*
*/
Both methods work as the document section in a program. It provides an overview of the
program. Anything written inside will be considered a part of the documentation section and will
not interfere with the specified code.
The preprocessor section contains all the header files used in a program. It informs the system to
link the header files to the system libraries. It is given by:
#include<stdio.h>
#include<conio.h>
The #include statement includes the specific file as a part of a function at the time of the
compilation. Thus, the contents of the included file are compiled along with the function being
compiled.
The #include<stdio.h> consists of the contents of the standard input output files, which contains
the definition of stdin, stdout, and stderr. Whenever the definitions stdin, stdout, are used in a
function, the statement #include<stdio.h> need to be used.
DEFINE SECTION
The define section comprises of different constants declared using the define keyword. It is given
by:
#define a = 2
GLOBAL DECLARATION
The global section comprises of all the global declarations in the program. It is given by:
char ch ='z';
MAIN FUNCTION
main() is the first function to be executed by the computer. It is necessary for a code to include
the main(). It is like any other function available in the C library. Parenthesis () are used for
passing parameters (if any) to a function.
main()
We can also use int or main with the main (). The void main() specifies that the program will not
return any value. The int main() specifies that the program can return integer type data.
int main()
OR
void main()
//Declaration
//Executable
Main function is further categorized into local declarations, statements, and expressions.
The user defined functions specified the functions specified as per the requirements of the user.
For example, color(), sum(), division(), etc.
Return function is generally the last section of a code. But, it is not necessary to include. It is
used when we want to return a value. The return function returns a value when the return type
other than the void is specified with the function.
Return type ends the execution of the function. It further returns control to the specified calling
function. It is given by:
return;
Or
Return expression ;
#include <stdio.h> includes the standard input output library functions. The printf() function
is defined in stdio.h .
int main() The main() function is the entry point of every program in c language.
return 0 The return 0 statement, returns execution status to the OS. The 0 value is used for
successful execution and 1 for unsuccessful execution.
1. Integrity:
This refers to the accuracy of the calculations. Integrity is needed to perform correct calculations
if any enhancement is done otherwise there will be no use of enhancement and all enhancement
will be meaningless Thus, the integrity of the calculations is an absolute necessity in any
computer program.
2. Clarity:
Refers to the overall readability of the program, with specific logic. If a program should not be
complicated it should be clearly written, it should be possible for another programmer to follow
the program logic without much effort. It should also be possible for the original author to follow
his or her own program after being away from the program for an extended period of time. One
of the objectives in the design of C is the development of clear, readable and disciplined
approach to programming
3. Simplicity:
The clarity, readability of the program and accuracy of a program are usually enhanced by
keeping things as simple as possible, uniqueness and consistency should be included with the
overall program objectives. In fact, it may be desirable to sacrifice a certain amount of
computational efficiency in order to maintain a relatively simple, straightforward program
structure.
4. Efficiency:
It is concerned with execution speed and efficient memory utilization. Many complex programs
require a tradeoff between these characteristics. Hence experience and common sense are key
factors used to increase efficiency of the program.
5. Modularity:
Many programs can be broken down into a series of identifiable subtasks. It is good
programming practice to implement each of these subtasks as a separate program module. In the
C programming language, such modules are written as functions. The use of a modular
programming structure enhances the accuracy and clarity of a program, and it facilitates future
program alterations.
6. Generality:
Program to be as general as possible, within reasonable limits. For example, we may design a
program to read in the values of certain key parameters rather than placing fixed values into the
program. As a rule, a considerable amount of generality can be obtained with very little
additional programming effort. All programs should be written in a generalized manner.
Compilation process in c
The compilation is a process of converting the source code into object code. It is done with the
help of the compiler. The compiler checks the source code for the syntactical or structural errors,
and if the source code is error-free, then it generates the object code.
The c compilation process converts the source code taken as input into the object code or
machine code.
1. Pre-processing
2. Compiling
3. Assembling
4. Linking.
The preprocessor takes the source code as an input, and it removes all the comments from the
source code. The preprocessor takes the preprocessor directive and interprets it.
For example, if <stdio.h>, the directive is available in the program, then the preprocessor
interprets the directive and replace this directive with the content of the 'stdio.h' file.
The following are the phases through which our program passes before being transformed into an
executable form:
Preprocessor
Compiler
Assembler
Linker
Preprocessor
The source code is the code which is written in a text editor and the source code file is given an
extension ".c". This source code is first passed to the preprocessor, and then the preprocessor
expands this code. After expanding the code, the expanded code is passed to the compiler.
Compiler
The code which is expanded by the preprocessor is passed to the compiler. The compiler
converts this code into assembly code. Or we can say that the C compiler converts the
pre-processed code into assembly code.
Assembler
The assembly code is converted into object code by using an assembler. The name of the object
file generated by the assembler is the same as the source file. The extension of the object file in
DOS is '.obj,' and in UNIX, the extension is 'o'. If the name of the source file is 'hello.c', then the
name of the object file would be 'hello.obj'.
Linker
Mainly, all the programs written in C use library functions. These library functions are
pre-compiled, and the object code of these library files is stored with '.lib' (or '.a') extension. It
links the object code of these files to our program.
The job of the linker is to link the object code of our program with the object code of the library
files and other files. The output of the linker is the executable file.
For example, if we are using printf() function in a program, then the linker adds its associated
code in an output file.
hello.c
#include <stdio.h>
int main()
printf("Hello FYBSC");
return 0;
Flowchart symbols:
● The flowchart shows the steps as boxes of various kinds, and their order by
connecting the boxes with arrows
The expanded source code is passed to the compiler, and the compiler converts this expanded
source code into assembly code. The extension of the assembly code would be hello.s.
This assembly code is then sent to the assembler, which converts the assembly code into object
code.
After the creation of an object code, the linker creates the executable file. The loader will then
load the executable file for the execution.
Pseudo code: It’s simply an implementation of an algorithm in the form of annotations and
informative text written in plain English. It has no syntax like any of the programming language
and thus can’t be compiled or interpreted by the computer.
Acts as a bridge between the program and the algorithm or flowchart. Also works as a rough
documentation, so the program of one developer can be understood easily when a pseudo code is
written out.
The main goal of a pseudo code is to explain what exactly each line of a program should do,
hence making the code construction phase easier for the programmer
Algorithm:
Step 3 − c ← a + b
Step 4 − display c
Step 5 − STOP
Pseudocode
We can draft a pseudocode of the above algorithm as follows −
procedure find_sum(number)
sum=a+b
DISPLAY sum
end procedure
C Character Set:
C language also has a set of characters which include alphabets, digits, and special symbols. C
language supports a total of 256 characters.
Alphabets
Digits
C language supports 10 digits which are used to construct numerical values in C language.
Digits - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special Symbols
C language supports a rich set of special symbols that include symbols to perform mathematical
operations, to check conditions, white spaces, backspaces, and other special symbols.
Special Symbols - ~ @ # $ % ^ & * ( ) _ - + = { } [ ] ; : ' " / ? . > , < \ | tab newline space
NULL bell backspace vertical tab etc.,
Every character in C language has its equivalent ASCII (American Standard Code for
Information Interchange) value.
Blank space, newline, horizontal tab, carriage return and form feed.
C Keywords and Identifiers:
C Keywords
Keywords are predefined, reserved words used in programming that have special meanings to the
compiler. Keywords are part of the syntax and they cannot be used as an identifier. For example:
int money;
Here, int is a keyword that indicates money is a variable of type int (integer).
As C is a case sensitive language, all keywords must be written in lowercase. Here is a list of all
keywords allowed in ANSI C.
C Keywords
C Identifier:
Identifier refers to name given to entities such as variables, functions, structures etc.
They are created to give a unique name to an entity to identify it during the execution of the
program.
For example:
int money;
double accountBalance;
Also remember, identifier names must be different from keywords. You cannot use int as an
identifier because int is a keyword.
Examples of keywords are: int, char, Examples of identifiers are: Test, count1,
8 if, while, do, class etc. high_speed, etc.
This determines the type and size of data associated with variables.
For example:
int myVar;
Here, myVar is a variable of int (integer) type. The size of int is 4 bytes
int:
Integers are whole numbers that can have both zero, positive and negative values but no decimal
values.
float and double are used to hold real numbers or number with decimal values.
for example:
float salary;
double price;
And the size of double (double precision float data type) is 8 bytes.
char :
Keyword char is used for declaring character type variables.
For example,
char test = 'h';
Basic types
Here's a table containing commonly used types in C programming for quick access.
Type Size (bytes) Format Specifier
char 1 %c
float 4 %f
double 8 %lf
signed char 1 %c
unsigned char 1 %c
List of Constants in C
Constant Example
1) C const keyword
The const keyword is used to define constant in C programming.
1. const float PI=3.14;
Now, the value of PI variable can't be changed.
1. #include<stdio.h>
2. int main(){
3. const float PI=3.14;
4. printf("The value of PI is: %f",PI);
5. return 0;
6. }
Output:
The value of PI is: 3.140000
2) C #define preprocessor
The #define preprocessor is also used to define constant.
Variables:
Variables
To indicate the storage area, each variable should be given a unique name (identifier). Variable
names are just the symbolic representation of a memory location. For example:
Here, playerScore is a variable of int type. Here, the variable is assigned an integer value 95.
The value of a variable can be changed, hence the name variable.
char ch = 'a';
// some code
ch = 'l';
1. A variable name can only have letters (both uppercase and lowercase letters), digits and
underscore.
2. The first letter of a variable should be either a letter or an underscore.
3. There is no rule on how long a variable name (identifier) can be. However, you may run into
problems in some compilers if the variable name is longer than 31 characters.
Types of Variables in C
There are many types of variables in c:
1. local variable
2. global variable
3. static variable
4. automatic variable
5. 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.
1. void function1(){
2. int x=10;//local variable
3. }
You must have to initialize the local variable before it is used.
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.
1. int value=20;//global variable
2. void function1(){
3. int x=10;//local variable
4. }
Static Variable
A variable that is declared with the static keyword is called static variable.
It retains its value between multiple function calls.
1. void function1(){
2. int x=10;//local variable
3. static int y=10;//static variable
4. x=x+1;
5. y=y+1;
6. printf("%d,%d",x,y);
7. }
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.
1. void main(){
2. int x=10;//local variable (also automatic)
3. auto int y=20;//automatic variable
4. }
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
1. extern int x=10;//external variable (also global)
program1.c
1. #include "myfile.h"
2. #include <stdio.h>
3. void printValue(){
4. printf("Global variable: %d", global_variable);
5. }
Character :
● In C and C++, the char type is used to define and declare characters.
● The char type is a single BYTE.
● In the C language they are formed with 8 bits, that means a character has 256 different
types.
● In C and C++, we can define a variable as a char type as below,
char a;
● Char types are ASCII coded bytes, generally 32-255 characters are visible characters. For
example in ASCII standard 65th character is A, so we can declare this as below,
char a = 65;
● we can use ‘ and ‘ to declare a character directly. Note that we use ‘ and ‘ symbols for
characters, ” and ” symbols to declare strings.
char b = 'A';
● Example :
#include <stdio.h>
int main()
{
char a = 65;
char b = 'A';
getchar();
return 0;
}
Character String :
● We can also define multiple char arrays by using [ and ] brackets and the number
of characters inside.
● See example below,
char c[5];
c[0] = 'A';
c[1] = 'B';
c[2] = 'C';
c[3] = 'D';
c[4] = 'E';
● We can define multiple char arrays by using [ and ] brackets and a string with
these characters. These are also defined char arrays; in other words, these are
strings. The code below is completely same as above in usage.
● char c[] = "ABCDE";
● Strings are defined as an array of characters. The difference between a character
array and a string is the string is terminated with a special character ‘\0’.
● Declaration of strings: Declaring a string is as simple as declaring a one-dimensional
array. Below is the basic syntax for declaring a string.
char str_name[size];
● // C program to illustrate strings
#include<stdio.h>
int main()
{
// declare and initialize string
char str[] = "Geeks";
// print string
printf("%s",str);
return 0;
}
typedef in C
● The above statement define a term ulong for an unsigned long datatype. Now this ulong
identifier can be used to define unsigned long type variables.
ulong i, j;
Type Casting in C
Implicit Conversion :
● Implicit type casting means conversion of data types without losing its original meaning.
● This type of typecasting is essential when you want to change data types without
changing the significance of the values stored inside the variable.
● Implicit type conversion in C happens automatically when a value is copied to its
compatible data type.
● This type of type conversion can be seen in the following example.
#include<stdio.h>
int main(){
short a=10; //initializing variable of short data type
int b; //declaring int variable
b=a; //implicit type casting
printf("%d\n",a);
printf("%d\n",b);
}
Explicit Conversion :
● In C language, we use cast operator for typecasting which is denoted by (type).
● Syntax:
(type)value;
OR
(type_name) expression
● Example :
#include <stdio.h>
int main()
{
int sum = 17, count = 5;
double mean;
mean = (double) sum / count;
printf("Value of mean : %f\n", mean );
return 0;
}
Output :