0% found this document useful (0 votes)
84 views26 pages

Problem Solving With Computer: Introduction To Software System Development Lifecycle (SDLC)

The document discusses the system development life cycle (SDLC) which defines a series of stages for software development including problem definition, analysis, design, coding, testing, documentation, and maintenance. It describes each stage in detail. Problem definition requires precisely defining the problem in user terms. Analysis determines objectives, inputs/outputs, and processing requirements. Design characterizes how data and functions will be structured. Coding writes the program. Testing debugs and fixes errors. Documentation writes user guides. Maintenance adjusts for bugs and changes over time.

Uploaded by

Jeevan Pandey
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
84 views26 pages

Problem Solving With Computer: Introduction To Software System Development Lifecycle (SDLC)

The document discusses the system development life cycle (SDLC) which defines a series of stages for software development including problem definition, analysis, design, coding, testing, documentation, and maintenance. It describes each stage in detail. Problem definition requires precisely defining the problem in user terms. Analysis determines objectives, inputs/outputs, and processing requirements. Design characterizes how data and functions will be structured. Coding writes the program. Testing debugs and fixes errors. Documentation writes user guides. Maintenance adjusts for bugs and changes over time.

Uploaded by

Jeevan Pandey
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

1.

Problem Solving with Computer


Introduction to Software System Development Lifecycle (SDLC)
Procedure Oriented software development is usually characterized by a series of stages depicting the various
tasks involved in the development process. SDLC defines a sequence of tasks that must be carried out to
build a new system. System Development Life Cycle (SDLC) is an organized way to build an information
system.

1. Problem definition: activity requires a precise definition of the problem in user terms.
2. Problem analysis: determine program objectives, desired output, required input, and processing
requirements.
3. Program design: characterize design techniques to convert problem definition into solution
definition.
4. Program code: select programming language and write the program code.
5. Program test: running the program on a computer and fixing the parts that do not work; unit test,
system test, integration test, alpha test, beta test.
6. Program documentation: write procedures for users, operators, and programmers.
7. Program maintenance: adjust for errors, inefficient or ineffective operations, nonstandard code, and
changes over time.

1.1Problem Definition:
This activity requires a precise definition of the problem in user terms. A clear statement of the problem is very
essential to the success of the software. It helps the program developer to understand the problem better.

1.2Problem Analysis/System Analysis


System analysis enables the system engineer (analyst) to specify software function and performance,
indicate software’s interface with other system elements, and establish constraints that software must meet.
System analysis allows the analyst to refine the software allocation and build models of the data, functional,
and behavioral domains that will be treated by software. System analysis provides the software designer
with models that can be translated into data, architectural, interface and procedural design.

1.3 Program Design


During design, the team attempts to define how data are to be structured, how function is to be implemented,
how procedural details are to be implemented, how interface are to be characterized and how the design will
be transformed into a programming language.

1.3.1-Top-down program design


In top-down design, the team starts with the large picture and moves to the detail. They look the major
functions that the system must provide and break these down into smaller activities. Each of these activities
will then be programmed in the next phase of the SDLC. Top-down design has some rigid rules.
Top-down program design is a structured design technique, in which the programmer, having
determined the outputs to be produced and the inputs required, identifies the major processing steps that the
program must perform. These major processing steps are called program modules.

1.3.2-Algorithms
Algorithms consist of statements in describing structured program steps and logic. It allows the program
designer to focus on the logical steps of the programs and not on details of programming or flowcharting.

1
1.3.3-Flowcharts
One of the most widely used tool for designing structured programs is the flowchart, which graphically
represents the logic needed to solve a programming problem. A program flowchart represents the detailed
sequence of steps, needed to solve the problem. Program flowcharts are frequently used to visualize the
logic and steps in processing. Following symbols are widely used to construct flowcharts.

Process Alternative Data


Decision
Process

Predefine Document
Internal Multiple
Process

Terminator Preparation Manual


Mag

Manual Direct
Operation Magnetic Display
Access
Disk Storage

Direction of flow symbols Connector symbol

Data symbol is used to represent any input or output operation. It may represent the point in a program
where the data (input) is required or where the information (output) is to be displayed.
Process symbol represents some type of data manipulation or arithmetic operation.
Decision symbol represents a logical comparison operation. Based on the comparison, one of the two path
will be taken.
Connector symbol is used to connect another portion of the flow chart where the program flow continues.
Predefined process symbol is often used to represent a process that is used several times in the same
program. This process is defined only once and reference by
this block thereafter. START
Terminator symbol represents the start or end of a program.
Direction of flow symbols READ N
START indicates the next step in the
program
FACTN = 1
INPUT L
I=1
INPUT B

FACTN = FACTN*I
A = L*B

NO
PRINT L, B, A IS I = N I = I+1
YES
END PRINT N, FACTN

END
2
An example of a flow chart to calculate area of a rectangle
An example of a flow chart to calculate the Factorial of a

number N
1.4Coding
In this step, programmers use the logic developed in the design phase to actually write the program. Most of
the time required to complete a project is spent here. Writing a computer program is a cyclic process of
writing code, compiling, correcting, and rewriting. The more detailed the design, the more easier is the
coding and better its reliability.

1.5Compilation and Execution


