0% found this document useful (0 votes)
36 views32 pages

Unit 1 - 1

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)
36 views32 pages

Unit 1 - 1

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

UNIT 1 :

WHAT IS AN ALGORITHM :

● Algorithm is a step-by-step procedure, which defines a set of instructions to be executed in a


certain order to get the desired output.

A programming algorithm is a procedure or formula used for solving a problem. It is based on


conducting a sequence of specified actions in which these actions describe how to do something,
and your computer will do it exactly that way every time. An algorithm works by following a
procedure, made up of inputs.

In computer programming terms, an algorithm is a set of well-defined instructions to solve a


particular problem. It takes a set of input(s) and produces the desired output.

● Some important categories of algorithms are:

➢ Search − Algorithm to search an item in a data structure.

➢ Sort − Algorithm to sort items in a certain order.

➢ Insert − Algorithm to insert item in a data structure.

➢ Update − Algorithm to update an existing item in a data structure.

➢ Delete − Algorithm to delete an existing item from a data structure.

Characteristics of an algorithm are:

● 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

Step 2 − declare three integers a, b & c

Step 3 − define values of a & b(read values given by user)

Step 4 − add values of a & b

Step 5 − store output of step 4 to c

C= a+b

Step 6 − print c

Step 7 − STOP

Algorithms tell the programmers how to code the program.

Alternatively, the algorithm can be written as −

Step 1 − START ADD

Step 2 − get values of a & b

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.

Language Year Developed By

Algol 1960 International Group

BCPL 1967 Martin Richard

B 1970 Ken Thompson

Traditional C 1972 Dennis Ritchie

K&RC 1978 Kernighan &


Dennis Ritchie

ANSI C 1989 ANSI Committee

ANSI/ISO C 1990 ISO Committee

C99 1999 Standardization Committee

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.

2) Machine Independent or Portable

Unlike assembly language, c programs can be executed on different machines with some
machine specific changes. Therefore, C is a machine independent language.

3) Mid-level programming language


Although, C is intended to do low-level programming. It is used to develop system applications.
It also supports the features of a high-level language. That is why it is known as mid-level
language.

4) Structured programming 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

C provides a lot of inbuilt functions that make the development fast.

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

C language is extensible because it can easily adopt new features.

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.

Importance of structure of a C program

Sometimes, when we begin with a new programming language, we are not aware about the basic
structure of a program. The 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

The sections of a C program are listed below:

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

/*

Overview of the code

*/

Both methods work as the document section in a program. It provides an overview of the
program. Anything written inside will be considered a part of the documentation section and will
not interfere with the specified code.

PREPROCESSOR SECTION/LINK SECTION

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

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

There are various header files available for different purposes.

For example, #include <math.h>. It is used for mathematic functions in a program.

DEFINE SECTION

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

#define a = 2

GLOBAL DECLARATION

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

float num = 2.54;


int a = 5;

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.

The main function is declared as:

main()

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

int main()

OR

void main()

//Declaration

//Executable

Main function is further categorized into local declarations, statements, and expressions.

USER DEFINED FUNCTIONS/SUBPROGRAM

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.

printf() The printf() function is used to print data on the console.

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.

PROGRAM CHARACTERISTICS/Desirable Program Characteristics:

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.

The compilation process can be divided into four steps, i.e.,

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.

Let's understand through an example.

hello.c

#include <stdio.h>

int main()

printf("Hello FYBSC");

return 0;

Flowchart symbols:

● A flowchart is a type of diagram that represents a workflow or process.


● A flowchart can also be defined as a diagrammatic representation of an algorithm, a
step-by-step approach to solving a task.

● The flowchart shows the steps as boxes of various kinds, and their order by
connecting the boxes with arrows

Now, we will create a flow diagram of the above program:


In the above flow diagram, the following steps are taken to execute a program:
Firstly, the input file, i.e., hello.c, is passed to the preprocessor, and the preprocessor converts the
source code into expanded source code. The extension of the expanded source code would be
hello.i.

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 1 − START ADD

Step 2 − get values of a & b

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

C language supports all the alphabets from the English language.

Lower and upper case letters together support 52 alphabets.

lower case letters - a to z

UPPER CASE LETTERS - A to Z

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.

White space Characters

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

Auto double Int struct

Break else Long switch

case enum Register typedef

char extern Return union

continu for Signed void


e
do if Static while

default goto Sizeof volatile

const float Short unsigned

C Identifier:

Identifier refers to name given to entities such as variables, functions, structures etc.

Identifiers must be unique.

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;

Here, money and accountBalance are identifiers.

Also remember, identifier names must be different from keywords. You cannot use int as an
identifier because int is a keyword.

Rules for naming identifiers


