Introduction to Computers:mrecacademics.com/DepartmentStudyMaterials/20201227...  · Web view2020....

205
Introduction to Computers: Computer Systems: A computer is a system made of two major components: hardware and software. The computer hardware is the physical equipment. The software is the collection of programs (instructions) that allow the hardware to do its job. Computer Hardware The hardware component of the computer system consists of five parts: input devices, central processing unit (CPU), primary storage, output devices, and auxiliary storage devices. Computer System Hardwa re Softwa re

Transcript of Introduction to Computers:mrecacademics.com/DepartmentStudyMaterials/20201227...  · Web view2020....

Introduction to Computers:

Computer Systems:

A computer is a system made of two major components: hardware and software. The computer hardware is the physical equipment. The software is the collection of programs (instructions) that allow the hardware to do its job.

Computer Hardware

The hardware component of the computer system consists of five parts: input devices, central processing unit (CPU), primary storage, output devices, and auxiliary storage devices.

The input device is usually a keyboard where programs and data are entered into the computers. Examples of other input devices include a mouse, a pen or stylus, a touch screen, or an audio input unit.

The central processing unit (CPU) is responsible for executing instructions such as arithmetic calculations, comparisons among data, and movement of data inside the system. Today’s computers may have one, two, or more CPUs. Primary storage is also known as main memory, is a place where the programs and data are stored temporarily during processing. The data in primary storage are erased when we turn off a personal computer or when we log off from a time-sharing system.

The output device is usually a monitor or a printer to show output. If the output is shown on the monitor, we say we have a soft copy. If it is printed on the printer, we say we have a hard copy.

Auxiliary storage, also known as secondary storage, is used for both input and output. It is the place where the programs and data are stored permanently. When we turn off the computer, or programs and data remain in the secondary storage, ready for the next time we need them.

Computer Software

Computer software is divided in to two broad categories: system software and application software. System software manages the computer resources. It provides the interface between the hardware and the users. Application software, on the other hand is directly responsible for helping users solve their problems.

System Software:

System software consists of programs that manage the hardware resources of a computer and perform required information processing tasks.

These programs are divided into three classes: the operating system, system support, and system development.

The operating system provides services such as a user interface, file and database access, and interfaces to communication systems such as Internet protocols. The primary purpose of this software is to keep the system operating in an efficient manner while allowing the users access to the system.

System support software provides system utilities and other operating services. Examples of system utilities are sort programs and disk format programs. Operating services consists of programs that provide performance statistics for the operational staff and security monitors to protect the system and data.

The last system software category, system development software, includes the language translators that convert programs into machine language for execution, debugging tools to ensure that the programs are error free and computer –ssisted software engineering (CASE) systems

Application software

Application software is broken in to two classes:

General-purpose software and

Application – specific software.

General purpose software is purchased from a software developer and can be used for more than one application. Examples of general purpose software include word processors, database management systems ,and computer design systems. They are labeled general purpose because they can solve a variety of user computing problems.

Application –specific software can be used only for its intended purpose.

A general ledger system used by accountants and a material requirement planning system used by a manufacturing organization are examples of application-specific software. They can be used only for the task for which they were designed they cannot be used for other generalized tasks.

The relationship between system and application software is shown in above figure. In this figure, each circle represents an interface point. The inner core is hard ware. The user is represented by the out layer. To work with the system, the typical user uses some form of application software. The application software in turn interacts with the operating system, which is a part of the system software layer. The system software provides the direct interaction with the hard ware. The opening at the bottom of the figure is the path followed by the user who interacts directly with the operating system when necessary.

Computing Environments:

In the early days of computers, there was only one environment: the main frame computer hidden in a central computing department. With the advent of mini computers and personal computers, the environment changed, resulting in computers on virtually every desktop.

Personal Computing Environment

In 1971,Marcian E.Hoff, working for Intel, combined the basic elements of the central processing unit into the microprocessor. The first computer on a chip was the Intel 4004 and was the grandparent many times removed of Intel’s current system. If we are using a personal computer, all of the computer hardware components are tied together in our personal computer (PC).

Time-Sharing Environment

Employees in large companies often work in what is known as a time-sharing environment. In the times-sharing environment, many users are connected to one or more computers. These computers may be minicomputers or central mainframes. The terminals they use are often nonprogrammable, although today we see more and more microcomputers being used to simulate terminals. Also, in the time-sharing environment, the output devices and auxiliary storage devices are shared by all of the users. A typical college lab in which a minicomputer is shared is shared by many students is shown in figure.

Client/Server Environment

A client/server computing environment splits the computing function between a central computer and users’ computers. The users are given personal computers or work stations so that some of the computation responsibility can be moved from the central computer and assigned to the workstations. In the client-server environment, the users’ micro computers or workstations are called the client. The central computer, which may be a powerful microcomputer, minicomputer, or central mainframe system, is known as the server. Because the work is now shared between the users’ computers and the central computer, response time and monitor display are faster and the users are more productive.

Distributed Computing

A Distributed Computing environment provides a seamless integration of computing functions between different servers and clients. The internet provides connectivity to different servers throughout the world. For example, eBay uses several computers to provide its auction services. This environment provides a reliable, scalable, and highly available network.

Computer Languages:

To write a program for a computer, we must use a computer language. Over the year’s computer languages have evolved from machine languages to natural languages.

1940’sMachine level Languages

1950’sSymbolic Languages

1960’sHigh-Level Languages

Machine Languages

In the earliest days of computers, the only programming languages available were machine languages. Each computer has its own machine language, which is made of streams of 0’s and 1’s.

Instructions in machine language must be in streams of 0’s and 1’s because the internal circuits of a computer are made of switches transistors and other electronic devices that can be in one of two states: off or on. The off state is represented by 0 , the on state is represented by 1.

The only language understood by computer hardware is machine language.

Symbolic Languages:

In early 1950’s Admiral Grace Hopper, A mathematician and naval officer developed the concept of a special computer program that would convert programs into machine language. The early programming languages simply mirror to the machine languages using symbols of mnemonics to represent the various machine language instructions because they used symbols, these languages were known as symbolic languages.

Computer does not understand symbolic language it must be translated to the machine language. A special program called assembler translates symbolic code into machine language. Because symbolic languages had to be assembled into machine language, they soon became known as assembly languages.

Symbolic language uses symbols or mnemonics to represent the various, machine language instructions.

High Level Languages:

Symbolic languages greatly improved programming efficiency; they still required programmers to concentrate on the hardware that they were using. Working with symbolic languages was also very tedious because each machine instruction has to be individually coded. The desire to improve programmer efficiency and to change the focus from the computer to the problem being solved led to the development of high-level language.

High level languages are portable to many different computers, allowing the programmer to concentrate on the application problem at hand rather than the intricacies of the computer. High- level languages are designed to relieve the programmer from the details of the assembly language. High level languages share one thing with symbolic languages, they must be converted into machine language. The process of converting them is known as compilation. The first widely used high-level languages, FORTRAN (FORmula TRANslation) was created by John Backus and an IBM team in 1957; it is still widely used today in scientific and engineering applications. After FORTRAN was COBOL (Common Business-Oriented Language). Admiral Hopper was played a key role in the development of the COBOL Business language. C is a high-level language used for system software and new application code.

Software Development Method:

Software life cycle models describe phases of the software cycle and the order in which those phases are executed. Each phase produces deliverables required by the next phase in the life cycle. Requirements are translated into design. Code is produced according to the design which is called development phase. After coding and development the testing verifies the deliverable of the implementation phase against requirements. The testing team follows Software Testing Life Cycle (STLC) which is similar to the development cycle followed by the development team.

There are following six phases in every Software development life cycle model:

· Requirement gathering and analysis

· Design

· Implementation or coding

· Testing

· Deployment

· Maintenance