1.5.1Compiler
A computer can directly recognize only machine language programs. Hence, a high-level language program
must be converted (translated) into its equivalent machine language code before it can be executed on the
computer. This translation is done with the help of a translator program, which is known as compiler. Hence,
a compiler is a translator program, which translates a high-level language program into its equivalent
machine language program.

High-level language Input Compiler Output Machine


language
source code code

The compiler translates each high-level language instruction into a set of machine language instructions at
once. Every high level language has its own compiler. Thus, compiler can translate only those source codes,
for which it is designed. For example, a C compiler is only capable of translating source code written in C
language. Therefore, each computer requires a separate compiler for each high-level language.

1.5.2The compiling process


The objective of the compiler is to convert source program written in high-level language into object code.
The program written by programmer is called source code, which must go through several steps before it
becomes an executable program.

3
Source File Source File Source File

Compiler

Object Object Object

Executable
Linker
Routine program

Compiling process

The first step is to pass the source code through a compiler, which translates the high-level language
instructions into object code. If there is any syntax error in the program, it will be checked at the time of
compilation. Compiler only produces object code when the source code is free from syntax error. Then
object code is further passed through linker program to produce executable code.
1.6 Debugging, Testing and Documentation
1.6.1Testing
Testing a program means running the program on a computer and fixing the parts that do not work. There
are two types of programming errors- syntax errors and logic errors.
A syntax error occurs due to violation of the rules of the programming language (ie if a programmer does
not write syntax correctly). A logic error occurs when there is an incorrect output or result. There are
number of ways by which syntax and logic errors weeded out.

Structured walkthrough: -A structured walkthrough is a formal review process designed not only to verify
computer code but also evaluate the documentation and the design of the program. In this process, a coded
program is submitted to a review team of programmers including the one who produced the code. After
review, the program’s overall completeness, accuracy, and quality of the design are discussed. Typically the
program is put through desk checking, in which the entire program is reviewed, that is by running sample
data manually through the program.

Checking for syntax errors: - After the structured walkthrough, the programmer attempts to compile/run
the program. If there are any syntax errors that have slipped the walkthrough phase, they will be identified
by programs –compiler or interpreter.

Checking for logic errors: - After all syntax errors have been corrected and the program code has been
successfully translated into machine code, the program can be tested for logic errors using a set of test data,
designed to thoroughly test all aspects of the program. Both the tested output and the expected output are
compared to find out the existence of any logic errors.
It is important to catch these errors, both syntax and logic, as early in the programming process as possible.

Unit Testing refers to a method of testing that verifies the individual units of source code are working
properly. Since this testing deals with the software code, and requires a detailed knowledge of it, it is
implemented by the programmer itself rather than the software tester.

4
Functional Testing involves testing the system against the functional requirements for the product. For
system testing, no knowledge of internal logic or code structure is required.

Integration Testing: Different small software modules are combined together to perform the integration
testing. Here, the testing process is taken as a whole system testing.

1.6.2Debugging
Debugging is a process of eliminating logical errors (program bugs) from a program. Debugger is a kind of
translator that is used in high level programming language for debugging process. Debugger is a program
that executes a command of programming statement at a time, so we can thoroughly test all aspects of the
program. Every high level language has its own debugger.

1.6.3Documentation
Program documentation consists of written descriptions and procedures about a program and how to use it.
This document should contain statements on the program’s objectives, output specifications, input
requirements, processing requirements and feasibility. In other words, the document should describe
everything you have done so far. Documentation is carried on throughout all the programming steps.

Main uses of documentation are:


♦ For the programmer’s own present or future use.
♦ For the present or future use of other programmers, including the programmer’s supervisor, eg, for
maintenance, modification, debugging, etc.
♦ For the users of the program, who may themselves vary in expertise?

The following items may be expected as part of the complete process of documentation:
♦ A statement of the problem.
♦ Documents specifying the formats of inputs and outputs.
♦ Details about data structure and file structure.
♦ Description about elimination of errors (error-free methods) of input and output for the program’s users.
♦ Detailed instructions to the user
1. Limitations of the program.
2. Requirements in order to run the programs
3. Details of how to run the program.
4. Instructions, with examples, on how to use the program.

1.7Introduction and History of C language


C is a general-purpose structured programming language, which is often called a middle level programming
language. The 'C' programming language was designed and developed by Brian Kernighan, and Dennis
Ritchie
In 1972 at the Bell Research Labs. In 1978 the publication of the C Programming Language by Kernighan &
Ritchie caused a revolution in the computing world. C was initially used for system development work, in
particular the programs that make-up the operating system. C produces code that runs nearly as fast as the
code written in assembly language. In recent years C has been used as a general-purpose language because
of its popularity with programmers. The resulting definition, the ANSI standard, or “ANSI C”, was
completed late 1988. C seems to be largely successful language due to following considerations
¾ Portability of the computer
¾ Standard library concept
5
¾ Powerful and varied capability of operators
¾ Excellent syntax
¾ Ready access to the hardware when needed

Programs written in C are efficient and fast. This is due to variety of data types and powerful operators. C language is
well suited for structured programming, thus requiring the user to think of a problem in terms of function modules or
blocks. A proper collection of these modules would make a complete program. This modular structure makes program
debugging, testing and maintenance easier.

