--> Sayadasite: INTRODUCTION TO PROGRAMMING

Multiple Ads

Search

Menu Bar

INTRODUCTION TO PROGRAMMING

UNIT I 

Languages are a means of communication. Normally people interact with each other through a language. On the same pattern, communication with computers is carried out through a language. This language is understood both by user and the machine. The Programming language is the medium of communication between the man and the machine. Programming is a set of instructions given to the computer to perform user defined tasks.

PROBLEM SOLVING

Problem solving by the computer involves the following steps.

1)       Problem Definition 

2)       Analysis   

3)       Algorithm

4)       Flowchart

5)       Coding

6)       Running the program

7)       Debugging

8)       Testing

9)       Documentation

1 PROBLEM DEFINITION

This is the first step in computer problem solving. The problem solver should understand the problem thoroughly in terms of the requirements. That is, what are the input and output operations to be performed? The programmer should extract from the problem statement, a set of well-defined and precise tasks that can be carried out.

2 ANALYSIS

The given problem must be analyzed before it is solved. This determines the data items, their types and relationship. We should specify the operations (Arithmetic and logic) to be performed on them and checking the suitability in terms of memory and execution time.

3 ALGORITHM

This is a problem solving technique. It can be defined as a step by step procedure to solve a particular problem. It consists of English like statements. Each statement must be precise and well defined to perform a specific operation. When these statements are carried out for a given set of conditions, they will produce the required results. The word algorithm is derived from the famous Arabic author and mathematician, Abu Jafar Mohammad Ibn Musa Al Khowarizmi. The last two terms of the name termed as Algorithm.

CHARACTERISTICS OF ALGORITHM

Each and every algorithm is characterized by the following five important characteristics.

1 Input : It may accept zero or more inputs

2 Outputs : It should produce at least one output (result)

3 Definiteness : Each instruction must be clear, well-defined and precise. There should not be any ambiguity.

4 Finiteness : It should be a sequence of finite instructions. That is, it should end finite time at one or more levels of complexity. It should be effective whenever trace manually for the results.

5 Effectiveness : This means that operations must be simple and are carried out in a finite time at one or more levels of complexity. It should be effective whenever traced manually for the results.

ALGORITHMIC NOTATIONS

While writing algorithms the following notations are considered.

1)            Name of the Algorithm : It specifies the problem to be solved.

2)            Step number : Identification tag of an instruction and it is an unsigned positive integer

3)            Explanatory Comment : It follows the step number and describes the operation. It should  be written within a pair of square brackets.

4)            Termination : It specifies the end of the algorithm. It is generally a Stop statement and the last instruction in the algorithm.

Example 1

Algorithm to compute the area of circle

Algorithm : Area of Circle Step 1 : Start

Step 2 : Read radius

Step 3 : [Compute the Area]

Area = 3.142 x radius x radius Step

4 : [Print the Area]

Print “Area of Circle = ”, Area Step

5 : [End of algorithm]

Stop

Example 2

Algorithm to calculate the simple interest.

Algorithm : Simple Interest Step 1 : Start

Step 2 : [Read the value P, T, R]

Read P, T, R

Step 3 : [Compute the Simple Interest]

SI = ( PxTxR) / 100

Step 4 : [Print the Simple Interest]

Print “Simple Interest= ”, SI Step 5 : [End of algorithm]

Stop

Example 3

Algorithm to find the largest of two numbers.

Algorithm : Largest of two numbers

Step 1 : Start

Step 2 : [Read the values A and B]

Read A, B

Step 3 : [Compare A and B]

If (A>B) Then

Print ‘A is largest’

Else

Print ‘B is largest’

End If

Step 6 : [End of algorithm]

Stop

4 FLOWCHART

This is a chart showing a flow of logic involved in solving a problem. This is defined for an algorithm. The flowchart can be defined as a diagrammatic representation of an algorithm. It is referred to as the blue print of an algorithm. It is also defined as a visual or graphical representation of an algorithm. The flowchart is an easy way to understand and analyze the problem. It is a useful aid

for programmers and system analysts.

Flowcharts make use of geometric figures, to specify a particular operation. Those are

 

Geometrical Figure

Name

Function

 

 

Oval

 

Start and Stop

 

 

Parallelogram

 

Input and Output

 

 

Rectangle

 

Processing

 

 

Rhombus

 

Decision Making

 

 

Arrows

 

Connections

 

 

Circle

 

Continuation

 

 

Hexagon

 

Repetition / Looping

 

Example 1 :   Draw a flowchart to find area of triangle


Example 2 : Draw a flowchart to find the Simple Interest.

 

 


5 CODING