1) Requirement gathering and analysis: Business requirements are gathered in this phase. This phase is the main focus of the project managers and stake holders. Meetings with managers, stake holders and users are held in order to determine the requirements like; Who is going to use the system? How will they use the system? What data should be input into the system? What data should be output by the system? These are general questions that get answered during a requirement gathering phase. After requirement gathering these requirements are analyzed for their validity and the possibility of incorporating the requirements in the system to be development is also studied.

Finally, a Requirement Specification document is created which serves the purpose of guideline for the next phase of the model. The testing team follows the Software Testing Life Cycle and starts the Test Planning phase after the requirements analysis is completed.

2) Design: In this phase the system and software design is prepared from the requirement specifications which were studied in the first phase. System Design helps in specifying hardware and system requirements and also helps in defining overall system architecture. The system design specifications serve as input for the next phase of the model.

In this phase the testers come up with the Test strategy, where they mention what to test, how to test.

3) Implementation / Coding: On receiving system design documents, the work is divided in modules/units and actual coding is started. Since, in this phase the code is produced so it is the main focus for the developer. This is the longest phase of the software development life cycle.

4) Testing: After the code is developed it is tested against the requirements to make sure that the product is actually solving the needs addressed and gathered during the requirements phase. During this phase all types of functional testing like unit testing, integration testing, system testing, acceptance testing are done as well as non-functional testing are also done.

5) Deployment: After successful testing the product is delivered / deployed to the customer for their use.

As soon as the product is given to the customers, they will first do the beta testing. If any changes are required or if any bugs are caught, then they will report it to the engineering team. Once those changes are made or the bugs are fixed then the final deployment will happen.

6) Maintenance: Once when the customers start using the developed system then the actual problems come up and needs to be solved from time to time. This process where the care is taken for the developed product is known as maintenance.

Creating and Running C Program

Generally, the programs created using programming languages like C, C++, Java, etc., are written using a high-level language like English. But, the computer cannot understand the high-level language. It can understand only low-level language. So, the program written in the high-level language needs to be converted into the low-level language to make it understandable for the computer. This conversion is performed using either Interpreter or Compiler.

Popular programming languages like C, C++, Java, etc., use the compiler to convert high-level language instructions into low-level language instructions. A compiler is a program that converts high-level language instructions into low-level language instructions. Generally, the compiler performs two things, first it verifies the program errors, if errors are found, it returns a list of errors otherwise it converts the complete code into the low-level language.

To create and execute C programs in the Windows Operating System, we need to install Turbo C software. We use the following steps to create and execute C programs in Windows OS…

Step 1: Creating a Source Code

Source code is a file with C programming instructions in a high-level language. To create source code, we use any text editor to write the program instructions. The instructions written in the source code must follow the C programming language rules. The following steps are used to create a source code file in Windows OS…

· Click on the Start button

· Select Run

· Type cmd and press Enter

· Type cd c:\TC\bin in the command prompt and press Enter

· Type TC press Enter

· Click on File -> New in C Editor window

· Type the program

· Save it as FileName.c (Use shortcut key F2 to save)

Step 2: Compile Source Code (Alt + F9)

The compilation is the process of converting high-level language instructions into low-level language instructions. We use the shortcut key Alt + F9 to compile a C program in Turbo C.

Whenever we press Alt + F9, the source file is going to be submitted to the Compiler. On receiving a source file, the compiler first checks for the Errors. If there are any Errors then compiler returns List of Errors, if there are no errors then the source code is converted into object code and stores it as a file with .obj extension. Then the object code is given to the Linker. The Linker combines both the object code and specified header file code and generates an Executable file with a .exe extension.

Step 3: Executing / Running Executable File (Ctrl + F9)

After completing compilation successfully, an executable file is created with a .exe extension. The processor can understand this .exe file content so that it can perform the task specified in the source file.

We use a shortcut key Ctrl + F9 to run a C program. Whenever we press Ctrl + F9, the .exe file is submitted to the CPU. On receiving .exe file, CPU performs the task according to the instruction written in the file. The result generated from the execution is placed in a window called User Screen.

Step 4: Check Result (Alt + F5)

After running the program, the result is placed into User Screen. Just we need to open the User Screen to check the result of the program execution. We use the shortcut key Alt + F5 to open the User Screen and check the result.

Execution Process of a C Program

When we execute a C program it undergoes with the following process…

The file which contains c program instructions in a high-level language is said to be source code. Every c program source file is saved with .c extension, for example, Sample.c.

Whenever we press Alt + F9 the source file is submitted to the compiler. Compiler checks for the errors, if there are any errors, it returns a list of errors, otherwise generates object code in a file with name Sample.obj and submit it to the linker. The linker combines the code from specified header file into an object file and generates executable file as Sample.exe. With this compilation process completes.

Now, we need to run the executable file (Sample.exe). To run a program we press Ctrl + F9. When we press Ctrl + F9 the executable file is submitted to the CPU. Then CPU performs the task according to the instructions written in that program and place the result into User Screen.

Then we press Alt + F5 to open UserScreen and check the result of the program.

Algorithm

An algorithm is a step by step by step for solving a problem. Algorithm help a programmer in breakdown the solution of problem into a number of sequential steps. Algorithm is a complete step by step representation of the solution of the problem represented in English like language.

To develop any program, we need

1) Input

2) Task to be performed(process)

3) output

Properties:

· An algorithm must terminate in a finite number of steps.

· Each step of an algorithm must be clear and easy to understand

· Each step must be effective, in the sense that should be primitive (easily convertible to program).

· The algorithm must be complete, so that it can be used to solve problems.

Real time example:

1. Start

2. Get dressed to go the market

3. Check your wallet for money

4. If there is no money, replenish it

5. Gog to shop

6. Ask your favorite brand of pen

7. If pen is available, goto step 8 else go to step 11

8. Give money to the shop keeper

9. Keep the purchased pen

10. Go back home safely

11. Ask for any other brand of pen

12. Stop

Example 1 – Write an algorithm to find the sum of given two numbers

1. Read first and second number

2. Add both numbers to get the result

3. Print the result

Example 2 -write an algorithm to find the biggest number out of two numbers

1. Read first and second number

2. Compare first with second number

3. If the first number is bigger than second then print the first number

4. Otherwise print the second number

Exercise

1. Write an algorithm to find the simple interest.

2. Write an algorithm to find the quadratic equation using the following condition.

If d==0, roots are equal

Else if d<0, roots are complex numbers

Else roots are real numbers, Here d is discriminant

3. Write an algorithm to print natural number from 1 to 10

Pseudocode:

Pseudo code specifying only logic, which is used by the programmer for developing a computer program.

In pseudo code representation, each step will be written via operators and statements equivalent to programming language instructions

Pseudo code will start with keyword “START” and complete with keyword “STOP” or “END”

Write a pseudocode for sum of given two numbers

1. START

2. DEFINE: Integer a, b, sum

3. READ: integer a

4. READ : integer b

5. COMPUTE : sum = a + b

6. DISPLAY: sum

7. STOP

Write a pseudocode for total and average of marks obtained by the student

1. START

2. DEFINE: Integer m1,m2,m3, total

3. DEFINE: Real avg

4. DISPLAY “Enter three subject marks”

5. READ: m1,m2,m3

6. COMPUTE: total=m1+m2+m3

7. COMPUTE avg=tot/3

8. DISPLAY: “Total Marks” + total

9. DISPLAY: “Average Marks” + avg

10. STOP

Write a pseudocode to check given number is positive or negative number

1. START

2. DEFINE: Integer n

3. DISPLAY: “Enter n value”

4. READ: n

5. If n > 0 then

6. DISPLAY: “Given number is Positive number”

7. Else

8. DISPLAY: “Given number is Negative number”

9. STOP

Write a pseudocode to print 1 to 10

1. START

2. DEFINE : Integer i

3. For i=1 to 10 step 1

DISPLAY i

4. ENDFOR

5. STOP

Write a pseudocode to sum of given 10 numbers

1. START

2. DEFINE : Integer i, n, sum