1.8-Structure of a C program
A program written in ‘C’ language may contain one or more sections given below.

Documentation Section

Link Section

Definition Section

Global Declaration Section

main() Function Section


{
Declaration Part

Executable Part
}
Subprogram or user-defined function section
Function 1
Function 2
.
.
Function n
The documentation section consists of a set of comment lines giving the name of the program, the author
and other details which the programmer would like to use later.
The link section provides instructions to the compiler to link functions from the system library. The
definition section defines all symbolic constants.
There are some variable that are used in more than one function. Such variable are called global variables
and are declared in the global declaration section that is outside of all the functions.
Every C program must have one main() function. The program will always begin by executing the main
function, which may access other functions. Any other function definitions must be defined separately,
either ahead of or after main. This section contains two parts, declaration part and executable part. The
declaration part declares all the variables used in the executable part. There is at least one statement in the
executable part. These two parts must appear between the opening and the closing brace. The closing brace
of the main function section is the logical end of the program. All statements in the declaration and
executable parts end with a semicolon.
The subprogram section contains all the user-defined functions that are called in the main function. Every
C program consists of one or more modules called functions. A function is a subroutine that may include one
or more statements designed to perform a specific task. To write a C program, we first create functions and
6
then put them together. User-Defined functions are generally placed immediately after the main function
although they may appear in any order.

A simple ‘C’ program that display a message “Hello World” in your screen.
#include <stdio.h>
void main()
{
printf("***********************\n");
printf("\n* Hello World *\n");
printf("***********************\n");
}

A simple C program that calculate the area of a circle.


/*Program to calculate the area of circle*/ /*DOCUMENTATION
SECTION*/
#include <stdio.h> /*LINK SECTION*/

void main() /*FUNCTION HEADING*/


{
float radius, area; /*VARIABLE DECLERATION*/
printf("***********************\n");
printf("Radius = ?\n");
scanf("%f",&radius); /* INPUT STATEMENT */
area = 3.14159*radius*radius; /* ASSIGNMENT STATEMENT
*/
printf("Area = %f",area); /* OUTPUT STATEMENT */
printf("***********************\n");
}

Review Questions
1. Discuss in brief about different steps involved in program development phase.
2. Write short notes on algorithm and flowchart. Explain their uses.
3. Explain briefly about the source code compilation process of structured programming language.
4. Give a brief introduction on ‘C’ language.
5. Write short notes on following
a) Testing
b) Debugging
c) Structure of a program written ‘C’ language

2. Elements of C
In C program the smallest individual units are known as C tokens (basic elements of C).

7
C TOKENS

Keyword Constant Strings Operators

Identifiers Special Symbols

2.1The C character set


C uses the uppercase letters A to Z, the lowercase letters a to z, the digits 0 to 9, and certain special
characters as building blocks to form basic program elements (e.g., constants, , variables, operators,
expressions, etc.). Some special characters are listed below.

+ - * / = % & # ! ? ^ “ ‘ ~
\ | < > ( ) [ ] { } : ;
. , _ @ $ (blank space)

2.2Identifiers
Identifiers are names that are given to various program elements, such as variables, functions and arrays.
Identifier consist of letters and digits, in any order, except that the first character must be a letter. Both
upper- and lowercase letters are permitted. An uppercase letter is not equivalent to the corresponding
lowercase letter. The underscore character (_) can be included, and is considered to be a letter.

Some valid identifiers


X
Y1
Name
_row
volume

Some invalid identifiers


5X the first character must be a letter.
‘Y’ illegal characters (‘). First-
Name illegal characters (-).
Circ Area illegal characters (blank space).
2.3Keywords
Keywords are reserved words, they have standard, predefined meanings in C. These keywords can be used
only for their intended purpose; they cannot be used as programmer-defined identifiers. (the keywords are
all lowercase). Since uppercase and lowercase characters are not equivalent, it is possible to utilize an
uppercase keyword as an identifier.

Some standers keywords in C are


auto extern sizeof break floaten static case for
struct char goto switch const if typedef
continue int union default long unsigned do
rgister void double return volatile else short
while enum signed
8
Some compilers may also include some or all of the following keywords.
ada far near asm fortran pascal entry huge

2.4Data types
C language is rich in its data types. Storage representations and machine instructions to handle constants
differ from machine to machine. The variety of data types allow the programmer to select the type
appropriate to the needs of the application as well as the machine. C general (or fundamental) data types are
listed below.

Data types Description Typical Memory Requirements


int integer quantity 2 bytes or one word (varies from one
compiler to another)
char single character 1 byte
float floating-point number 1 word (4 bytes)
double double-precision floating-point number 2 words (8 bytes)
long double largest in magnitude 10 bytes long

The char type is used to represent individual characters and it requires one byte of memory. With most
compilers, a char data type will permit a range of values extending from 0 to 255. Some compilers represent
the char data (with typical values ranging from –128 to +127).

short int smaller_number data range(–32,768 to +32,767)

long int big_number data range (-4294967296 through to +4294967295). Long int will generally have
double the requirements (e.g., 4 bytes).

float floating point numbers with data range (MAXFLOAT 3.40282346638528860e+38 and MINFLOAT
1.40129846432481707e-45)

long float (double) floating point numbers with data range (MAXDOUBLE 1.79769313486231470e+308
and MINDOUBLE 4.94065645841246544e-324)

Signed and unsigned prefixes: - For both the character and integer types the declaration can be preceded by
the word "unsigned". This shifts the range so that0is the minimum, and the maximum is twice that of the
signed data type. It's useful if you know that it is impossible for the number to go negative.

Type Length Range


unsigned char 8 bits 0 to 255
char 8 bits -128 to 127
enum 16 bits -32,768 to 32,767
unsigned int 16 bits 0 to 65,535
short int 16 bits -32,768 to 32,767
int 16 bits -32,768 to 32,767
unsigned long 32 bits 0 to 4,294,967,295
long 32 bits -2,147,483,648 to 2,147,483,647
float 32 bits 3.4 * (10**-38) to 3.4 * (10**+38)

9
double 64 bits 1.7 * (10**-308) to 1.7 * (10**+308)
long double 80 bits 3.4 * (10**-4932) to 1.1 * (10**+4932)
2.5Escape sequence
Certain nonprinting characters, as well as the backslash (\) and apostrophe ( ‘ ), can be expressed in terms of
escape sequences. An escape sequence always begins with a backward slash and is followed by one or more
special characters.
The commonly used escape sequences are listed below.

Character Escape Sequence ASCII value


bell (alert) \a 0
0
7
backspace \b 0
0
8
horizontal tab \t 0
0
9
vertical tab \v 0
1
1
newline (line feed) \n 0
1
0
form feed \f 0
1
2
carriage return \r 0
1
3
quotation mark (“) \” 0
3
4
apostrophe (‘) \’ 0
3
9
question mark (?) \? 0
6
3
backslash (\) \\ 0
9
2
null \0 0
0
0
2.6Constants
Constants in C refer to fixed values that do not change during the execution of a program. C supports several
types of constants as illustrated in fig.

10
CONSTANTS

Numeric Character constants

Integer Floating Single String


constants point character constants
Integer and floating-point constants are numeric type constants.
Integer constants: - An integer constant is an integer-valued number. Integer constants can be written in
three different number systems.

Decimal (base 10). A decimal integer constant can consist of any combination of digits taken from the set 0
through 9.

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

Hexadecimal (base 16). A hexadecimal integer constant must begin with either ox or OX. It can then be
followed by any combination of digits taken from the sets 0 through 9 and the letters a through f (or A
through F) represents the (decimal) quantities 10 through 15, respectively.

Unsigned and long integer constants: - An unsigned integer constants can be approximately twice as large
as an ordinary int (though of course negative values are not permitted). An unsigned integer constant can be
identified by appending the letter U (either upper- or lowercase) to the end of the constant.
Long integer constants may exceed the magnitude of ordinary integer constants, but require more memory
within the computer. To create a long integer constant, append the letter L (either upper- or lowercase) to the
end of the constant.

Floating-Point Constants (Real Constants): - A floating-point constant is a base-10 number that contains
either a decimal point or an exponent (or both). Floating-point constants have a much greater range than
integer constants. Typically, the magnitude of a floating-point constant might range from a minimum value
of approximately 3.4E-38 to a maximum of 3.4E+38. Some versions of language permit floating-point
constants that cover a wider range, such as 1.7E-308 to 1.7E+308. Floating point constants are normally
represented as double-precision quantities in C. The general form is:
mantissa e exponent

The mantissa is either a real number expressed in decimal notation or an integer. The exponent is an
integer number with an optional plus or minus sign. The letter e separating the mantissa and the exponent
can be written in either in uppercase or lowercase. Since the exponent causes the decimal point to “float”,
this notation is said to represent a real number in floating point form.

Example
The quantity 3*105 can be represented in C by any of the following floating-point constants.
300000. 3e5 3e+5 3E5 3.0e+5 .3e6 0.3E6 30E4 300e3
-5
The quantity 5.001*10 can be represented in C by any of the following floating-point constants.
5.001E-5 .5001E-4 50.01E-6

11
Character Constants: - A character constant is a single character, enclosed in apostrophes.
Example of character constants are shown below.
‘A’ ‘X’ ‘9’
Character constants have integer values that are determined by the computer’s particular character set.
Most computers, and virtually all personal computers, make use of the ASCII (i.e., American Standard
Code for Information Interchange) character set, in which each individual character is numerically encoded
with its own unique 7-bit combination (hence a total of 27 = 128 different characters). For example
Constant Value
A---Z 65---
90
a---z 97---
122
0---9 48---
57

String Constants: - A string constant consists of any number of consecutive characters, enclosed in
(double) quotation marks.
Some examples of string constants are as shown below
“Name” “School” “245115” “$111.90” “Line 1\nLine 2\nLine 3”

Symbolic constants: - A symbolic constant is a name that substitutes for a sequence of characters. The
characters may represent a numeric constant, a character constant or a string constant. Thus a symbolic
constant allows a name to appear in place of a numeric constant, a character constant or a string. When a
program is compiled, each occurrence of a symbolic constant is replaced by its corresponding character
sequence.

Symbolic constants are usually defined at the beginning of a program.


Syntax #define name text
where name- represents a symbolic name, typically written in uppercase letters. text-
represents the sequence of characters that is associated with the symbolic name.

Example-2.1. A program written in C language that uses symbolic constants.


#include<stdio.h>
#define PI 3.141593
#define MESSAGE "I am writing my first C program"

void main()
{
float radius,area;
printf("Input the value of radius\n");
scanf("%f",&radius);
area = PI*radius*radius;
printf("%s\n",MESSAGE);
printf("\a\n");
printf("Radius = %f Area = %f\n\n",radius,area);
printf("Type any number and press Enter\n");
scanf("%f",&radius);
}

12
2.7Variables
A variable is an identifier that is used to represent a single data item; i.e., a numerical quantity or a character
constant. Initially, data item must be assigned to the variable at some point in the program. The data item
can then be accessed later in the program simply by referring to the variable name. A given variable can be
assigned different data items at various places within the program. Thus, the information represented by the
variable can change during the execution of the program.
Local variables: - Local variables are declared within the body of a function, and can only be used within
that function.
Global Variables: - Alternatively, a variable can be declared globally so it is available to all functions.
Modern programming practice recommends against the excessive use of global variables. A global variable
declaration looks normal, but is located outside any of the program's functions. This is usually done at the
beginning of the program file, but after preprocessor directives. The variable is not declared again in the
body of the functions which access it.

External Variables: - Where a global variable is declared in one file, but used by functions from another, then
the variable is called an external variable in these functions, and must be declared as such. The declaration
must be preceded by the word extern. The declaration is required so the compiler can find the type of the
variable without having to search through several source files for the declaration.
Global and external variables can be of any legal type. They can be initialized, but the initialization takes
place when the program starts up, before entry to the main function.

Static Variables: - Another class of local variable is the static type. A static can only be accessed from the
function in which it was declared, like a local variable. The static variable is not destroyed on exit from the
function; instead its value is preserved, and becomes available again when the function is next called. Static
variables are declared as local variables, but the declaration is preceded by the word static. Following
example represents the declaration of static variable.

Variable declarations: - A declaration associates a group of variables with a specific data type. A
declaration consists of a data type, followed by one or more variable names, ending with a semicolon. Each
array variable must be followed by a pair of square brackets, containing a positive integer which specifies
the size (number of elements) of the array.

Review Questions
1. Describe the basic data types in C with suitable example.
2. What is an operator? Describe several types of operators that are included C.
3. What is scope and lifetime of a variable? Describe global local and static variables in terms of their
scope and lifetime.
4. Write short notes on following
a) Constants
b) Variable
c) Keywords
d) Identifier

3. Input and Output


Conversion specification, I/O operation, Formatted I/O

‘C’ programming language has a number of input/output functions. Some of these functions
are getchar putchar -> facilitate the input and output of character. scanf printf -> permit
the transfer of single characters, numerical values and strings.
13
gets puts -> facilitate the input and output of strings.

These functions permit the transfer of information between the computer and the standard input/output
devices. As a rule, the header file required by the standard input/output library functions is called “stdio.h”
(standard input/out function).

3.1Character input/output
getchar(): ‐ Single Character Input Function
The getchar() function is a part of the ‘C’ I/O library. It returns a single character from a standard input
device (typically a keyboard). General syntax of using getchar() function is written as: Character
variable = getchar();
Where character variable refers to some previously declared character variable

puttchar(): - Single Character Output Function


The putchar() function, like getchar(), is a part of the C I/O library. It transmits a single character from a
standard output device (typically a monitor). General syntax of using putchar() function is written as:
putchar (Character variable);
Where character variable refers to some previously declared character variable

Example-1. A program written in C language with implementation of character


input/output function.

#include<stdio.h>
#include<ctype.h>

void main()
{
char upper, lower;
lower = getchar(); upper
=toupper(lower);
putchar(upper);
putchar(‘A’); putchar(65);
getch();
}

3.2Formatted Data Input/output


Formatted Data Input Function scanf(): - Data can be entered into the computer by means of the ‘C’
library function scanf(). This function can be used to enter any combination of numerical values, single
characters and strings.
In general terms, the scanf function is written as
scanf(control1 string, arg1, arg2,..., argn) Where control
string refers to a string containing certain required
formatting information, and arg1, arg2, ..., argn are
arguments that represent the individual input data items.
The control string consists of individual groups of characters, with one character group for each input data
item. Each character group must begin with a percent sign (%). In its simplest form, a single character group
will consists of the percent sign, followed by a conversion character which indicates the type of the
corresponding data item. Within the control string, multiple character groups can be contiguous, or they can
be separated by white-space characters (i.e., blank spaces, tab or new line characters).
14
Commonly Used Conversion Characters for Data Input
Conversion Character Meaning
c Data item is a single character
d Data item is a decimal integer
e Data item is a floating-point value
f Data item is a floating-point value
g Data item is a floating-point value
h Data item is a short integer
i Data item is a decimal, hexadecimal or octal integer
o Data item is a octal integer
s Data item is a string followed by a white-space character (the null character \0
will automatically be added at the end)
u Data item is an unsigned decimal integer
x Data item is a hexadecimal integer
[...] Data item is a string which may include white-space characters
Each variable name must be preceded by an ampersand (&). (The arguments are actually pointers that
indicate where the data items are stored in the computer’s memory.) However, one-dimensional array of
characters should not begin with an ampersand.

Formatted Data Output Function –printf(): - Output data can be written from the computer onto a
standard output device means of the C library function printf(). This function can be used to output any
combination of numerical values, single characters and strings. It is similar to the input function scanf(),
except that its purpose is to display data rather than to enter it to the computer. In general terms, the printf()
function is written as printf(control1 string, arg1, arg2,..., argn)

Where control string refers to a string containing certain required formatting information, and arg1, arg2, ...,
argn are arguments that represent the individual input data items.
The control string consists of individual groups of characters, with one character group for each output data
item. Each character group must begin with a percent sign (%). In its simplest form, a single character group
will consists of the percent sign, followed by a conversion character indicating the type of the corresponding
data item. Within the control string, multiple character groups can be contiguous, or they can be separated
by white-space characters (i.e., blank spaces, tab or new-line characters).

Commonly Used Conversion Characters for Data Output

Conversion Character Meaning


c Data item is displayed as a single character
d Data item is displayed as a decimal integer
e Data item is displayed as a floating-point value with an exponent
f Data item is displayed as a floating-point value with an exponent
g Data item is displayed as a floating-point value using either e-type or
ftype conversion, depending on value. Trailing zeros and trailing
decimal point will not be displayed.
i Data item is displayed as a signed decimal.
O Data item is displayed as an octal integer, without leading zero
S Data item is displayed as a string.
U Data item is displayed as an unsigned decimal integer

15
X Data item is displayed as a hexadecimal integer, without the leading ox

3.3Line input output function


gets and puts: - Each of these functions accepts a single argument. The argument must be a data item that
represents a string. In case of gets, the string will be entered from the keyboard and the string will end when
the user presses the Enter key.

4. Operators and Expressions


An operator is a function which is applied to values to give a result. An operation is a defined action upon
data. For example 3+5 is an arithmetic operation on two integers. The result of operation 3+5 is 8. The
operator used to signify this operation has the symbol “+”. The operands are the data items operated upon,
in this example the operands are 3 and 5.
Some Operators require two operands while others act upon only one operand (called unary operators).
Some operators of C are listed below

 Arithmetic Operators  Unary Operators  Relational and Logical Operators  Assignment


Operators  Conditional Operator

4.1- Arithmetic Operators


There are five arithmetic operators in C. They are:
Operator Purpose
+ Addition
-* Subtraction
/ Multiplication
% Division
Modulus (remainder after integer division)
s
C includes a class of operators that act upon a single operand to produce a new value. Such operators
are known as Unary Operators. Unary operators usually precede their single operands, through some
operators are written after their operands.
The most common unary operation is unary minus, where a numerical constant, variable or expression is
preceded by a minus sign.
Operators Meaning
* Contents of the storage field to which a pointer is
pointing
& Address of a variable
-! Negative Value(minus sign)
~ Negation(0)
++ Bit wise complement
-- Increment operator
type Decrement operator
sizeof Forced typed of conversion
Size of the subsequent data type or type in byte
16
The increment operator causes its operand to be increased by 1, where as the decrement operator causes its
operand to be decreased by 1.

4.3- Relational Operators


There are four relational operators in c++. They are:
Operator Meaning
< Less than
<= Less than or equal to
> Grater than
>= Greater than equal to
4.4- Equality Operators
Closely related with the relational operators, are following two equality Operators. The equality operators
fall into a separate precedence group, beneath the relational operators. These operators also have left-to-right
associatively.
Operators Meaning
== ! Equal to
= Not equal to
4.5- Logical Operators
C ++ contains two logical operators. The logical operators act upon operands that are themselves logical
expressions. The net effect is to combine the individual logical expressions into more complex conditions
that are either true or false.
Operators Meaning
&& Logical AND Logical
|| OR

And operator
Z= X && Y
x y z
0 0 0
0 1 0
1 0 0
1 1 1

Or operator
Z= X !! Y
x y z
0 0 0
0 1 1
1 0 1
1 1 1

17
4.6- Assignment Operators
There are Several Assignment operators in C which is used to assign the value of an expression to an
identifier. The most commonly used assignment operator is =. Assignment expressions that make use of this
operator are written in the form

Identifier = expression
Where identifier generally represents a variable and expression represents a constant.
Operator Meaning
= Assign right hand side(RHS) value to the left hand side(LHS)
+= Value of LHS variable will be added to the value of RHS and assign it back to the
variable in LHS
-= Value of RHS variable will be subtracted from the value of LHS and assign it back
to the variable in LHS.
*= Value of LHS variable will be multiplied by the value of RHS and assign it back to
the variable in LHS.
/= Value of LHS variable will be divided by the value of RHS and assign it back to the
variable in LHS.
%= The Remainder will be stored back to the LHS after integer division is carried out
between the LHS variable and the RHS variable
Assignment operators have a lower precedence than any of the other operators that been discussed so far.

Expression Equivalent
Expression
i += 5 i=i+5
f -= g f=f–g
j *= (i - 3) j = j * (i - 3)
f /= 3 f=f/3
i %= (j - 2) i = i % (j - 2)