1. A valid identifier can have letters (both uppercase and lowercase letters), digits and
underscores.
2. The first letter of an identifier should be either a letter or an underscore.
3. You cannot use keywords like int, while etc. as identifiers.
4. There is no rule on how long an identifier can be. However, you may run into problems in
some compilers if the identifier is longer than 31 characters.

Difference between Keyword and Identifier


SR.
NO. KEYWORD IDENTIFIER

Identifiers are the values used to define


Keywords are predefined word that different programming items such as
gets reserved for working program variables, integers, structures, unions and
that have special meaning and cannot others and mostly have an alphabetic
1 get used anywhere else. character.

2 Specify the type/kind of entity. Identify the name of a particular entity.

It always starts with a lowercase First character can be a uppercase, lowercase


3 letter. letter or underscore.

An identifier can be in upper case or lower


4 A keyword should be in lower case. case.

A keyword contains only An identifier can consist of alphabetical


5 alphabetical characters. characters, digits and underscores.

They help to identify a specific


property that exists within a They help to locate the name of the entity
6 computer language. that gets defined along with a keyword.

No special symbol, punctuation is No punctuation or special symbol except


7 used. ‘underscore’ is used.

Examples of keywords are: int, char, Examples of identifiers are: Test, count1,
8 if, while, do, class etc. high_speed, etc.

C data types and sizes:


In C programming, data types are declarations for variables.

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.

For example, 0, -5, 10

We can use int for declaring an integer variable.


int id;

Here, id is a variable of type integer.

You can declare multiple variables at once in C programming.


For example,
int id, age;

The size of int is usually 4 bytes (32 bits).

float and double :

float and double are used to hold real numbers or number with decimal values.

for example:
float salary;
double price;

In C, floating-point numbers can also be represented in exponential.


For example,
float normalizationFactor = 22.442e2;

The size of float (single precision float data type) is 4 bytes.

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

The size of the character variable is 1 byte.

Difference between signed and unsigned :


Signed :Positive and negative both
Unsigned: only positive

Basic types
Here's a table containing commonly used types in C programming for quick access.
Type Size (bytes) Format Specifier

int at least 2, usually 4 %d, %i

char 1 %c

float 4 %f

double 8 %lf

short int 2 usually %hd

unsigned int at least 2, usually 4 %u

long int at least 4, usually 8 %ld, %li

long long int at least 8 %lld, %lli

unsigned long int at least 4 %lu

unsigned long long int at least 8 %llu

signed char 1 %c

unsigned char 1 %c

long double at least 10, usually 12 or 16 %Lf


Constants in C:

A constant is a value or variable that can't be changed in the program

There are different types of constants in C programming.

List of Constants in C

Constant Example

Decimal Constant 10, 20, 450 etc.

Real or Floating-point Constant 10.3, 20.2, 450.6 etc.

Octal Constant 021, 033, 046 etc.

Hexadecimal Constant 0x2a, 0x7b, 0xaa etc.

Character Constant 'a', 'b', 'x' etc.

String Constant "c", "c program", "c in javatpoint" etc.

2 ways to define constant in C


There are two ways to define constant in C programming.
1. const keyword
2. #define preprocessor

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

In programming, a variable is a container (storage area) to hold data.

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:

int playerScore = 95;

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

Rules for naming a variable

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 and character string in C :

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

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


printf("character : %c \n", b);

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

● typedef is a keyword used in C language to assign alternative names to existing


datatypes.
● It is mostly used with user defined datatypes, when names of the datatypes become
slightly complicated to use in programs.
● Following is the general syntax for using typedef,

typedef <existing_name> <alias_name>

● Lets take an example and see how typedef actually works.

typedef unsigned long ulong;

● 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

Typecasting allows us to convert one data type into other.


There are two types of Type casting :
1. Implicit Conversion
2. Explicit Conversion

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 :

Value of mean : 3.400000


Note :

ASCII (American Standard Code for Information Interchange) is a standard character


encoding used in telecommunication. The ASCII pronounced ‘ask-ee’ , is strictly a seven bit
code based on English alphabet. ASCII codes are used to represent alphanumeric data . The code
was first published as a standard in 1967. it was subsequently updated and published as ANSI
X3.4-1968, then as ANSI X3.4-1977 and finally as ANSI X3.4-1986. Since it is a seven bit code
, it can at the most represent 128 characters. it currently defines 95 printable characters including
26 upper case letters (A to Z) , 26 lower case letters , 10 numerals (0 to 9) and 33 special
characters including mathematical symbols, punctuation marks and space character. They
represent text in, telecommunications equipment, and devices. These include numbers, upper and
lowercase English letters, functions, punctuation symbols, and some other symbols. In total,
there are 256 ASCII characters, and can be broadly divided into three categories:

1. ASCII control characters (0-31 and 127)


2. ASCII printable characters (32-126) (most commonly referred)
3. Extended ASCII characters (128-255)

Ascii value 65 =A….Z=90,a=97…z=122

You might also like