3. SET sum=0

4. SET i=1

5. While (i<=10)

DISPLAY “Enter n value”

Read n

Sum=sum+n

i-i+1

7. End while

8. DISPLAY “Sum of given numbers is” + sum

9. STOP

Flow Chart

Flow chart is a pictorial representation of a process, which describes the sequence and flow of control and information within the process. A flow of information is represented inside the flow chart in a step by step form.

The various symbols are used in flowchart. They are

Start and End

It is represented by an oval and rounded rectangle. It represents the starting and the ending of a process.

Input or Output

It represented by parallelogram. It is representing the inputs to the process and output given the process to the user.

Action or Process

It is represented by rectangle. It represents the actions and calculations or computations taking place in a process.

Decision and Condition

It is represented by rhombus or a diamond shape. It represents the condition and decision-making step in a flowchart. The result of decision is a Boolean value, which is true or false.

Arrows

It is represented by a directed line. It represents the flow of process and the sequence of steps in a flow chart.

Connector

It is represented by circle. It connected the flowchart between pages.

Draw a flowchart to calculate sum and average of two numbers and display the sum and average of given numbers.

Draw a flowchart to calculate THE total and average of given three subjects marks

Draw a flowchart to check given number is even or odd number

Draw a flowchart to print natural numbers1 to 10

Introduction C Language

Background

· C programming language developed by Dennis Ritchie in in 1972 at AT&T(American Telephone & Telegraph), Bell Laboratories of located in the U.S.A. Dennis Ritchie is founder of the c language. C language was developed for a specific purpose, to designing the UNIX operating system.

· In 1960, ALGOL ((Algorithmic Language) was an early high-level computer programming language developed by International Group for the purpose of scientific calculations.

· In 1967, BCPL (Basic Combined Programming Language) developed by Martin Richards. This language has no concept of data types and access memory directly. So, it is useful for system programming.

· In 1970, Ken Thompson developed B language. This language used to develop first version of Unix operation system.

· 1972, Dennis Ritchie developed C Language, based on the concept from ALGOL, BCPL and B languages.

· In 1978, C popularized in the book of “The C Programming Language” book by Brain W. Kernighan and Dennis Ritchie. Then this language came to be known as K&RC.

· In 1983, ANSI (American National Standard Institute) defining standard for C.

· This standard is approved in in December 1989 and came to be known as ANSI C.

· In 1990, ISO (International Standards Organisation) adopted the ANSI C. this version is known as C89.

· In 1995, some minor changes were made to C89, the modified version known as C95.

· In 1999, significant changes were made to C95, the modified version known as C99.

C Tokens:

C tokens are the basic induvial smallest units to buildings blocks in C to write a C program. This means that a program constructed using the combination of these tokens. There are six types of tokens in C. They are

Keywords

C has set of reserved words known as keywords. Keywords have fixed meaning and these meaning cannot be changed.

They are listed below.

auto

double

int

struct

break

else

long

switch

case

enum

register

typedef

char

extern

return

union

const

float

short

unsigned

continue

for

signed

void

default

goto

sizeof

volatile

do

if

static

while

Important points for keywords

· Keywords can be used only for their intended purpose.

· Keywords can't be used as programmer defined identifier.

· The keywords can't be used as names for variables.

Variables

Variable is used to store the values temporarily during the execution (runtime) of the program. Variables are allocated Memory Space (in RAM) depending on the data type.

Rules for variables

· The first letter should be alphabet.

· Variables can be combination of alphabets and digits.

· Underscore (“_”) is the only special character allowed.

· Variables can be written in both Uppercase and Lowercase or combination of both.

· Variables are Case Sensitive.

· No Spaces allowed between Characters.

· Variable name should not make use to the C Reserved Keywords.

· Variable name should not start with a number.

Constants

The term constant means that it does not change during the execution of program. Constants are two types. They are

1. Numeric Constants

2. Character Constants

Numeric Constants:

Numeric constants are two types. They are

· Boolean constants

· Integer constants

· Real constants or floating-point constant

· Complex constants

· Character constants

· String constants

Boolean Constants

Boolean data type can take only two values. The values are true and false.

Integer Constants

Integer constants are whole numbers without any fractional part. Integer constants consist of a sequence of digits. Integer constants can be written in three different number systems:

Decimal Integer Constant

A decimal integer constant consists of any combination of digits taken from the set 0 through 9 preceded an optional – or + sign.

The examples of decimal integer constants are 298, +98, -987

Octal Integer Constant

An octal integer constant can consist any combination of digits taken from the set 0 through 7. However, the first digit must be 0, in order to identify the constant as an octal number.

The examples of octal integer constants are 07, 0125, 0555

Hexadecimal Integer Constant

A hexadecimal integer constant must begin with either 0x or 0X. It can then be followed by any combination of digits taken from the set 0 through 9 and A through F (either upper-case or lower-case).

The examples of Hexadecimal integer constants are 0X0, 0x123, 0XAB12578, 0x55578

Floating-point constants or Real constants

A floating-point constant can be written in two forms: Factorial form or Exponential form.

1. A floating-point constant in a fractional form must have at least one digit each to the left and right of the decimal point.

The examples of floating-point constants are

-0.25

2.567

2. A floating-point in exponent form consists of a mantissa and an exponent. he first bit defines the non-zero part of the number and is called the Mantissa, the second part defines how many positions we want to move the decimal point, this is known as the Exponent.

For example 2E-4, -0.1555e-4

Complex constants

Complex constants has two parts, real part and imaginary part, separated by + or - sign. In imaginary part can be abbreviated by i

Example 2+3i, -4i

Character Constants

Character constants are two types.

Single Character Constants

A character constant is a single character, enclosed in single quotation marks.

For example: ‘A’, ‘B’, ‘g’

The character constant has integer value known as ASCII (American Standard Code for Information Interchange) values.

For example

ASCII value of A is 65

ASCII value of a is 98.

Escape sequence characters are non-printing control characters that are begin with backslash(\)

Constant

Meaning

\a

Audible alert (bell)

\b

Back space

\f

Form feed

\n

New line

\r

Carriage return

\t

Horizontal tab

\v

Vertical tab

\‟

Single quote

\”

Double quote

\\

Backslash

\0

Null Character

String Constants

A string constant is a sequence of zero or more characters and always enclosed with double quotes (“ “)

“Welcome to C Programming”

Strings

A string is an array of characters ended with a null character(\0). This null character indicates that string has ended. Strings are always enclosed with double quotes(“ “).

For example

Special Characters

Special characters are used in C, and they have a special meaning which cannot be used for another purpose.

Symbol

Description

Square brackets [ ]

The opening and closing square brackets represent the single and multidimensional subscripts in arrays.

Rounded brackets ( ):

It is used in function declaration and function calling. For example, printf() is a pre-defined function

Curly braces { }

It is used in the opening and closing of the code. It is used in the opening and closing of the loops

Comma (,): 

It is used for separating. For example, separating the variable when printing the value of more than one variable using a single printf statement

Hash/pre-processor (#): 

It is used for pre-processor directive. It basically denotes that we are using the header file.

Asterisk (*)

This symbol is used to represent pointers and also used as an operator for multiplication

Period (.)

It is used to access a member of a structure or a union.

Tilde (~): 

It is used as a destructor to free memory.

Operators

An operator is a symbol that operates on a value or a variable. For example: + is an operator to perform addition.

In any operation, an operand may any numerical value, variables, constant, etc on which program makes an operation.

For example, a+b, operator +, a and b are the operands.

Unary Operator

A unary operator is an operator applied to the single operand. For example: increment operator (++), decrement operator (--), sizeof, (type)*.

Binary Operator

The binary operator is an operator applied between two operands. The following is the list of the binary operators:

· Arithmetic Operators

· Relational Operators

· Shift Operators

· Logical Operators

· Bitwise Operators

· Conditional Operators

· Assignment Operator

· Miscellaneous Operator

identifiers

Identifiers are the names that are given to various program elements such as variables, symbolic constants and functions.

Rules for Identifies:

· Identifier name must be a sequence of letter and digits, and must begin with a letter.

· The underscore character („_‟) is considered as letter.

· Names shouldn't be a keyword (such as int , float, if ,break, for etc)

· Both upper-case letter and lower-case letter characters are allowed. However, they're not interchangeable.

· No identifier may be keyword.

· No special characters, such as semicolon, period, blank space, slash or comma are permitted

Restrictions for identifiers

· Alphanumeric characters ( a ~ z , A~Z , 0~9 ) and half underscore ( _ ) can only be used.

· The first character of the first contain letters ( a ~ z , A~Z ) or half underscore ( _ ) can only be used.

· Case is distinguishable. That is, word and WORD is recognized as a separate identifier.

· Reserved words are not allowed. However, part of an identifier reserved words can be included

Basic Data types

A data type is defined as type of data which is used to define a variable before its use

There are four basic data types in C language.

They are

1. char

2. Int

3. float

4. double

5. Void

· Character

A char data type is used to hold individual characters and usually occupies one byte.

For example:

{

char Letter;

Letter = 'x';

}

· Integer

An integer requires 2 bytes and minimum and maximum numbers that can hold -32,768 and 32,767. It is used to whole integer number and cannot have fractional value or decimal point.

For example:

{

int Count;

Count = 5;

}

· Float

A float data type is used to store floating point numbers i.e., number have decimal values. The minimum and maximum numbers that can hold approximately 3.4E-38 and 3.4E+38. It requires 4 bytes to store a float and they give a fractional precision of 6 digits.

For example:

{

float Miles;

Miles = 5.6;

}

· Double

A double data type is also used to store floating point numbers, but which can give precision of 15 digits. It requires 8 bytes to store and minimum and maximum numbers that can hold approximately 1.7E-308 and 1.7+E308.

For example:

{

double Atoms;

Atoms = 2500000;

}

· Void data type

Void is an empty data type that has no value.  This is usually used to specify the type of functions which returns nothing.

Preprocessors

Preprocessors are programs that process our source code before compilation. It is a separate step in the compilation process. In simple terms, a C Preprocessor is just a text substitution tool and it instructs the compiler to do required pre-processing before the actual compilation.

All preprocessor commands begin with a hash symbol (#). It must be the first nonblank character, and for readability, a preprocessor directive should begin in the first column. There is different preprocessor directives available they are named as

1. Macros

2. File Inclusion

3. Conditional Compilation

4. Other directives

Macros:

Macros are part of code in a program which is given by some name. Whenever this name is encountered by the compiler the compiler replaces the name with the actual piece of code.like #define,#undef.

Ex: #define MAX_ARRAY_LENGTH 20

A small program with preprocessed macros as below:

#include

int main()

{

printf("File :%s\n", __FILE__ );

printf("Date :%s\n", __DATE__ );

printf("Time :%s\n", __TIME__ );

printf("Line :%d\n", __LINE__ );

printf("ANSI :%d\n", __STDC__ );

}

File inclusion: This type of preprocessor directive tells the compiler to include a file in the source code program. There are two types of files which can be included by the user in the program:

Header File or Standard files: These files contains definition of pre-defined functions like printf(), scanf() etc. These files must be included for working with these functions. Different functions are declared in different header files. For example, standard I/O functions are in ‘iostream’ file whereas functions which perform string operations are in ‘string’ file. where file_name is the name of file to be included. The ‘<‘ and ‘>’ brackets tells the compiler to look for the file in standard directory.

User defined files: When a program becomes very large, it is good practice to divide it into smaller files and include whenever needed. These types of files are user defined files. These files can be included as: #include"filename"

A program showing file inclusion directives:-

#include

int main() {

printf("My college name is Malla Reddy Engineering College” );

}

Conditional Compilation:  Conditional Compilation directives are type of directives which helps to compile a specific portion of the program or to skip compilation of some specific part of the program based on some conditions. This can be done with the help of two preprocessing commands ‘ifdef‘ and ‘endif‘.

#include

#define YEARS_OLD 5

void main()

{

#ifdef YEARS_OLD

printf("eligible to go to school kid is %d years old.\n", YEARS_OLD);

#endif

}

Other directives: Apart from the above directives there are two more directives which are not commonly used. These are:

#undef Directive: The #undef directive is used to undefine an existing macro. This directive works as:

#undef LIMIT

Using this statement will undefine the existing macro LIMIT. After this statement every “#ifdef LIMIT” statement will evaluate to false.

#pragma Directive: This directive is a special purpose directive and is used to turn on or off some features. This type of directives are compiler-specific, i.e., they vary from compiler to compiler. Some of the #pragma directives are discussed below:

#pragma startup and #pragma exit: These directives helps us to specify the functions that are needed to run before program startup( before the control passes to main()) and just before program exit (just before the control returns from main()).

#pragma warn Directive: This directive is used to hide the warning message which are displayed during compilation.We can hide the warnings as shown below:

· #pragma warn -rvl: This directive hides those warning which are raised when a function which is supposed to return a value does not returns a value.

· #pragma warn -par: This directive hides those warning which are raised when a function does not uses the parameters passed to it.

· #pragma warn -rch: This directive hides those warning which are raised when a code is unreachable. For example: any code written after the return statement in a function is unreachable.

Small program to use pragma directive

include

#include

void func() ;

#pragma startup func

#pragma exit func

void main(){

printf("\nI am in main");

getch();

}

void func(){

printf("\nI am in func");

getch();

}

Managing input output functions:

Input & Output statements in C:

We use input functions for INPUT (reading) the data & Output functions for OUTPUT (printing) the data.

OUTPUT FUNCTIONS: These functions are used to print data on the monitor, named as

Formatted output function : printf( ): Used to print a formatted output on the monitor

INPUTFUNCTIONS: These functions are used to input data from the keyboard.TheFormatted input functions: scanf( ):Used to read a formatted string from the key board.

Formatted Input:

1) scanf():

· scanf() is an input function used to read data values from keyboard and store them in variables.

· The syntax of scanf() is :

scanf( “ Format-string ” , &variable1, &variable2….&variablen );

A) Format string : This part contains format specifier: %conversion code( %d %f %p %c %s %i %u …)

i) % is conversion character

ii) Conversion Code: indicates the type of data (value) is to be read from keyboard.

(c -character, i or d -integer, s -strings f or g or e -Real Numbers, u -Unsigned Integer,

ld -Long integer, lf-double, Lf-long double)

B) &variable: This part consists of addresses of the variable where the read (values)data are to be stored.

The & symbol should be in front of the variable name indicates the addressof the variable

Example-1:

int a,b; scanf(“%d%d”,&a,&b);

//This is to read two integer values and store them in thevariables a , b

Example-2:

float r; ===>scanf(“%f”,&r);

//This is to read a Real Number and store itin the float variable r.

Example-3:

char ch; scanf(“%c”,ch);

//This is to read a character value&store it inthe character variable ch

Formatted Output:

printf(): is a formatted output function used print data value of variables on the monitor.

Syntax: printf( “ Format-string” , variables );

· Format string:consists of three parts.

1) MessageText that is to be printed as it is.

2) Escapesequences: escape sequences are the character sequence that begin with \.

3) each sequence prints its own value.

· \n (newline)

· \t (tab)

· \v (vertical tab)

· \f (new page)

· \b (backspace)

· \r (carriage return)

· \n (newline)

printf format specifiers take the form of

%[flags][width][.precision][length]specifier

· where:

· specifier is the most important and only required part, indicating the type of data to be printed. e.g. "%f"

· width specifies the total number of spaces to use to print the number, filling in with blanks if necessary

· Example: "%15f" would print a float in a space 15 characters wide.

· . precision indicates how many digits of a number to print, or sometimes the number to the right of the decimal point.

· Examples:

· "%15.3f" would print 10 * pi as 31.416, with three digits to the right of the decimal point.

· %15.3e" would print 10 * pi as 3.14e1, with three total digits of precision

· [flags] are optional, and can include:

· A minus sign ( - ) to left justify the output. Default is right justified.

· A plus sign ( + ) to force a sign to be printed.

· zero ( 0 ) to left pad the number with zeros instead of spaces

· With octal or hexidecimal output, specifies a leading 0 or 0x for non-zero data values

#include

int main()

{

int integer = 9876;

float decimal = 987.6543;

// Prints the number right justified within 6 columns

printf("4 digit integer right justified to 6 column: %6d\n", integer);

// Tries to print number right justified to 3 digits but the number is not right adjusted because there are only 4 numbers

printf("4 digit integer right justified to 3 column: %3d\n", integer);

// Rounds to two digit places

printf("Floating point number rounded to 2 digits: %.2f\n",decimal);

// Rounds to 0 digit places

printf("Floating point number rounded to 0 digits: %.f\n",987.6543);

// Prints the number in exponential notation(scientific notation)

printf("Floating point number in exponential form: %e\n",987.6543);

return 0;

}

Output

4 digit integer right justified to 6 column: 9876

4 digit integer right justified to 3 column: 9876

Floating point number rounded to 2 digits: 987.65

Floating point number rounded to 0 digits: 988

Floating point number in exponential form: 9.876543e+02

Operators

Arithmetic operators

C Language supports all the basic arithmetic operators. The basic arithmetic operators supported by C language are as follows.

Operator

Description

+

Perform addition of operands

-

subtract second operand from the first

*

multiply two operand

/

divide numerator by denominator

%

remainder of division(Modular division)

Relational operators

The following table shows all relation operators supported by C.

Operator

Description

==

Check whether two operands are equal

!=

Check whether two operands are not equal.

>

Check if operand on the left side is larger than operand on the right side

<

Check operand on the left is smaller than right operand

>=

check left operand is greater than or equal to right operand

<=

Check if operand on left is smaller than or equal to right operand

Logical operators

C language supports following logical operators.

Operator

Description

&&

Logical AND

||

Logical OR

!

Logical NOT

Bitwise operators

Bitwise operators are useful for manipulating data at bit level. These operators also perform shifting of bits from right to left.

Operator

Description

&

Bitwise AND

|

Bitwise OR

^

Bitwise exclusive OR

<<

left shift

>>

right shift

Assignment Operators

Assignment operators supported by C language are given below.

Operator

Description

=

assigns values from right side operands to left side operand

+=

adds right operand to the left operand and assign the result to left

-=

subtracts right operand from the left operand and assign the result to left operand

*=

multiply left operand with the right operand and assign the result to left operand

/=

divides left operand with the right operand and assign the result to left operand

%=

calculate modulus using two operands and assign the result to left operand

Conditional operator

The conditional operators in C language are known as ternary operator (? :)

The syntax of a conditional operator is :

Expression1? Expression2: Expression3

It evaluate the first expression (expression 1) . If (expression 1) returns true then the expression on the left side of " : " i.e (expression 2) is executed. Otherwise the expression on the right side of " : " i.e (expression 3) is executed.

Special operator

Operator

Description

Example

sizeof

Returns the size of an variable

sizeof(x) return size of the variable x

&

Returns the address of an variable

&x ; return address of the variable x

*

Pointer to a variable

*x ; will be pointer to a variable x

Increment and Decrement Operators

C programming has two operators increment ++ and decrement -- to change the value of an operand (constant or variable) by 1.Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. These two operators are unary operators, meaning they only operate on a single operand.

Increment and decrement operator as prefix and postfix

If you use the ++ operator as prefix such as  ++var, The value of var is incremented by 1 then, it returns the value.

Ex:

Let x=5

y=++x(The incremented value of x is assigned to y)

after the execution of the above statement the value of x and y are 6,6

If you use the ++ operator as postfix like: var++, The original value of var is returned first then, var is incremented by 1.

Ex:

Let x=5

y=x++(The old value of x is assigned to y and the x value is incremented by 1)

after the execution of the above statement the value of x and y are 6,5

The -- operator works in a similar manner except it decreases the value by 1.

Expressions

Arithmetic Expressions

An arithmetic expression is an expression that consists of operands and arithmetic operators.

Ex: a+b*c-(d/2)

Relational Expressions

A relational expression is an expression used to compare two operands. In relational expressions, a numeric value cannot be compared with the string value. The result of the relational expression can be either zero or non-zero value. Here, the zero value is equivalent to a false and non-zero value is equivalent to true.

#include   

 int main()  

{  

      

    int x=4;  

    if(x%2==0) //relational expression 

    {  

        printf("The number x is even");  

    }  

    else  

    printf("The number x is not even");  

    return 0;  

}  

Logical Expressions

A logical expression is an expression that combines two or more relational expression.

include   

int main()  

{  

    int x = 4;  

    int y = 10;  

    if ( (x <10) && (y>5))  //combine two relation expression using the logical operator &&

    {  

        printf("Condition is true");  

    }  

    else  

    printf("Condition is false");  

    return 0;  

}  

Conditional expressions

An expression which include conditional operators or ternary operator (? :) is called as conditional expression.

include   

int main()  

{  

    int x = 4;  

    int y = 10;  

   c= x>y ? x: y;// conditional expression to find largest of two numbers

printf(“largest among two is %d”, c);

return 0;

}

 Precedence and Associativity

Operator precedence: It determines which operator is performed first in an expression with more than one operator with different precedence.

Operators Associativity: It is used when two operators of same precedence appear in an expression. Associativity can be either left to right or right to left.

Expression Evaluation

Evaluation of Arithmetic Expressions

The expressions are evaluated by performing one operation at a time. The precedence and associativity of operators decide the order of the evaluation of individual operations.

When individual operations are performed, the following cases can be happened:

When both the operands are of type integer, then arithmetic will be performed, and the result of the operation would be an integer value. For example, 5/2 will give the value 2 not 2.5 as the fractional part is ignored.

When both the operands are of type float, then arithmetic will be performed, and the result of the operation would be a real value. For example, 6.0/2.0 will yield 3.0, not 3.

If one operand is of type integer and another operand is of type real, then the mixed arithmetic will be performed. In this case, the first operand is converted into a real operand, and then arithmetic is performed to produce the real value. For example, 6/2.0 will yield 3.0 as the first value of 6 is converted into 6.0 and then arithmetic is performed to produce 3.0.

Let's understand through an example.

6*2/ (2+1 * 2/3 + 6) + 8 * (8/4)

Evaluation of expression

Description of each operation

6*2/( 2+1 * 2/3 +6) +8 * (8/4)

An expression is given.

6*2/(2+2/3 + 6) + 8 * (8/4)

2 is multiplied by 1, giving value 2.

6*2/(2+0+6) + 8 * (8/4)

2 is divided by 3, giving value 0.

6*2/ 8+ 8 * (8/4)

2 is added to 6, giving value 8.

6*2/8 + 8 * 2

8 is divided by 4, giving value 2.

12/8 +8 * 2

6 is multiplied by 2, giving value 12.

1 + 8 * 2

12 is divided by 8, giving value 1.

1 + 16

8 is multiplied by 2, giving value 16.

17

1 is added to 16, giving value 17.

Type casting

Typecasting is converting one data type into another one. It is also known as data conversion or type conversion. 'C' programming provides two types of type casting operations:

1. Implicit type casting

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 happens automatically when a value is copied to its compatible data type. Conversion hierarchy is as shown below.

include

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

}

We cannot perform implicit type casting on the data types which are not compatible with each other such as:

Converting float to an int will truncate the fraction part hence losing the meaning of the value.

Converting double to float will round up the digits.

Converting long int to int will cause dropping of excess high order bits.

In all the above cases, when we convert the data types, the value will lose its meaning. Generally, the loss of meaning of the value is warned by the compiler.

2.Explicit type casting

Explicit type conversion uses the unary cast operator, to convert data from one type to another. To cast data from one type to another, we specify the new type in parentheses before the value we want converted.

int main() 

{ int a , b;

   float c; 

   a=5;

   b=2; 

   c=(float)a/b; 

   printf("%d",c); 

return 0;

}

References

Reema Thareja, Programming in C, Second edition, Oxford Press

Behrouz A. Forouzan | Richard F. GilbergProgramming for Problem Solving, Cengage

Byron S Gottfried, Programming with C, fourth edition, Schaum's Outlines

https://www.javatpoint.com/

https://computerscience4beginners.wordpress.com/

https://sites.google.com/site/cppprogram123/basic-c-programming/

https://www.studytonight.com/c/

https://www.sanfoundry.com/c-interview-questions-answers/

MODULE II

CONTENTS

MODULE II: Conditional statements and Repetition statements [09 Periods]

Conditional Statements: simple if statement, if-else statement, if-elseif- ladder, nested if-

else, Dangling else problem, switch statements

Repetition statements – while, for, do-while statements, nested looping, other statements

related to looping – break, continue, goto, Simple C Programming examples.

Control statements help us to specify the flow of program control; which represent the order in which the instructions in a program must be executed..

The main control statements in C:

1. Conditional statements

1. Repetition statements

1. Jump statements

Conditional Statements

Also called as branching statements. It is known so because it decide what action to take based on particular condition. The following are the decision making statements.

(a)Simple if statement

Syntax:-

if (test expression)

{

statement block;

}

statement–x ;

If the test expression is true statement block will be executed. Then statements outside the block will be executed. On the other hand if the test expression is false only statement x will be executed.

Flowchart:

Sample code:

#include

void main()

{

int sal,age;

printf(“Enter the salary\n”); scanf(“%d”,&sal);

printf(“Enter the age\n”);

scanf(%d”, &age);

if (age>=65)

{

sal=sal+1000;

}

printf(“salary is %d”,sal);

}

Sample output:

Enter the salary 6500

Enter the age 67

Salary is 7500

(b) If-else statement

Syntax:-

if (test expression)

{

statement block1;

}

else

{

statement block2;

}

statement –x ;

If the test expression is true statement block1 followed by statement-x is executed. Otherwise statement block2 followed by statement x is executed

Flowchart:

Sample code:

#include

void main()

{

int a,b;

printf(“Read two numbers\n”); scanf(“%d%d”,&a,&b);

if (a>b)

printf(“ first number is largest\n”)

else

printf(“second number is largest\n”);

}

Sample output:

Read two numbers 17 90

second number is largest

( c) Nested if-else statement

Whenever we want to check multiple interdependent conditions we use nested if else statement

Syntax:-

if(text cond1)

{

if (test con2)

{

statement block1;

}

else

{

statement block 2;

}

}

else

{

statement block2;

}

statement-x ;

Flowchart:

Sample code:

#include

void main()

{

int a,b;

printf(“Read three numbers\n”); scanf(“%d%d%d”,&a,&b,&c);

if (a>b)

{

if(a>c)

{

printf(“%d is largest”,a);

}

else

{

printf(“%d is largest”,c);

}

}

else

{

if(b>c)

{

printf(“%d is largest”,b);

}

else

{

printf(“%d is largest”,c);

}

}

getch();

}

Sample output:

Read three numbers 7 90 100

100 is largest

(d) if-elseif ladder statement

Syntax:

if(condition1)

statement1;

elseif(condition2)

statement 2;

elseif(condition3)

statement 3;

else

statement;

statement-x;

Flowchart:

Sample code:

#include

void main()

{

int opt;

printf(“Enter option\n”); scanf(“%d”, &opt);

if(opt==1)

{

printf(“color is red”);

}

elseif(opt==2)

{

printf(“color is white”);

}

elseif(opt==3)

{

printf(“color is blue”);

}

else

{

printf(“color is blue”);

}

}

getch ();

}

Sample output:

Enter option 2

color is white

Dangling Else problem

It explains the association of single else statement in a nested if statement. In nested if statements, when a single “else clause” occurs, the situation happens to be dangling else

if (condition)

if (condition)

if (condition)

else

printf("dangling else!\n");

(e) The Switch statement :

Also called as multidecision statement.

Syntax:

switch(expression)

{

case value-1

block- 1 break;

case value-2

block- 2 break;

----------------

default:

default block;

}

statement–x;

Flowchart:

Sample code:

#include

void main()

{

int marks,index;

char grade[10];

printf(“Enter your marks”); scanf(“%d”,&marks); index=marks/10;

switch(index)

{

case 10 :

case 9:

case 8:

case 7:

case 6: grade=”first class”; break;

case 5 : grade=”second class”; break;

case 4 : grade=”third class”; break;

default : grade =”fail”; break;

}

printf(“Grade is %s”,grade);

}

Sample output:

Enter your marks 80

Grade is first class

Repetition statement:

Sometimes we require a set of statements to be executed repeatedly until a condition is satisfied.

We have two types of looping structures.

1. Entry controlled

1. Exit controlled

I. Entry controlled statement

1. While statement

It is an entry controlled statement. The condition is evaluated and if it is true then body of loop is executed. After execution of body, the condition is once again evaluated and if is true body is executed once again. This process repeat until test condition becomes false.

Syntax:

while(test condition)

{

body of the loop

}

Flowchart:

Sample code:

#include

void main()

{

int n=0,limit;

printf(“Enter the limit”);

scanf(“%d”,&limit);

while(n<=limit)

{

n=n+1;

printf(“%d\t”,n);

}

}

Sample output:

Enter the limit 7

1 2 3 4 5 6 7

1. For statement:

.

Syntax:

for(initialization; test control; increment/decrement)

{

body of loop;

}

It is also an entry control statement. Initialization of the variable will be done only once during the first time execution of the loop. After that condition is checked. If the condition is true then body of the loop is executed. Now modification of control variable is done and condition will be checked again. This process will continue till the condition become false

Flowchart:

Sample code:

#include

void main()

{

int n,limit;

printf(“Enter the limit”);

scanf(“%d”,&limit);

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

{

printf(“%d\t”,n);

}

}

Sample output:

Enter the limit 9

1 2 3 4 5 6 7 8 9

II. Exit controlled statement

(a ) do-while statement

The do while is an exit controlled loop and its body is executed at least once. Initially the body of the loop is executed without checking any condition. Later the condition is checked and the body of the loop is executed until the condition become false.

Syntax:

do

{

body of the loop;

}while(test condition);

Flowchart:

Sample code:

#include

void main()

{

int n=0,limit;

printf(“Enter the limit”);

scanf(“%d”,&limit);

do

{

n=n+1;

printf(“%d\t”,n);

} while(n<=limit);

}

Sample output:

Enter the limit 4

1 2 3 4

III. jump statement

1. break statement:

It is used to terminate from the loop. When a break statement is found inside a loop the control is automatically transferred to first stament after the loop.

Syntax:

break;

Flowchart:

Sample code:

#include

void main()

{

int i=0,n;

printf(“Enter the value of n”);

scanf(“%d”,&n);

while(i<=n)

{

i=i+1;

if(i%3==0)

{

break;

}

printf(“%d\n”,i);

}

getch();

}

Sample output:

Enter the value of n 10

1 2

(b)continue statement:

When a continue statement is found inside a loop the control is transferred to beginning of the loop by passing statements which has not been executed.

Syntax:

continue;

Flowchart:

Sample code:

#include

void main()

{

int i=0,n;

printf(“Enter the value of n”);

scanf(“%d”,&n);

while(i<=n)

{

i=i+1;

if(i%3==0)

{

continue;

}

printf(“%d\n”,i);

}

getch();

}

Sample output:

Enter the value of n 10

1 2 4 5 7 8 10

(c) goto statements:

Also known as unconditional jump or branching statement because it transfer the control to another part of the program without checking any condition.

Syntax:

goto label;

where goto is a reserved keyword and label is the name of the statement to which control has to be transferred. Label name must be unique and is followed by colon.

Flowchart:

Sample code:

#include

void main()

{

printf(“hello\n”);

goto name;

printf(“students\n”);

printf(“mrec\n”);

name:

printf(“Good bye\n”);

getch();

}

Sample output:

Hello

Good bye

Reference for images: programiz.com, geekstogeek.com,beginnersbook.com, https://www.sanfoundry.com/

MODULE III

Designing Structured Programs and Arrays

Part A:

Designing Structured Programs-Introduction to function, Advantages, user defined functions, inter function communication-call by value, Storage classes-auto, register, static, extern, scope rules, type qualifiers, recursion – recursive functions-Towers of Hanoi problem.

Part B:

Arrays: Basic Concepts, Types of arrays, applications- Selection sort, Bubble sort, Insertion sort, Linear search and Binary search methods, arrays and functions.

Introduction to function and User defined functions:

A function is a group of statements that together perform a task. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions.

You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division is such that each function performs a specific task.

A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function.

A function can also be referred as a method or a sub-routine or a procedure, etc.

Defining a Function

The general form of a function definition in C programming language is as follows −

return_type function_name( parameter list ) {

body of the function

}

A function definition in C programming consists of a function header and a function body. Here are all the parts of a function −

Return Type − A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.

Function Name − This is the actual name of the function. The function name and the parameter list together constitute the function signature.

Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.

Function Body − The function body contains a collection of statements that define what the function does.

Example

Given below is the source code for a function called max(). This function takes two parameters num1 and num2 and returns the maximum value between the two −

/* function returning the max between two numbers */

int max(int num1, int num2) {

/* local variable declaration */

int result;

if (num1 > num2)

result = num1;

else

result = num2;

return result;

}

Function Declarations

A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately.

A function declaration has the following parts −

return_type function_name( parameter list );

For the above defined function max(), the function declaration is as follows −

int max(int num1, int num2);

Parameter names are not important in function declaration only their type is required, so the following is also a valid declaration −

int max(int, int);

Function declaration is required when you define a function in one source file and you call that function in another file. In such case, you should declare the function at the top of the file calling the function.

Calling a Function

While creating a C function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform the defined task.

When a program calls a function, the program control is transferred to the called function. A called function performs a defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns the program control back to the main program.

To call a function, you simply need to pass the required parameters along with the function name, and if the function returns a value, then you can store the returned value. For example −

#include

/* function declaration */

int max(int num1, int num2);

int main () {

/* local variable definition */

int a = 100;

int b = 200;

int ret;

/* calling a function to get max value */

ret = max(a, b);

printf( "Max value is : %d\n", ret );

return 0;

}

/* function returning the max between two numbers */

int max(int num1, int num2) {

/* local variable declaration */

int result;

if (num1 > num2)

result = num1;

else

result = num2;

return result;

}

Output : Max value is :200

Advantages of Functions:

The advantages of using functions are:

· Avoid repetition of codes.

· Increases program readability.

· Divide a complex problem into simpler ones.

· Reduces chances of error.

· Modifying a program becomes easier by using function.

Inter function Communication in C Language

There are two methods to pass the data into the function in C language, i.e., call by value and call by reference.

Call by value in C

· In call by value method, the value of the actual parameters is copied into the formal parameters. In other words, we can say that the value of the variable is used in the function call in the call by value method.

· In call by value method, we can not modify the value of the actual parameter by the formal parameter.

· In call by value, different memory is allocated for actual and formal parameters since the value of the actual parameter is copied into the formal parameter.

· The actual parameter is the argument which is used in the function call whereas formal parameter is the argument which is used in the function definition.

Call by Value Example: Swapping the values of the two variables

#include

void swap(int , int); //prototype of the function

int main()

{

int a = 10;

int b = 20;

printf("Before swapping the values in main a = %d, b = %d\n",a,b);

// printing the value of a and b in main swap(a,b);

printf("After swapping values in main a = %d, b = %d\n",a,b);

/*The value of actual parameters do not change by changing the formal parameters in call by value, a = 10, b = 20 */

}

void swap (int a, int b)

{

int temp;

temp = a;

a=b;

b=temp;

printf("After swapping values in function a = %d, b = %d\n",a,b);

// Formal parameters, a = 20, b = 10

}

Output:

Before swapping the values in main a = 10, b = 20

After swapping values in function a = 20, b = 10

After swapping values in main a = 10, b = 20

Call by reference in C

· In call by reference, the address of the variable is passed into the function call as the actual parameter.

· The value of the actual parameters can be modified by changing the formal parameters since the address of the actual parameters is passed.

· In call by reference, the memory allocation is similar for both formal parameters and actual parameters. All the operations in the function are performed on the value stored at the address of the actual parameters, and the modified value gets stored at the same address.

Call by reference Example: Swapping the values of the two variables

#include

void swap(int *, int *); //prototype of the function

int main()

{

int a = 10;

int b = 20;

printf("Before swapping the values in main a = %d, b = %d\n",a,b);

// printing the value of a and b in main swap(&a,&b);

printf("After swapping values in main a = %d, b = %d\n",a,b);

// The values of actual parameters do change in call by reference, a = 10, b = 20

}

void swap (int *a, int *b)

{

int temp;

temp = *a;

*a=*b;

*b=temp;

printf("After swapping values in function a = %d, b = %d\n",*a,*b);

// Formal parameters, a = 20, b = 10

}

Output:

Before swapping the values in main a = 10, b = 20

After swapping values in function a = 20, b = 10

After swapping values in main a = 20, b = 10

Storage Classes in C

Storage Classes are used to describe the features of a variable/function. These features basically include the scope, visibility and life-time which help us to trace the existence of a particular variable during the runtime of a program.

C language uses 4 storage classes, namely:

auto, register,static,extern

Auto Storage Class in C

The variables defined using auto storage class are called as local variables. Auto stands for automatic storage class. A variable is in auto storage class by default if it is not explicitly specified.

The scope of an auto variable is limited with the particular block only. Once the control goes out of the block, the access is destroyed. This means only the block in which the auto variable is declared can access it.

A keyword auto is used to define an auto storage class. By default, an auto variable contains a garbage value.

Example: auto int age;

The program below defines a function with has two local variables

int add(void) {

int a=13;

auto int b=48;

return a+b;}

We take another program which shows the scope level "visibility level" for auto variables in each block code which are independently to each other:

#include

int main( )

{

auto int j = 1;

{

auto int j= 2;

{

auto int j = 3;

printf ( " %d ", j);

}

printf ( "\t %d ",j);

}

printf( "%d\n", j);}

OUTPUT:

3 2 1

Register Storage Class in C

You can use the register storage class when you want to store local variables within functions or blocks in CPU registers instead of RAM to have quick access to these variables. For example, "counters" are a good candidate to be stored in the register.

Example: register int age;

The keyword register is used to declare a register storage class. The variables declared using register storage class has lifespan throughout the program.

It is similar to the auto storage class. The variable is limited to the particular block. The only difference is that the variables declared using register storage class are stored inside CPU registers instead of a memory. Register has faster access than that of the main memory.

The variables declared using register storage class has no default value. These variables are often declared at the beginning of a program.

#include /* function declaration */

main()

{

register int weight;

int *ptr=&weight ;/*it produces an error when the compilation occurs ,we cannot get a memory location when dealing with CPU register*/

}

OUTPUT:

error: address of register variable 'weight' requested

Static Variables in C

Static variables have a property of preserving their value even after they are out of their scope. Hence, static variables preserve their previous value in their previous scope and are not initialized again in the new scope.

Syntax:

static data_type var_name = var_value;

Following are some interesting facts about static variables in C.

1) A static int variable remains in memory while the program is running. A normal or auto variable is destroyed when a function call where the variable was declared is over.