4.7- Conditional Operator


Simple conditional operations can be carried out with the conditional operator (?:). An expression
that makes use of the conditional operator is called a conditional expression. Such an expression can be
placed in terms of more traditional if-else statement. A conditional expression is written in the form
Expression 1? expression 2: expression 3

In this case, Expression 1 is evaluated first. If expression 1 is true, then expression 2 is evaluated and
becomes the value of the conditional expression. Otherwise expression 3 is evaluated and becomes the value
of the conditional expression.

Example: Here is an assignment statement that contains a conditional expression on the right-hand side.
flag = (i < 0)? 1: 0
If the value of i is negative, then 1 will be assigned to flag. If it is not negative, however, 0 will be assigned
as flag
min = (x1 < x2) ? x1 : x2
This statement causes the value of the smaller of x1 and x2 to be assigned to min. 4.8-
Precedence rule for all of the operators
Operator category Operators Associativity
18
Unary operators - ++ -- !sizeof (type) R→L
Arithmetic multiply, divide and remainder * / % L→R
Arithmetic add subtract + - L→R
Relational operators < <= > >= L→R
Equality operators == != L→R
Logical and && L→R
Logical or || L→R
Conditional operator ?: R→L
Assignment operators = += -= *= /= %= R→L

4.9-Expressions
An expression consists of one or more data items interconnected by one or more operators. Expressions can
also represent logical conditions that are either true or false.
Examp
les: a
+b x
=y a
<= b
x == y
++i

4.10-Statements
A statement causes the computer to carry out some action. There are different types of statements in C. They
are expression statements, compound statements and control statements. An expression statement consists
of an expression followed by a semicolon. The execution of an expression statement causes the expression to
be evaluated. Examples:
y = a + b;
++i;
A compound statement consists of several individual statements enclosed within a pair of braces ({ }). The
individual statements may themselves be expression statements, compound statements or control statements.

Review Questions
1. Explain operator precedence and associativity with suitable examples.
2. Explain in brief about the different types of operators available in C language.
3. What logical operators are available in C? Explain their precedence and associativity with examples.
4. Write short notes on following
a) Expressions and statements
b) Conditional operator
c) Unary Operators
5-Control Statements
The order in which program instructions are performed by the computer must be carefully controlled, and
programming languages like C contain features that allow the order of instruction execution to be controlled.

19
5.1-Control structures
Program control structures are used to regulate the order in which program statements are executed. Types of
control structures-
¾ Sequences
¾ Selections
¾ Repetitions

Sequences: In the absence of selections or repetitions program statements are executed in the sequence in
which they appear in the program:
Instruction1
Instruction2
Instruction3

5.2-Selection
Selections form part of the decision-making facilities within programming languages. They allow alternative
actions to be taken according to the conditions that exist at particular stages in program execution.

2Selections
2.1 If statement
2.2 If-else statement
2.3 if else if statement
2.4 Switch-case statement

If Statement
It is used to express conditional expressions. If the given condition is true, then it executes the statements.

Syntax
if
If(expression)
{
statement-1; statement- false
2; expression
}
true
Statement1

Statement2

endif
If -else statement
The if –else statement is used to carry out a logical test and then take one of two possible actions depending
on the outcome of the condition. If the given expression is true, then the statements of if part will be
executed, otherwise the statement of the else part will be executed.

Syntax
If(expression) if
{
false true
Instruction1;
} expression

20
Instruction2 Instruction1
endif

else {
Instruction2;
}

If -else -if statement: It permits us to make a multiple decision making facility.

Syntax if
If(Expression_1)
{
true
Instruction_1;
Expression_1 Instruction1
}
else if(Expression_2) false
{ true
Instruction_2; Expression_2 Instruction2
}
else if(Expression_n) false true
{
Instruction_n; Expression_n Instruction_n
}
false
else
{ Instruction_else
Instruction_else;
}
endif

5.3-The Switch statement


The switch statement causes a particular group of statements to be chosen from several available groups. The
selection is based upon the current value of an expression which is included within the switch statement. The
general form of the switch statement is
switch (expression) statement

Where the expression may be an integer or type char.


For each alternative, the first statement within the group must be preceded by one or more case labels. The
labels identify the different groups of statements (i.e., the different alternatives) and distinguished them from
one another. The case labels therefore must be unique within a given switch statement.
One of the labeled groups of statements within the switch statement may be labeled default. This group will
be selected if none of the case labels matches the value of the expression. The default group may appear
anywhere within the switch statement –it need not necessary be placed at the end.

21
swhich

Expression
case ‘X’: case ‘Y’: case ‘Z’: default:

InstructionX InstructionY InstructionZ Default_Instruction

End switch

Syntax
switch(expression)
{
case ‘X’:

InstructionX;
break; case
‘Y’:

InstructionY;
break; case
‘Z’:
InstructionZ;
break; default:
Default_Instruction;

}
Example-4
#include<stdio.h>
#include<ctype.h>
#include<conoi.h>

5.4-Loop Statements
The repeated performance of the same statements is often called loping. There are three common types of
loop constructs.
Loop Statements
3.1 While Loop
3.2 For loop
3.3 do- While Loop
While loop is indefinite loop (ie. it does not define the number of repetitions that will occur when the loop
is executed). The while statement is used to carry out looping operations, in which a group of statements
is executed repeatedly, until some condition has been satisfied. The general form of the while statement is,
while (expression) statement