The complete structure of a problem to be solved by a computer is called a program. The computer does not process an algorithm or a flowchart, but executes the program. A program is a set of instructions to solve a particular problem by the computer and the actual process of writing a program is called coding. Program are written using programming languages and are fed to the computer.

6 RUNNING THE PROGRAM :

The program can be run(executed) in the central processing unit. This phase of problem solving by a computer involves three steps.

1)                  Understand the instructions

2)                  Store data and instructions

3)                  Perform computations

The user prepares his/her program and makes it ready for execution. All the instructions stored in the RAM, must be fetched one by one to the ALU to perform corresponding operations. This is called the fetch/execute cycle. The processed data is stored again in the RAM. Finally, they are transferred to the output devices.

7 DEBUGGING

The process of detecting and correcting errors(mistakes) in the program is known as debugging. There is a program called debugger that takes object program as input and executes it and helps in eliminating the mistakes that occur in the source program.

Generally, programmers commit three types of errors. These are,

1)                  Syntax Errors

2)                  Logical Errors

3)                  Run-time Errors

SYNTAX ERRORS

This type of errors is the result of violation of programming rules. On encountering these errors a computer displays error message specifying the line number. It is easy to debug these errors. For Example: If the statement of C is typed without the semicolon at the end, then there will be an error because of a missing semicolon.

LOGICAL ERRORS

Logical errors occur during coding process. When the programmer codes his problem, he must take care of correct operations to be performed. The program will be executed but produce some unwanted results. It is very difficult to debug such errors, because the computer does not display them. We can eliminate such errors by tracing it and running for sample data.

RUN-TIME ERRORS

These errors occur when we attempt to run an ambiguous instructions. For example, an infinite loop in program sequence which causes no output. These are also occur due to device errors, improper sequencing of constructs, errors in system software, incorrect data input etc., The computer will print error message. Some of run-time errors are:

1)                  Divide by zero

2)                  Null pointer assignment

3)                  Data overflow

8 TESTING

The process of executing the program to test the correctness of the outputs of the problem is called testing. The program is tested by executing with different sets of data. Logical errors are the outcome of this process.

9 DOCUMENTATIONS

While writing programs, it is good programming practice to make a brief explanatory note on the program or program segments. This explanatory note is called a comment. It explains how the program works and how to interact with it. Thus, it helps other programmers to understand the program.

There are two types of documentation. They are,

1)                  Internal documentation

2)                  External documentation

INTERNAL DOCUMENTATION

This documentation is a comment statement within a program. It describes the function of the program or program segments. These statements are not translated to machine language. Translators simply discard these statements during the translation process.

EXTERNAL DOCUMENTATION

This documentation is an executable statement in a program. It may be a message to the user to respond to the program requirement. This is accomplished using output statements. It makes the program more attractive and interactive. Some sample examples are given below:

Print, “Input numbers one by one” Print, “Input the order of the matrix” Print, “Do you what to continue ?”

INTRODUCTION TO C

C is a high level language. It is both general purpose and specific purpose programming language. Now a days, C has become a common programming language for every application developer. It was developed at Bell & T Laboratory, USA in 1972. It is the outcome of the efforts of Dennis Ritchie and Brian Kernighan.

C is derived from two early programming languages such as BCPL (Basic Combined Programming Language) and B Language. The BCPL was developed by Martin Richards. And, B was developed by Ken Thompson.

In 1972, Dennis Ritchie developed a new version of B and named it as C. He selected the name C for his new language because C comes after B in the alphabetical order which indicates advancement to B. Some sources also say that Dennis Ritchie selected the second character of BCPL for naming his language.

In 1978, Dennis Ritchie and Brian Kernighan jointly published a detailed description of the C Language document. It is known as “K & R C”. It was released to commercial applications in 1978.

CHARACTERISTICS OF C

C has become popular programming language because of its many features. The important characteristics of C are :

·        C is a general purpose programming language

·        C is a structured programming language

·        Helps in development of System Software

·        It has rich set of operators

·        It provides compact representation for expressions

·        It allows manipulation of internal processor registers

·        No rigid format. Any number of statements can be typed in a single line.

·        Portability : any C program can be run on different machines with little or not modification.

·        Supports a rich set of data types

·        Very less number of reserved words

·        Pointer arithmetic and pointer manipulation

·        Ability to extend itself by adding functions to its library

APPLICATIONS OF C

Because of its portability and efficiency, C is used to develop the system as well as application software. Some of the system and application software are listed below.

System Software

Operating Systems

Interpreters

Compilers

Assemblers

Editors

Loaders

Linkers

Application Software

Data Base Systems

Graphic Packages

Spread Sheets

CAD/CAM Application

Word Processors

Office Automation Tools

Scientific and Engineering Applications