For example, we can use static int to count a number of times a function is called, but an auto variable can’t be used for this purpose.

#include

int fun()

{

static int count = 0;

count++;

return count;

}

int main()

{

printf("%d ", fun());

printf("%d ", fun());

return 0;

}

Output:

1 2

Example without static

#include

int fun()

{

int count = 0;

count++;

return count;

}

int main()

{

printf("%d ", fun());

printf("%d ", fun());

return 0;

}

Output:

1 1

External variables in C language

External variables are also known as global variables. These variables are defined outside the function. These variables are available globally throughout the function execution. The value of global variables can be modified by the functions. “extern” keyword is used to declare and define the external variables.

Scope − They are not bound by any function. They are everywhere in the program i.e. global.

Default value − Default initialized value of global variables are Zero.

Lifetime − Till the end of the execution of the program.

Here are some important points about extern keyword in C language,

External variables can be declared number of times but defined only once.

“extern” keyword is used to extend the visibility of function or variable.

By default the functions are visible throughout the program, there is no need to declare or define extern functions. It just increase the redundancy.

Variables with “extern” keyword are only declared not defined.

Initialization of extern variable is considered as the definition of the extern variable.

Here is an example of extern variable in C language

Example

#include

extern int x = 32;

int b = 8;

int main() {

auto int a = 28;

extern int b;

printf("The value of auto variable : %d\n", a);

printf("The value of extern variables x and b : %d,%d\n",x,b);

x = 15;

printf("The value of modified extern variable x : %d\n",x);

return 0;

}

Output

The value of auto variable : 28

The value of extern variables x and b : 32,8

The value of modified extern variable x : 15

Scope rules in C

A scope in any programming is a region of the program where a defined variable can have its existence and beyond that variable it cannot be accessed. There are three places where variables can be declared in C programming language −

Inside a function or a block which is called local variables.

Outside of all functions which is called global variables.

In the definition of function parameters which are called formal parameters.

Let us understand what are local and global variables, and formal parameters.

Local Variables

Variables that are declared inside a function or block are called local variables. They can be used only by statements that are inside that function or block of code. Local variables are not known to functions outside their own. The following example shows how local variables are used. Here all the variables a, b, and c are local to main() function.

#include

int main () {

/* local variable declaration */

int a, b;

int c;

/* actual initialization */

a = 10;

b = 20;

c = a + b;

printf ("value of a = %d, b = %d and c = %d\n", a, b, c);

return 0;

}

Global Variables

Global variables are defined outside a function, usually on top of the program. Global variables hold their values throughout the lifetime of your program and they can be accessed inside any of the functions defined for the program.

A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration. The following program show how global variables are used in a program.

#include

/* global variable declaration */

int g;

int main () {

/* local variable declaration */

int a, b;

/* actual initialization */

a = 10;

b = 20;

g = a + b;

printf ("value of a = %d, b = %d and g = %d\n", a, b, g);

return 0;

}

A program can have same name for local and global variables but the value of local variable inside a function will take preference. Here is an example −

#include

/* global variable declaration */

int g = 20;

int main () {

/* local variable declaration */

int g = 10;

printf ("value of g = %d\n", g);

return 0;

}

When the above code is compiled and executed, it produces the following result −

value of g = 10

Formal Parameters

Formal parameters, are treated as local variables with-in a function and they take precedence over global variables. Following is an example −

#include

/* global variable declaration */

int a = 20;

int main () {

/* local variable declaration in main function */

int a = 10;

int b = 20;

int c = 0;

printf ("value of a in main() = %d\n", a);

c = sum( a, b);

printf ("value of c in main() = %d\n", c);

return 0;

}

/* function to add two integers */

int sum(int a, int b) {

printf ("value of a in sum() = %d\n", a);

printf ("value of b in sum() = %d\n", b);

return a + b;

}

When the above code is compiled and executed, it produces the following result −

value of a in main() = 10

value of a in sum() = 10

value of b in sum() = 20

value of c in main() = 30

Initializing Local and Global Variables

When a local variable is defined, it is not initialized by the system, you must initialize it yourself. Global variables are initialized automatically by the system when you define them as follows −

Data TypeInitial Default Value

int0

char'\0'

float0

double0

pointerNULL

It is a good programming practice to initialize variables properly, otherwise your program may produce unexpected results, because uninitialized variables will take some garbage value already available at their memory location

TYPES OF C TYPE QUALIFIERS:

There are two types of qualifiers available in C language. They are,

const

volatile

1. CONST KEYWORD:

Constants are also like normal variables. But, only difference is, their values can’t be modified by the program once they are defined.

They refer to fixed values. They are also called as literals.

They may be belonging to any of the data type.

Syntax:

const data_type variable_name; (or) const data_type *variable_name;

2. VOLATILE KEYWORD:

When a variable is defined as volatile, the program may not change the value of the variable explicitly.

But, these variable values might keep on changing without any explicit assignment by the program. These types of qualifiers are called volatile.

For example, if global variable’s address is passed to clock routine of the operating system to store the system time, the value in this address keep on changing without any assignment by the program. These variables are named as volatile variable.

Syntax:

volatile data_type variable_name; (or) volatile data_type *variable_name;

RECURSIVE FUNCTIONS:

Recursion is a repetitive process in which a function calls itself (or) A function is called recursive if it calls itself either directly or indirectly. In C, all functions can be used recursively.

Example: Fibonacci Numbers

A recursive function for Fibonacci numbers (0,1,1,2,3,5,8,13...)

/* Function with recursion*/

int fibonacci(int n)

{

if (n <= 1)

return n;

else

return (fibonacci(n-1) + fibonacci(n-2));

}

With recursion 1.4 x 10 9 function calls needed to find the 43rd Fibonacci number(which has the value 433494437) .If possible, it is better to write iterative functions.

int factorial (int n) /* iterative version */

{

for ( ; n > 1; --n)

product *= n;

return product;

}

C Program for Tower of Hanoi

Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:

1) Only one disk can be moved at a time.

2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.

3) No disk may be placed on top of a smaller disk.

// C recursive function to solve tower of hanoi puzzle

void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod)

{

if (n == 1)

{

printf("\n Move disk 1 from rod %c to rod %c", from_rod, to_rod);

return;

}

towerOfHanoi(n-1, from_rod, aux_rod, to_rod);

printf("\n Move disk %d from rod %c to rod %c", n, from_rod, to_rod);

towerOfHanoi(n-1, aux_rod, to_rod, from_rod);

}

int main()

{

int n = 4; // Number of disks

towerOfHanoi(n, \'A\', \'C\', \'B\'); // A, B and C are names of rods

return 0;

}

ARRAYS :

An array is a group of related data items that share a common name.

Ex:- Students

The complete set of students are represented using an array name students. A particular value is indicated by writing a number called index number or subscript in brackets after array name. The complete set of value is referred to as an array, the individual values are called elements.

ONE – DIMENSIONAL ARRAYS :

A list of items can be given one variable index is called single subscripted variable or a one-dimensional array.

The subscript value starts from 0. If we want 5 elements the declaration will be

int number[5];

The elements will be number[0], number[1], number[2], number[3], number[4]

There will not be number[5]

Declaration of One - Dimensional Arrays :

Type variable – name [sizes];

Type – data type of all elements Ex: int, float etc.,

Variable – name – is an identifier

Size – is the maximum no of elements that can be stored.

Ex:- float avg[50]

This array is of type float. Its name is avg. and it can contains 50 elements only. The range starting from 0 – 49 elements.

Initialization of Arrays :

Initialization of elements of arrays can be done in same way as ordinary variables are done when they are declared.

Type array name[size] = {List of Value};

Ex:- int number[3]={0,0,0};

If the number of values in the list is less than number of elements then only that elements will be initialized. The remaining elements will be set to zero automatically.

Ex:- float total[5]= {0.0,15.75,-10};

The size may be omitted. In such cases, Compiler allocates enough space for all initialized elements.