22 while

Instructions

true
false

The statement will be executed repeatedly, as long as the expression is true. The statement can be either
endwhile
simple or compound.

The first time program sees the condition of While


loop (checks weather the value of the condition is True
or False). If it’s False, it will ignore all the instructions
inside the while loop. If it’s True, then it will follow
all the instructions inside the while loop. If the
condition of a while loop is always True, the while
loop repeats itself an endless number of times until
you turn off the computer. When a loop repeats itself
endlessly, it is called an endless loop or infinite loop.

Do –while statement
With while loop, the test for continuation of the loop is carried out at the beginning of each pass. With
do- while statement, the test for continuation of the loop is carried out at the end of each pass. The
general form of the do- while statement is, do statement while (expression);
The statement will be executed repeatedly, as long as the value of expression is true. The statement will
always be executed at least once, since the test for repetition does not occur until the end of the first pass
through the loop. The statement must include some feature that eventually alters the value of expression so
the looping action can terminate.

For loop
The for loop is the most commonly used looping in C. For loop is definite loop (ie. defines the number of
repetitions that will occur during execution).

The statement consists of three parts:


i. Initialization part : Where value is assigned to the variable.
ii. Conditional or Logical Part: where the condition is checked until the expression is true.
iii. Incrementer or decrementer part: Which change index value of the for loop.

Syntax: for (expression1; expression2; expression3)


{
statements;
}
Where expression1 is used to initialize some parameter (called an index) that controls the looping action,
expression2 represents a condition that must be true for the loop to continue execution, and expression3 is
used to alter the value of the parameter initially assigned by expression1. Typically, expression 1 is an
assignment expression, expression2 is a logical expression and expression3 is a unary expression or an
assignment expression.

for

i=i+1

i<=10 Instructions
23 true
false

endfor
The first line of the for-statement contains three expressions, enclosed in parentheses. The first expression
assigns an initial value 0 to the integer variable i; the second expression continues the looping action as long
as the current value of digit does not exceed 10 at the beginning of each pass; and the third expression
increases the value of digit by 1 at the end of each pass through the loop.

5.5-The comma operator


Comma operator (,) is used primarily in conjunction with the for statement. This operator permits two
different expressions to appear in situations where only one expression would ordinarily be used. For
example, it is possible to write for (expression_1a, expression_1b; expression_2; expression_3)
statement

where expression_1a and expression_1b are two expressions, separated by the comma operator. These two
expressions would typically initialize two separate indices that would be used simultaneously within the for
loop similarly, a for statement might make use of the comma operator in the following manner: for
(expression_1a, expression_1b; expression_2; expression_3a, expression_3b) statement

5.6-Nested control structures


When one loop is written inside another loop is called nesting. One if –else statement can be nested within
another. Nested control structures can involve both loops and if –else statements.

Example-8. A sample program that will demonstrate nested for loop structure.
#include <stdio.h>
#include <conio.h>

void main()
{
int i,j;
clrscr(); for (i
=0; i<5;i++)
{
for (j =0; j<=i;++j) printf(" %d ",i);
printf("\n");
}
getch();
}

5.7-Break, continue and goto statement


Break statement
The break statement is used to terminate loops or exit from a switch. It can be used within a for, while, do –
while, or switch statement. If a break statement is included in a while, do –while or for loop, then control
will immediately be transferred out of the loop when the break statement is encountered.
Example a program to determine whether a number is prime or not. A prime number is one
which is divisible only by 1 or itself.
24
#include<stdio.h>
#include<conio.h>
void main()
{ in
t n,
i;
clrscr();

printf("\Enter a number\n");
scanf("%",&n);
i=2;
while(i<n)
{
if(n % i==0)
{
printf("\nNot a prime number");
break;
}
i++;
}
if(i==n)
printf("\nPrime number");
getch();
}

In this program the moment num % i turns out to be zero, the message “Not a prime number” is printed and
the control breaks out of the while loop.

Continue statement
The continue statement is used to bypass the reminder of the current pass through a loop. The loop does not
terminate when a continue statement is encountered. Rather, the remaining loop statements are skipped and
the computation proceeds directly to the next pass through the loop.

Goto statement
The goto statement is used to alter the normal sequence of program execution by transferring control to
some other part of the program. Syntax
goto label;

Where label is an identifier that is used to label the target statement to which control will be transferred. The
target statement must be labeled, and the label must be followed by a colon. Thus, the target statement will
appear as
Label: statement

Example-11
#include<stdio.h>
#include<conio.h>
void main()
{
25
char ch;
clrscr();
printf("Inter any alphebet\n");
ch = getchar();

if ((ch == 'A') || (ch == 'a') || (ch == 'E') || (ch == 'e') || (ch == 'I') || (ch == 'i') || (ch == 'O') || (ch == 'o')
|| (ch == 'U') || (ch == 'u'))
{
printf("\n Youu have typed an alphabet: %c is vowel",ch);
goto label1;
}
printf("\n Youu have typed an alphabet: %c is consonent",ch);
label1:
getch();
}

26

You might also like