BASIC STRUCTURE OF A C PROGRAM :

Every programming languages have their own format of coding. The complete structure of C program as shown below.

preprocessor statements

global declarations;

main( )

{

declaration;

statements;

/* comments */

}

user defined function

1 Preprocessor Statements :

These statements begin with # symbol and also called preprocessor directives. These statements direct the C preprocessor to include header files and also symbolic constants into a C program. Some of the preprocessor statements are :

# include <stdio.h>

# include <conion.h> etc.,

2 Global Declaration :

Variables or functions whose existence is known in the main( ) function and other user defined functions, are called the global variables and their declarations are called the global declarations. This declaration should be made before main( ) function.

3 main( ) function :

This is the main function of every C program. Execution of C program starts from main(). No C program is executed without main() function. It should be written in lowercase letters and should not be terminated by a semicolon. It calls other library functions and user defined functions.

4 Braces :

Every C program uses a p[air of curly braces i.e., { and }. The left brace indicates the beginning of main( ) function. On the other hand, the right indicates the end of the main( ) function. The braces can also be used to indicate the beginning and end of user-defined functions and compound statements.

5 Declaration :

It is a part of the C program where all the variables, arrays, functions etc., used in the C program are declared and may be initialized with their basic data types.

6 Statements :

These are instructions to the computer to perform specific operations. They may be input- output statements, arithmetic statements, control statements and other statements.

7 Comments :

Comments are explanatory note on some instructions. The statements to be commented on must be enclosed with /* and */. Comment statements are not compiled and executed.

8 User-defined functions :

These are subprograms. Generally, a subprogram is a function. The user defined functions contain a set of statements to perform a specific task. These are written by the user, hence the name user-defined functions. They may be written before or after the main( ) function.

A Simple C Program is given below

#include<stdio.h>

main()

{

printf(“\nWelcome to C”);

\* a call to output function *\

}

The first line tells the compiler to include standard input/output header file to perform reading and printing of the data. The second line is the main( ), the main function of a C program. The body of C program contains the statement i.e.,

printf(“\nWelcome to C”);

When this statement is taken for execution, main( ) calls the output function printf( ). Then printf( ) prints Welcome to C on the computer screen.”\n” is a new line character. It is used to print the message to the new line. The statement i.e., \* a call to output function *\ is comment. Comment describes the above statement.

Program Compilation and Execution

Compiling a C program means translating it into machine language. ‘C’ compilers are used for this purpose. The process of generating outputs of the program on the screen is called Execution. Press Ctrl + F9 to compile the program. Press Alt + F5 to run the program.

Starting C Program Editor

1 Click Start menu & Select Run option

2 Type command & Press Enter key

3 Press Alt+Enter key to view DOS in Full Screen

4 Type cd\tc\bin & Press Enter Key

5 Type tc & Press Enter Key

CHARACTER SET

Every programming language has its own set of characters to form the lexical elements. The characters used in C are grouped into the following three categories.

 

1 Alphabet:     Upper Case     A-Z

          Lower Case     a-z

2 Digits  :  0 to 9

3 Special Characters    :

, comma                    + plus sign

. dot                           - minu sign

: colon                       * asterisk

; semicolon                / slash

opostrophe              % percentage

quotation mark       & ampersand

? question mark              ^ caret

! exclamation mark   ~ tilde

_ underscore              < less than

# hash                        > greater than

= equal sign               \ back slash

| pipeline character    ( left parenthesis

) right parenthesis     [ left bracket

] right bracket

{ left brace                } right brace

C TOKENS

The basic and the smallest units of a C program are called C Tokens. There are six types of tokens in C.

1 Keywords

2 Identifiers

3 Constants

4 String

5 Operators

6 Special Symbols

KEYWORDS

Every word in a C program is either a keyword or an identifier. All keywords (reserve words) are basically the sequence of characters that have one or more fixed meaning. All C keywords must be written in lowercase letters. Because, in C both uppercase and lowercase letters are significant.

Example for Keywords :

int

char

break

else

if

continue

do

float

goto

long

return

for

short

static

auto

union

struct

switch


IDENTIFIERS

Identifiers are names given to the program elements such as variables, arrays and functions.

Basically, identifiers are the sequences of alphabets and digits.

Rules for forming identifier name

·        The first character must be an alphabet (upper case or lowercase) or an underscore ( _ )

·        All succeeding characters must be either letters or digits

·        Uppercase and lower case identifiers are different in C

·        No special character or punctuation symbols are allowed except the underscore ( _ )

·        No two successive underscores are allowed

·        Keywords should not be used as identifiers.

CONSTANTS :

A Constant is an entity whose value does not change during program execution. The following are types of constants :

1 Integer Constant :

An integer constant is a whole number. It is a sequence of digits without a decimal point. It may prefixed with plus or minus sign.

Example : 246, 0, -3579, +25, -32028, 9999 etc.,

2 Floating Constant :

A floating constant is a number with a decimal point. It is defined as sequence of digits preceded and followed by the decimal point. They may have prefixed plus or minus sign.

Example : -246.01, +12.25, 0.0, 0.0005, 82.0, 9999.999, -0.00123 etc.,

3 Character Constant :

A character constant is a single character enclosed within pair of apostrophes.

Example : ‘a’, ‘?’, ‘#’, ‘ ‘(blank character) etc.,

4 String Constant :

A string constant is a sequence of characters enclosed within a pair of double quotes.

Example : “Hi”, “Welcome”, “2007”, “x+2”etc.,

VARIABLES

A variable is an entity used by a program to store values in the program. It is a symbolic name used for actual memory location. Therefore variable are also called as identifiers.

Example : sum, area, num, length, age, city etc.,

Rules for forming variable names

·        The first character of a variable name must be an alphabet or an underscore

·        All succeeding characters consists of letters and digits

·        Both uppercase and lowercase variables are significant in C

·        Keywords should be used as variables

·        Special characters are not allowed

·        There is not limit on the number of characters in a variable name

·        Always choose an appropriate variable name that makes proper sense to the user

DECLARATION OF VARIABLES

All the variables must be declared before they are used in the program. A variable declaring consists of a data type name followed by a list of one or more variables of that type, separated by commas.

Syntax :

Datatype Variable_name,…..,….;

Example :

int num;

char name[10]; float rate;

ASSIGNING VALUES TO VARIABLES

We know that the variables represent some memory location, where the data is stored. Each variable is associated with one or more values. The process of giving values to variables is called assignment of values. The assignment operator ‘=’ is used to assign a value to a variable.

Syntax :

variable_name = value;

Example :

int num=5; float pi=3.142; x = 10;

sum = a + b;

name = “Saraswati”

DATA TYPES

Data type indicate the type of data that a variable can hold. The data may be numeric or non- numeric in nature. There are four fundamental C data types

Types

Keyword

Size(in bytes)

Integers

int

2 bytes

Real(Floating point)

float

4 bytes

Double Precision

double

8 bytes

Character

char

1 byte

int :

This is keyword used to indicate an integer number. Any integer number is a sequence ofdigits without a decimal point. A 8 bit computer the maximum integer that can be input is either - 128 or +127. Similarly, a 16 bit computer handles the integers from -32,768 to +32,767.

Example :

-248, 14042, 27246, +1996,    0, 32760

float :

This is a keyword used to indicate a floating-point number. The floating-point numbers are

same as real numbers. They are called floating point. These numbers may be expressed in scientific notation.

Example :    -263.238, 2.63238E+02, 0.0263238E+04, 26323.802

char :

This is a keyword used to indicate the character type data.

The data may be a character

Constant or a string constant. A character constant can be defined as any single character enclosed within a pair of apostrophes.

Example :

‘a’, ‘p’, ‘$’, ‘2’, ‘?’, ‘ ‘(blank) etc.,

double :

This is a keyword used to indicate a double precision floating point numbers. The precision is associated with the accuracy of data. The float usually stores a maximum or 6 digits after the decimal point. But double stored 16 significant digits after the decimal point.

Example : 234.0000000000000000, -0.0000001023999001

BACKSLASH CONSTANTS

A backslash constant a combination of two character in which the first character is always  the backslash( \ ). And the second character can be any one of the characters a, b, f, n, r, t, v , ’, “, \, and 0.The backslash characters also called as escape sequences. These statements are used in output statements.

Backslash Constant

Meaning

\a

System Alarm (bell or beep)

\b

Backspace

\f

Form feed

\n

New line

\r

Carriage return

\t

Horizontal tab

\v

Vertical tab

\”

Double quote

\’

Apostrophe

\0

Null character

\\

Back slash character (\)

SYMBOLIC CONSTANTS

A symbolic constant is a name that substitutes a numeric constant, a character constant or a string constant. For example, assume that we are computing the area of a circle using the formula.

area = 3.142 * radius * radius

In this formula, the numeric constant 3.142 can be replaced by symbolic constant name PI. Thus, the formula takes a new form as

area = PI * radius * radius

Here, we substituted PI for a numeric constant. During compile-time, each occurrence of PI is replaced by its value defined. Symbolic constants are defined using preprocessor statement #define.

Example :

# define PI 3.142

# define  NAME “PRABHU”

# define FOUND 1

Symbolic constants must be defined at the beginning of a program. That is, before the main( ) function of a C Program.

 

No comments: