Sei sulla pagina 1di 42

INTRODUCTION TO FLOWCHART AND PSEUDOCODE

The flowchart is a means of visually presenting the flow of data through an information processing
system, the operations performed within the system and the sequence in which they are performed.
The program flowchart describes what operations are required in what sequence to solve a given
problem. It can be compared to the blueprint of a building. A programmer prefers to draw a flowchart
prior to writing a computer program. As in the case of the drawing of a blueprint, the flowchart is
drawn according to defined rules and using standard flowchart symbols prescribed by the American
National Standard Institute (ANSI).

Pseudocode is an outline of a program, written in a form that can easily be converted into real
programming statements. Pseudocode cannot be compiled nor executed, and there is no real
formatting or syntax rules. It is simply one-step – an important one – in producing the final code. The
benefit of pseudocode is that it enables the programmer to concentrate on the algorithms without
worrying about all the syntactic details of a particular programming language.

Algorithm is a finite set of instructions that specify a sequence of operations to be carried out in order
to solve a specific problem or class of problems.

Objectives:

At the end of this chapter, you will be able to:

 Know the meaning of flowchart and pseudocode.


 Understand the basic parts of the flowchart such as flowchart symbols and the flowlines
connecting these symbols.
 Know the advantages and limitations of flowchart.

A. Flowcharts

A flowchart is a type of diagram that represents an algorithm or process, showing the steps as boxes of
various kinds, and their order by connecting these with arrows. This diagrammatic representation can
give a step-by-step solution to a given problem. It is common method for defining the logical steps of
flow a program by using a series of symbols to identify basic input, process and output (IPO’s) function
within a program.

Flowcharts are usually drawn using some standard symbols; however, some special symbols can also
be developed when required. Some standard symbols, which are frequently required for flowcharting
for many computer programs are shown below.

Terminal – used to signify the start or end of the program

Preparation/Initialization – signifies the preparation of data

Processing - computational steps or processing function of a program

Input or output – shows input and output. Data are to be read into computer memory
from input device or data are be passed from the memory to an output device.

Decision making and branching – two alternative execution paths are possible. The
path to be followed is selected during the execution by testing whether or not the
condition specify within the outline is fulfilled.

ES 01A – Computer Fundamentals and Programming Page 34


Subroutine or predefined process

On-page connector – shows the entry or exit point of the flowchart, joining of two
parts of program

Off-page connector - designates entry to or exit from one page when a flowchart
requires more than one page

Flowlines – signifies the process that is to be executed next

The following are some guidelines in flowcharting:

a. In drawing a proper flowchart, all necessary requirements should be listed out in logical order.
b. The flowchart should be clear, neat and easy to follow. There should not be any room for
ambiguity in understanding the flowchart.
c. The usual direction of the flow of procedure or system is from left to right or top to bottom.
d. Only one flow line should come out from a process symbol.
e. Only one flow line should enter a decision symbol, but two or three flow lines, one for each
possible answer, should leave the decision symbol
f. Only one flow line is used in conjunction with terminal symbol.
g. If the flowchart becomes complex, it is better to use connector symbols to reduce the number of
flow lines. Avoid the intersection of flow lines if you want to make it more effective and better way
of communication.
h. Ensure that the flowchart has a logical start and finish.
i. It is useful to test the validity of the flowchart by passing through it with a simple test data.

Advantages of Using Flowcharts

The benefits of flowcharts are as follows:

1. Communication: Flowcharts are better way of communicating the logic of a system to all
concerned.
2. Effective analysis: With the help of flowchart, problem can be analyzed in more effective way.
3. Proper documentation: Program flowcharts serve as a good program documentation, which is
needed for various purposes.
4. Efficient Coding: The flowcharts act as a guide or blueprint during the systems analysis and
program development phase.
5. Proper Debugging: The flowchart helps in debugging process.
6. Efficient Program Maintenance: The maintenance of operating program becomes easy with the
help of flowchart. It helps the programmer to put efforts more efficiently on that part.

Limitations of Using Flowcharts

1. Complex logic: Sometimes, the program logic is quite complicated. In that case, flowchart becomes
complex and clumsy.
2. Alterations and Modifications: If alternations are required the flowchart may require re-drawing
completely.
3. Reproduction: As the flowchart symbols cannot be typed, reproduction of flowchart becomes a
problem.
4. The essentials of what is done can easily be lost in the technical details of how it is done.

ES 01A – Computer Fundamentals and Programming Page 35


B. Pseudocode

Pseudocode is a compact and informal high-level description of a computer programming algorithm


that uses the structural conventions of a programming language, but it is intended for human reading
rather than machine reading. Pseudocode typically omits details that are not essential for human
understanding of the algorithm, such as variable declarations, system-specific code and subroutines.
The programming language is augmented with natural language descriptions of the details, where
convenient, or with compact mathematical notation. The purpose of using pseudocode is that it is
easier for humans to understand than conventional programming language code, and that it is an
efficient and environment-independent description of the key principles of an algorithm. It is
commonly used in textbooks and scientific publications that are documenting various algorithms, and
also in planning of computer program development, for sketching out the structure of the program
before the actual coding takes place.

As the name suggests, pseudocode generally does not actually obey the syntax rules of any particular
language; there is no systematic standard form, although any particular writer will generally borrow
style and syntax for example control structures from some conventional programming language.
Variable declarations are typically omitted. Function calls and blocks of code, for example code
contained within a loop, is often replaced by a one-line natural language sentence.

Depending on the writer, pseudocode may therefore vary widely in style, from a near-exact limitation
of a real programming language at one extreme, to a description approaching formatted prose at the
other.

Eg.: Pseudocode that will add 1 to the inputted number.

Input the number


number = number + 1
print the number

C. Basic Control Structures


1. Sequence – process is executed from one to another in a straight-forward manner.

Example 1. Design a flowchart that will accept and display a number. Write its equivalent algorithms.
Start Algorithm:

Step 1: Read in the value of N.


Read N
Step 2: Print the value of N.

Print N

ES 01A – Computer Fundamentals and Programming Page 36


End
Example 2. Create an algorithm and flowchart to convert temperature from Celsius to Fahrenheit.

C: temperature in Celsius
Start
F: temperature Fahrenheit

Algorithm: Input C

Step 1. Input temperature in Celsius (C)


F = (9.0/5.0 * C) + 32
Step 2. F = (9.0/5.0 x C) + 32

Step 3. Display temperature in Fahrenheit (F) Print F

End

2. Conditional statement (if – then – else) – a choice is provided


between two alternatives. It is a statement that check an
expression that may or may not execute a statement or group of
statements depending on the result of the condition.

ES 01A – Computer Fundamentals and Programming Page 37


Example.

3. Iterative statement / Repetition (Looping)


do-while : this structure provides for the repetitive execution of an operation
or routine while the condition is true. As long as the condition is true, the
process is executed, otherwise, control flows out of the structure.

Example. Construct a flowchart that will count from 1 to 10 and print each number
counted using the do-while-repetition structure.

Start
Step 1. Initialize the value of C to 0.

Step 2. Test if C is less than 10


C=0
Step 3. If C is less that 10, add 1 to the value of
C, print the value then go back to Step 2.
F However, if C is greater than 10, stop
C < 10 End processing.

ES 01A – Computer Fundamentals and Programming Page 38


T

C=C+1

Print C

Self – Review Exercises 1:

I. Fill in the blanks in each of the following questions.


1. A program flowchart indicates the _____ to be performed and the _____ in which they occur.
2. A program flowchart is generally read from _____ to _____.
3. Flowcharting symbols are connected together by means of ______.
4. A decision symbol may be used in determining the ______ or _____ of two data items.
5. ______ are used to join remote portions of a flowchart.
6. ______ connectors are used when a flowchart ends on one page and begins again on other page.
7. A _____ symbol in used at the beginning and end of a flowchart.
8. The flowchart is one of the best ways of _____ a program.
9. To construct a flowchart, one must adhere to prescribed symbols provided by the _____.
10. The programmer uses a ______ to aid in drawing flowchart symbols.
11. A procedure for solving a problem in terms of the actions to be executed and the order in which
the actions should be executed is called a(n) ______.
12. Specifying the execution order of statements by the computer is called _____.
13. All programs can be written in terms of three types of control statements: _____, _____ and ____.
14. The _____ selection statement is used to execute one action when a condition is true and another
action when that condition is false.
15. Several statements grouped together in braces ({ and }) are called a(n) ______.
16. The ____ repetition statement specifies that a statement or group statements is to be executed
repeatedly while some condition remains true.
17. Repetition of a set of instructions a specific number of times is called ____ repetition.
18. When it is not known in advance how many times a set of statements will be repeated, a(n) ____
value can be used to terminate the repetition.
19. ____ is an artificial and informal language that helps programmers develop algorithms.
20. ____ is a set of rules that defines the combinations of symbols that are considered to be a correctly
structured document or fragment in a computer language.

II. Research Activity: Design a flowchart and write its equivalent algorithm of the following basic
control structure:

4 item/problem for sequence; 3 for section; and 3 for looping

ES 01A – Computer Fundamentals and Programming Page 39


BASIC C LANGUAGE PROGRAMMING

C is a general-purpose programming language. It has been closely associated with the UNIX system
where it was developed, since both the system and most of the programs that run on it are written in
C. The language, however, is not tied to any one operating system or machine; and although it has
been called a “system programming” because it is useful for writing compilers and operating systems,
it has used usually well to write major programs in many different domains.

A. Brief History of C Language

Late 1960s BCPL (Basic Combined Programming Language) was designed by Martin
Richards of University of Cambridge.
1970 B Language was designed by Ken Thompson of AT&T Bell Laboratories for
systems programming. (Accounts differ regarding the origins of the name “B”.
Ken Thompson credits the BCPL programming language, but he had also
created a language called “Bon” in honor of his wife Bonnie)

1972 C language was designed by Dennis Ritchie, also of AT&T Bell Laboratories, for
writing the Unix operating system. (It was named “C” because many of its
features were derived from B language.

1970s, 80s Unix and C gained wide popularity.

1989 C standardized: ANSI (American National Standards Institute) standard X3.159-


1989.

1990 C adopted as an international standard by ISO (International Organization for


Standardization): ISO 9899:1990.

1990s Minor amendments made to the standards.

B. Advantages and Disadvantages of C Language


Given below are the advantages and disadvantages of C language:

Advantages:

 C is a real world language, widely available and popular among programmers.


 C is a small, efficient, powerful, flexible and versatile programming language. It can be used
develop programs for all sorts of applications.
 C has been standardized (adhering to the ANSI standard), making it portable across different
computing platforms. Very little modification is required when moving across platforms, e.g., a
program written in DOS will still be compiled in UNIX with hardly any changes in the code.

ES 01A – Computer Fundamentals and Programming Page 40


 C is close to the computer hardware revealing the underlying architecture to provide enough
low level access to be suitable for embedded systems.
 C is a high level language allowing complex systems to be constructed with minimum effort.
 C’s use of libraries makes it adaptable to many different application areas.
 The Unix operating system was written in C and supports C.
 C gave birth to C++, widely used for applications programming and more recently Java which
was based upon C++.
 Many other languages borrow from C’s syntax: e.g. Java, JavaScript, Pearl etc.

Disadvantages:

 C is not really a language for novices; it was designed for professional users.
 There are many things that can go wrong if you’re not careful. Small typing errors can cause
unwanted effect.
 C lacks much of the automatic checking found in other high level languages.
 Does not support modern concepts such as object orientation and multi-threading.

C. Compiler Versus Interpreters

The terms compiler and interpreter refers to the way in which a program is executed. In theory, any
programming language can be either compiled or interpreted, but some languages are usually
executed one way or the other. For example, Turbo BASIC is usually compiled (C interpreters have
some value as debugging aids). The way a program is executed is not defined by the language in which
it is written. Interpreters and compilers are simply sophisticated programs that operate on your
program source code.

An interpreter reads the source code of your program one line at a time and performs the specific
instructions contained in that line. A compiler reads the program and checks the whole program for
syntax errors but does not execute any of the code. The output of this process is called the object
code, which is a translation of the program source code into a form that can e directly executed by the
computer. Object code is also called binary code and machine code. Once a program is compiled, a line
of source code is no longer meaningful in the execution of the program.

Figure C.1 illustrates how an interpreter does the translation while the flowchart in Figure C.2 shows
the compilation process.

ES 01A – Computer Fundamentals and Programming Page 41


D. Parts of C Environment

1.) Main Menu – instruct C to do something as indicated in the list of menu. It can be activated or can
be used by pressing Alt key and the 1 st letter of the menu.

Basic Menus of C:

1. File – used to load and save files, handles directories, invokes DOS and exist C.
Submenus under the File menu
a.) Load – enables the user to select a file to be opened or loaded into the editor (F3)

ES 01A – Computer Fundamentals and Programming Page 42


b.) Pick – enables the user to select a file based on the last nine files previously opened or
edited (Alt F3)
c.) New – lets the user edit a new file or start a new program.
d.) Save – store or “saves the file currently in the editor”(F2).
e.) Write to – enables the user to “save a file using a different filename”.
f.) Directory – displays the content of the current working directory
g.) Change dir – to specify the defined path to change the default path or directory
h.) OS shell – loads the DOS command processor and lets the user execute DOS commands
i.) Quit – lets the user to exit or quit (Alt X)
2. Run – used to “compile (check for error), links, and runs the program currently loaded in the
environment.
3. Compile – used to compile the program currently in the environment.

2.) Editor status line and Edit window


- it is where you type your program and where you see the current line and column of the text
you typed.
3.) Message Window
- located beneath the middle of edit window and Hotkeys. It is used to display various compiler
or line messages.
4.) Hot keys
- Located at the bottom of C opening screen. It is used to shortcut or shorthand for selecting a
menu. Two sets of hotkeys: normal ones and alternate set
E. Elements of a C Program

Example of a simple program in C.

/* A simple C program*/
#include <stdio.h>
#include <conio.h>
main ()
{
clrscr();
printf(“This is the output of my first C program.\n”);
getch();
}
//end of Program

 The characters /* and */ mark the start and end of the program comment. As with any
programming language, program comments are used to put clarificatory notes within the program
code, and ae ignored by the compiler. Program comments may be used anywhere in the program,
and may be of any length. However, the programmer should check that no part of the actual code
is in between the /* and */ characters so that it will not be ignored by the compiler. In compilers
that support both C and C++, the double forward slash (//) is also used for comments. The
comments, however, extend only from the double slash at the end of the line.
 This C program starts with #include<stdio.h>. This line is called a preprocessor directive and it will
include the “standard I/O library” into your program. The standard I/O library lets you read input
from the keyboard (called “standard in”), write output to the screen (called “standard out”),
process text files stored in the disk, and so on. It is an extremely useful library. Another header file

ES 01A – Computer Fundamentals and Programming Page 43


is the <conio.h>, which is used for screen-handling functions. The getch() function located at the
bottom part of the program uses this header file. C has a large number of standard libraries like
stdio, including string, time and math libraries. A library is simply a package of code that someone
else has written to make your programming easier.
 The line main() declares the main function. Every C program must have a function named main
somewhere in the code. At run time, program execution starts at the first line of the main function.
 In C, the { and } symbols mark the beginning and end of a block of code. In this case, the block of
code making up the main function contains three lines. The first line clrscr(); is used to clear the
screen.
 The printf statement in C allows you to send output to standard out (for us, the screen). The text to
be printed is enclosed in double quotes (“This is the output of my first C program. \n”). The \n at
the end of the text tells the program to print a newline as part of the output.
 The getch() function; line that reads a character from the keyboard without echo on the screen
and does not wait for carriage return.

Important Symbols:
\n – a line char used to move the cursor to the next line
‘ ‘ – single quote is used for single character/letter
“ “ – double quote is used for two or more character
{ – open curly brace signifies begin
} – close curly brace signifies end
& – address of operator
* – indicator operator/pointer
; – terminator

printf and scanf


 printf() and scanf() functions are inbuilt library functions in C programming language which are
available in C library by default. These functions are declared and related macros are defined in
“stdio.h” which is a header file in C language.
 We have to include “stdio.h” file as shown in below C program to make use of these printf()
and scanf() library functions in C language.

1. PRINTF() FUNCTION:
 In C programming language, printf() function is used to print the “character, string, float,
integer, octal and hexadecimal values” onto the output screen.
 We use printf() function with %d format specifier to display the value of an integer variable.
 Similarly %c is used to display character, %f for float variable, %s for string variable, %lf for
double and %x for hexadecimal variable.
 To generate a newline, we use “\n” in C printf() statement.
 Syntax: printf(“control string codes”, argument list);
 Example: printf(“Hello, %s, you are %d years old”, name, age);
Note:
 C language is case sensitive. For example, printf() and scanf() are different from Printf() and
Scanf(). All characters in printf() and scanf() functions must be in lower case.

2. SCANF() FUNCTION:
 In C programming language, scanf() function is used to read character, string, numeric data
from keyboard
 Consider below example program where user enters a character. This value is assigned to the
variable “ch” and then displayed.
 Then, user enters a string and this value is assigned to the variable “str” and then displayed.

ES 01A – Computer Fundamentals and Programming Page 44


 Syntax: scanf(“control string codes”, identifier);
 Example: scanf(“%d’, & num);

EXAMPLE PROGRAM FOR PRINTF() AND SCANF() FUNCTIONS IN C PROGRAMMING LANGUAGE:

 The format specifier %d is used in scanf() statement. So that, the value entered is received as
an integer and %s for string.
 Ampersand is used before variable name “ch” in scanf() statement as &ch.
KEY POINTS TO REMEMBER IN PRINTF() AND SCANF():
1. printf() is used to display the output and scanf() is used to read the inputs.
2. printf() and scanf() functions are declared in “stdio.h” header file in C library.
3. All syntax in C language including printf() and scanf() functions are case sensitive.

Data types in C Language


Data types specify how we enter data into our programs and what type of data we enter. C language
has some predefined set of data types to handle various kinds of data that we can use in our program.
These datatypes have different storage capacities.

C language supports 2 different type of data types:


1. Primary data types:
These are fundamental data types in C namely integer (int), floating point (float),
character(char) and void.
2. Derived data types:
Derived data types are nothing but primary datatypes but a little twisted or grouped together
like array, structure, union and pointer.
Data type determines the type of data a variable will hold. If a variable x is declared as int. it means x
can hold only integer values. Every variable which is used in the program must be declared as what
data-type it is.

1. Integer type - are used to store whole numbers.


Size and range of Integer type on 16-bit machine:

ES 01A – Computer Fundamentals and Programming Page 45


Type Size(bytes) Range
int or signed int 2 -32,768 to 32767
unsigned int 2 0 to 65535
short int or signed short int 1 -128 to 127
unsigned short int 1 0 to 255
long int or signed long int 4 -2,147,483,648 to 2,147,483,647
unsigned long int 4 1 to 4,294,967,295

2. Floating point type - are used to store real numbers (real numbers have both an integer and a
fractional component)

Size and range of Integer type on 16-bit machine


Type Size(bytes) Range
Float 4 3.4E-38 to 3.4E+38
double 8 1.7E-308 to 1.7E+308
long double 10 3.4E-4932 to 1.1E+4932
3. Character type - used to store characters value.
Size and range of Integer type on 16-bit machine

Type Size(bytes) Range


char or signed char 1 -128 to 127
unsigned char 1 0 to 255

4. void type - means no value. This is usually used to specify the type of functions which returns
nothing.

MODIFIERS IN C LANGUAGE:
 It is used to alter the meaning of the base type to fit the needs of various situations more
precisely.
 The amount of memory space to be allocated for a variable is derived by modifiers.
 Modifiers are prefixed with basic data types to modify (either increase or decrease) the
amount of storage space allocated to a variable.
 For example, storage space for int data type is 4 byte for 32 bit processor. We can increase the
range by using long int which is 8 byte. We can decrease the range by using short int which is 2
byte.
 Modifiers available in C language:
1. short
2. long
3. signed
4. unsigned

ES 01A – Computer Fundamentals and Programming Page 46


Tokens and keywords
1. TOKENS:
 Tokens are the basic buildings blocks in C language which are constructed together to write a C
program.
 Each and every smallest individual units in a C program are known as tokens.
Tokens are of six types. They are,
1. Keywords               (eg: int, while),
2. Identifiers               (eg: main, total),
3. Constants              (eg: 10, 20),
4. Strings                    (eg: “total”, “hello”),
5. Special symbols  (eg: (), {}),
6. Operators              (eg: +, /,-,*)

where,
 main – identifier
 {,}, (,) – delimiter
 int – keyword
 x, y, total – identifier
 main, {, }, (, ), int, x, y, total – tokens

2. IDENTIFIERS IN C LANGUAGE:
 Each program elements in a C program are given a name called identifiers.
 Names given to identify Variables, functions and arrays are examples for identifiers. eg. x is a
name given to integer variable in above program.

RULES FOR CONSTRUCTING IDENTIFIER NAME IN C:


1. First character should be an alphabet or underscore.
2. Succeeding characters might be digits or letter.
3. Punctuation and special characters aren’t allowed except underscore.
4. Identifiers should not be keywords.

3. KEYWORDS IN C LANGUAGE:
 Keywords are pre-defined words in a C compiler.
 Each keyword is meant to perform a specific function in a C program.
 Since keywords are referred names for compiler, they can’t be used as variable name.

C language supports 32 keywords which are given below. 


auto double int struct const float short unsigned

break else long switch continue for signed viod

ES 01A – Computer Fundamentals and Programming Page 47


case enum register typedef default goto sizeof volatile

char estern return union do if static while

Constant
 Constants are also like normal variables. But, only difference is, their values cannot be
modified by the program once they are defined.
 Constants refer to fixed values. They are also called as literals
 Constants may be belonging to any of the data type.
 Syntax: const data_type variable_name; (or) const data_type *variable_name;

TYPES OF C CONSTANT:

1. INTEGER
 An integer constant must have at least one digit.
 It must not have a decimal point.
 It can either be positive or negative.
 No commas or blanks are allowed within an integer constant.
 If no sign precedes an integer constant, it is assumed to be positive.
 The allowable range for integer constants is -32768 to 32767.
 Example: int (53, 762, -478 etc )
unsigned int (5000u, 1000U etc)
long int, long long int
(483,647 2,147,483,680)

2. REAL OR FLOATING POINT


 A real constant must have at least one digit
 It must have a decimal point
 It could be either positive or negative
 If no sign precedes an integer constant, it is assumed to be positive.
 No commas or blanks are allowed within a real constant.
 Example: float (10.456789)
double (600.123456789)

3. CHARACTER AND STRING


 A character constant is a single alphabet, a single digit or a single special symbol enclosed
within single quotes.
 The maximum length of a character constant is 1 character.
 String constants are enclosed within double quotes.
 Example: char (Example: ‘A’, ‘B’, ‘C’)
char (Example: “ABCD”, “Hai”)

4. BACKSLASH CHARACTER
 There are some characters which have special meaning in C language.
 They should be preceded by backslash symbol to make use of special function of them.
 Given below is the list of special characters and their purpose.
Backslash_character Meaning
\b Backspace

ES 01A – Computer Fundamentals and Programming Page 48


\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\” Double quote
\’ Single quote
\\ Backslash
\v Vertical tab
\a Alert or bell
\? Question mark
\N Octal constant (N is an octal constant)
\XN Hexadecimal constant (N – hex.dcml cnst)

Variable
  Variable is a named location in a memory where a program can manipulate the data. This location is
used to hold the value of the variable.
 The value of the C variable may get change in the program.
 C variable might be belonging to any of the data type like int, float, char etc.

RULES FOR NAMING VARIABLE:


1. Variable name must begin with letter or underscore.
2. Variables are case sensitive
3. They can be constructed with digits, letters.
4. No special symbols are allowed other than underscore.
5. sum, height, _value are some examples for variable name

DECLARING & INITIALIZING VARIABLE:


 Variables should be declared in the C program before to use.
 Memory space is not allocated for a variable while declaration. It happens only on variable
definition.
 Variable initialization means assigning a value to the variable.
 Type  Syntax

data_type variable_name;
Variable declaration Example: int x, y, z; char flat, ch;

data_type variable_name = value;


Variable initialization Example: int x = 50, y = 30; char flag = ‘x’, ch=’l’;

THERE ARE THREE TYPES OF VARIABLES IN C PROGRAM:


1. Local variable
- The scope of local variables will be within the function only.
- These variables are declared within the function and can’t be accessed outside the function.
2. Global variable

ES 01A – Computer Fundamentals and Programming Page 49


- The scope of global variables will be throughout the program. These variables can be accessed
from anywhere in the program.
- This variable is defined outside the main function. So that, this variable is visible to main
function and all other sub functions.
3. Environment variable
- Environment variable is a variable that will be available for all C applications and C programs.
- We can access these variables from anywhere in a C program without declaring and initializing
in an application or C program.
- The inbuilt functions which are used to access, modify and set these environment variables are
called environment functions.
-
DIFFERENCE BETWEEN VARIABLE DECLARATION & DEFINITION IN C:
Variable Declaration Variable definition

Declaration tells the compiler about data Definition allocates memory for the
type and size of the variable. variable.

Variable can be declared many times in a It can happen only one time for a
program. variable in a program.

The assignment of properties and Assignments of storage space to a


identification to a variable. variable.

Operators and Expressions


 The symbols which are used to perform logical and mathematical operations are called
operators.
 These operators join individual constants and variables to form expressions.
 Operators, functions, constants and variables are combined together to form expressions.
 Consider the expression A + B * 5. where, +, * are operators, A, B  are variables, 5 is constant
and A + B * 5 is an expression.

TYPES OF OPERATORS:

1. ARITHMETIC OPERATORS IN C:

Arithmetic operators are used to perform mathematical calculations like addition, subtraction,
multiplication, division and modulus in C programs.

Arithmetic Operators/Operation Example

+ (Addition) A+B

– (Subtraction) A-B

* (multiplication) A*B

/ (Division) A/B

% (Modulus) A%B

ES 01A – Computer Fundamentals and Programming Page 50


EXAMPLE PROGRAM FOR C ARITHMETIC OPERATORS:
In this example program, two values “40” and “20” are used to perform arithmetic operations such
as addition, subtraction, multiplication, division, modulus and output is displayed for each operation.

2. ASSIGNMENT OPERATORS:
 In C programs, values for the variables are assigned using assignment operators.
 For example, if the value “10” is to be assigned for the variable “sum”, it can be assigned as
“sum = 10;”
 There are 2 categories of assignment operators in C language. They are,
1. Simple assignment operator ( Example: = )
2. Compound assignment operators ( Example: +=, -=, *=, /=, %=, &=, ^= )
Operators Example/Description

sum = 10;
= 10 is assigned to variable sum

sum += 10;
+= This is same as sum = sum + 10

sum -= 10;
-= This is same as sum = sum – 10

sum *= 10;
*= This is same as sum = sum * 10

sum /= 10;
/= This is same as sum = sum / 10

sum %= 10;
%= This is same as sum = sum % 10

ES 01A – Computer Fundamentals and Programming Page 51


sum&=10;
&= This is same as sum = sum & 10

sum ^= 10;
^= This is same as sum = sum ^ 10
EXAMPLE PROGRAM FOR C ASSIGNMENT OPERATORS:
 In this program, values from 0 – 9 are summed up and total “45” is displayed as output.
 Assignment operators such as “=” and “+=” are used in this program to assign the values and to sum up
the values.

3. RELATIONAL OPERATORS IN C:
Relational operators are used to find the relation between two variables. i.e. to compare the values of two
variables in a C program.

Operators Example/Description
> x > y (x is greater than y)
< x < y (x is less than y)
>= x >= y (x is greater than or equal to y)
<= x <= y (x is less than or equal to y)
== x == y (x is equal to y)
!= x != y (x is not equal to y)

EXAMPLE PROGRAM FOR RELATIONAL OPERATORS IN C:


 In this program, relational operator (==) is used to compare 2 values whether they are equal are not.
 If both values are equal, output is displayed as ” values are equal”. Else, output is displayed as “values
are not equal”.
 Note : double equal sign (==) should be used to compare 2 values. We should not single equal sign (=).

ES 01A – Computer Fundamentals and Programming Page 52


4. LOGICAL OPERATORS:
 These operators are used to perform logical operations on the given expressions.
 There are 3 logical operators in C language. They are, logical AND (&&), logical OR (||) and
logical NOT (!).
Operators Example/Description

&& (logical (x>5)&&(y<5)


AND) It returns true when both conditions are true

(x>=10)||(y>=10)
|| (logical OR) It returns true when at-least one of the condition is true

!((x>5)&&(y<5))
It reverses the state of the operand “((x>5) && (y<5))”
! (logical NOT) If “((x>5) && (y<5))” is true, logical NOT operator makes it false

ES 01A – Computer Fundamentals and Programming Page 53


EXAMPLE PROGRAM FOR LOGICAL OPERATORS IN C:

 In this program, operators (&&, || and !) are used to perform logical operations on the given
expressions.
 && operator – “if clause” becomes true only when both conditions (m>n and m! =0) is true.
Else, it becomes false.
 || Operator – “if clause” becomes true when any one of the condition (o>p || p!=20)  is true. It
becomes false when none of the condition is true.
 ! Operator  – It is used to reverses the state of the operand.
 If the conditions (m>n && m!=0) is true, true (1) is returned. This value is inverted by “!”
operator.
 So, “! (m>n and m! =0)” returns false (0).

5. BIT WISE OPERATORS:
 These operators are used to perform bit operations. Decimal values are converted into binary
values which are the sequence of bits and bit wise operators work on these bits.
 Bit wise operators in C language are & (bitwise AND), | (bitwise OR), ~ (bitwise NOT), ^ (XOR),
<< (left shift) and >> (right shift).

ES 01A – Computer Fundamentals and Programming Page 54


TRUTH TABLE FOR BIT WISE OPERATION & BIT WISE OPERATORS:

BELOW ARE THE BIT-WISE OPERATORS AND THEIR NAME IN C LANGUAGE.

1. & – Bitwise AND


2. | – Bitwise OR
3. ~ – Bitwise NOT
4. ^ – XOR
5. << – Left Shift
6. >> – Right Shift

Consider x=40 and y=80. Binary form of these values are given below.
x = 00101000
y=  01010000

All bit wise operations for x and y are given below.


 x&y = 00000000 (binary) = 0 (decimal)
 x|y = 01111000 (binary) = 120 (decimal)
 ~x = 11111111111111111111111111 11111111111111111111111111111111010111 = -41
(decimal)
 x^y = 01111000 (binary) = 120 (decimal)
 x << 1 = 01010000 (binary) = 80 (decimal)
 x >> 1 = 00010100 (binary) = 20 (decimal)

NOTE:
 Bit wise NOT : Value of 40 in binary is 00000000000000000000000000000000
00000000000000000010100000000000. So, all 0’s are converted into 1’s in bit wise NOT
operation.
 Bit wise left shift and right shift : In left shift operation “x << 1 “, 1 means that the bits will be
left shifted by one place. If we use it as “x << 2 “,  then, it means that the bits will be left shifted by
2 places.

EXAMPLE PROGRAM FOR BIT WISE OPERATORS IN C:


In this example program, bit wise operations are performed as shown above and output is displayed in
decimal format.

ES 01A – Computer Fundamentals and Programming Page 55


6. CONDITIONAL OR TERNARY OPERATORS:
 Conditional operators return one value if condition is true and returns another value is
condition is false.
 This operator is also called as ternary operator.
Syntax     :        (Condition? true_value: false_value);

Example :         (A > 100  ?  0  :  1);

 In above example, if A is greater than 100, 0 is returned else 1 is returned.  This is equal to if
else conditional statements.

EXAMPLE PROGRAM FOR CONDITIONAL/TERNARY OPERATORS:

ES 01A – Computer Fundamentals and Programming Page 56


7. Increment/decrement Operators
 Increment operators are used to increase the value of the variable by one and decrement
operators are used to decrease the value of the variable by one in C programs.
 Syntax:
Increment operator: ++var_name; (or) var_name++;
Decrement operator: – -var_name; (or) var_name – -;
 Example:
Increment operator :  ++ i ;    i ++ ;
Decrement operator :  – – i ;   i – – ;

EXAMPLE PROGRAM FOR INCREMENT OPERATORS:


In this program, value of “i” is incremented one by one from 1 up to 9 using “i++” operator and output
is displayed as “1 2 3 4 5 6 7 8 9”.

EXAMPLE PROGRAM FOR DECREMENT OPERATORS:


In this program, value of “I” is decremented one by one from 20 up to 11 using “i–” operator and
output is displayed as “20 19 18 17 16 15 14 13 12 11”.

ES 01A – Computer Fundamentals and Programming Page 57


DIFFERENCE BETWEEN PRE/POST INCREMENT & DECREMENT OPERATORS:
Below table will explain the difference between pre/post increment and decrement operators.
             Operator  Operator/Description

Pre increment operator (++i) value of i is incremented before assigning it to the


variable i

Post increment operator (i++) value of i is incremented after assigning it to the


variable i

Pre decrement operator (–i) value of i is decremented before assigning it to the


variable i

Post decrement operator (i–) value of i is decremented after assigning it to variable i

EXAMPLE PROGRAM FOR PRE – INCREMENT OPERATORS:

 Step 1 : In above program, value of “i” is incremented from 0 to 1 using pre-increment


operator.
 Step 2 : This incremented value “1” is compared with 5 in while expression.
 Step 3 : Then, this incremented value “1” is assigned to the variable “i”.
 Above 3 steps are continued until while expression becomes false and output is displayed as “1
2 3 4”.

ES 01A – Computer Fundamentals and Programming Page 58


EXAMPLE PROGRAM FOR POST – INCREMENT OPERATORS:

 Step 1 : In this program, value of  i “0” is compared with 5 in while expression.


 Step 2 : Then, value of “i” is incremented from 0 to 1 using post-increment operator.
 Step 3 : Then, this incremented value “1” is assigned to the variable “i”.
 Above 3 steps are continued until while expression becomes false and output is displayed as “1
2 3 4 5”.

EXAMPLE PROGRAM FOR PRE – DECREMENT OPERATORS:

 Step 1 : In above program, value of “i” is decremented from 10 to 9 using pre-decrement


operator.
 Step 2 : This decremented value “9” is compared with 5 in while expression.
 Step 3 : Then, this decremented value “9” is assigned to the variable “i”.
 Above 3 steps are continued until while expression becomes false and output is displayed as “9
8 7 6”.

ES 01A – Computer Fundamentals and Programming Page 59


EXAMPLE PROGRAM FOR POST – DECREMENT OPERATORS:

 Step 1 : In this program, value of  i “10” is compared with 5 in while expression.


 Step 2 : Then, value of “i” is decremented from 10 to 9 using post-decrement operator.
 Step 3 : Then, this decremented value “9” is assigned to the variable “i”.
 Above 3 steps are continued until while expression becomes false and output is displayed as “9
8 7 6 5”. 

8. SPECIAL OPERATORS:
Below are some of the special operators that the C programming language offers.

Operators Description

This is used to get the address of the variable.


& Example : &a will give address of a.

This is used as pointer to a variable.


* Example : * a  where, * is pointer to the variable a.

This gives the size of the variable.


Sizeof () Example : size of (char) will give us 1.

EXAMPLE PROGRAM FOR & AND * OPERATORS:


In this program, “&” symbol is used to get the address of the variable and “*” symbol is used to get the
value of the variable that the pointer is pointing to.

ES 01A – Computer Fundamentals and Programming Page 60


EXAMPLE PROGRAM FOR SIZEOF() OPERATOR IN C:
sizeof() operator is used to find the memory space allocated for each C data types.

Decision Control statement

 In decision control statements (if-else and nested if), group of statements are executed when
condition is true.  If condition is false, then else part statements are executed.
 3 types of decision making control statements:
1.   if statements
2.   if else statements
3.   nested if statements
“IF”, “ELSE” AND “NESTED IF” DECISION CONTROL STATEMENTS:

Syntax for each C decision control statements are given in below table with description.
Decision control  Syntax/Description 
statements

if Syntax:
if (condition)

ES 01A – Computer Fundamentals and Programming Page 61


{ Statements; }Description:
In these type of statements, if condition is true, then respective
block of code is executed.

if…else Syntax:
if (condition)
{ Statement1; Statement2; }
else
{ Statement3; Statement4; }Description:
In these type of statements, group of statements are executed
when condition is true.  If condition is false, then else part
statements are executed.

nested if Syntax:
if (condition1){ Statement1; }
else_if(condition2)
{ Statement2; }
else Statement 3;Description:
If condition 1 is false, then condition 2 is checked and statements
are executed if it is true. If condition 2 also gets failure, then else
part is executed.
EXAMPLE PROGRAM FOR IF STATEMENT:

In “if” control statement, respective block of code is executed when condition is true.

EXAMPLE PROGRAM FOR IF ELSE STATEMENT:

In C if else control statement, group of statements are executed when condition is true.  If condition is
false, then else part statements are executed.

ES 01A – Computer Fundamentals and Programming Page 62


EXAMPLE PROGRAM FOR NESTED IF STATEMENT:

 In “nested if” control statement, if condition 1 is false, then condition 2 is checked and
statements are executed if it is true. 
 If condition 2 also gets failure, then else part is executed.

Loop control statements

ES 01A – Computer Fundamentals and Programming Page 63


Loop control statements in C are used to perform looping operations until the given condition is true.
Control comes out of the loop statements once condition becomes false.

TYPES OF LOOP CONTROL STATEMENTS:


There are 3 types of loop control statements:
1. for
2. while
3. do-while

Syntax for each loop control statements are given in below table with description.
 Loop Name  Syntax 

for for (exp1; exp2; expr3)


{ statements; } where,
exp1 – variable initialization
( Example: i=0, j=2, k=3 )
exp2 – condition checking
( Example: i>5, j<3, k=3 )
exp3 – increment/decrement
( Example: ++i, j–, ++k )

while while (condition)


{ statements; }where,
condition might be a>5, i<10

do while do { statements; }
while (condition);where,
condition might be a>5, i<10

EXAMPLE PROGRAM (FOR LOOP:

In for loop control statement, loop is executed until condition becomes false.

ES 01A – Computer Fundamentals and Programming Page 64


EXAMPLE PROGRAM (WHILE LOOP):

In while loop control statement, loop is executed until condition becomes false.

EXAMPLE PROGRAM (DO WHILE LOOP):

In do..while loop control statement, while loop is executed irrespective of the condition for first time.
Then 2nd time onwards, loop is executed until condition becomes false.

ES 01A – Computer Fundamentals and Programming Page 65


Case control statements
The statements which are used to execute only specific block of statements in a series of blocks are
called case control statements.

There are 4 types of case control statements:

1. SWITCH CASE STATEMENT:


 Switch case statements are used to execute only specific case statements based on the switch
expression.
 Below is the syntax for switch case statement.
switch (expression)
{
     case label1:   statements;
                           break;
     case label2:   statements;
                           break;
     case label3:   statements;
                           break;
     default:      statements;
                           break;
}

ES 01A – Computer Fundamentals and Programming Page 66


EXAMPLE PROGRAM FOR SWITCH..CASE STATEMENT:

1. BREAK STATEMENT:
 Break statement is used to terminate the while loops, switch case loops and for loops from the
subsequent execution.
 Syntax: break;

ES 01A – Computer Fundamentals and Programming Page 67


EXAMPLE PROGRAM FOR BREAK STATEMENT:

3. CONTINUE STATEMENT:
 Continue statement is used to continue the next iteration of for loop, while loop and do-while
loops.  So, the remaining statements are skipped within the loop for that particular iteration.
 Syntax : continue;
EXAMPLE PROGRAM FOR CONTINUE STATEMENT IN C:

4. GOTO STATEMENT:
 goto statements is used to transfer the normal flow of a program to the specified label in the
program.

ES 01A – Computer Fundamentals and Programming Page 68


 Below is the syntax for goto statement in C.
{
         …….
         go to label;
         …….
         …….
         LABEL:
         statements;
}
EXAMPLE PROGRAM FOR GOTO STATEMENT:

Array in C
Array is a collection of variables belongings to the same data type. You can store group of data of same
data type in an array.
a) Array might be belonging to any of the data types
b) Array size must be a constant value.

ES 01A – Computer Fundamentals and Programming Page 69


c) Always, Contiguous (adjacent) memory locations are used to store array elements in memory.
d) It is a best practice to initialize an array to zero or null while declaring, if we don’t assign any
values to array.
e)
EXAMPLE FOR ARRAYS:

 int a[10];       // integer array


 char b[10];    // character array   i.e. string

There are 2 types of C arrays.


1. ONE DIMENSIONAL ARRAY IN C:

Syntax : data-type arr_name[array_size];

Array declaration, initialization and accessing  Example

Integer array example:

int age [5];


int age[5]={0, 1, 2, 3, 4};

age[0]; /*0 is accessed*/


age[1]; /*1 is accessed*/
age[2]; /*2 is accessed*/

Character array example:
char str[10];
char str[10]={‘H’,‘a’,‘i’};
(or)
char str[0] = ‘H’;
char str[1] = ‘a’;
char str[2] = ‘i;

Array declaration syntax:


data_type arr_name [arr_size];Array initialization syntax:
data_type arr_name [arr_size]=(value1, value2, value3, str[0]; /*H is accessed*/
str[1]; /*a is accessed*/
….);Array accessing syntax:
str[2]; /*i is accessed*/
arr_name[index];

ES 01A – Computer Fundamentals and Programming Page 70


EXAMPLE PROGRAM FOR ONE DIMENSIONAL ARRAY:

2. TWO DIMENSIONAL ARRAY:

 Two dimensional array is nothing but array of array.


 syntax : data_type array_name[num_of_rows][num_of_column];
Array declaration, initialization and accessing  Example

Array declaration syntax: Integer array example:


data_type arr_name [num_of_rows]
int arr[2][2];
[num_of_column];Array initialization syntax:
int arr[2][2] = {1,2, 3, 4};
data_type arr_name[2][2] = {{0,0},{0,1},{1,0},
{1,1}};Array accessing syntax:
arr [0] [0] = 1;
arr_name[index]; arr [0] ]1] = 2;
arr [1][0]  = 3;
arr [1] [1] = 4;

ES 01A – Computer Fundamentals and Programming Page 71


EXAMPLE PROGRAM FOR TWO DIMENSIONAL ARRAY:

ES 01A – Computer Fundamentals and Programming Page 72


Self-Review Exercises 2.

1.1. Fill in the blanks in each of the following.


a) The ____ tells the compiler to include the standard input/output header in the program.
b) Every c program begins execution at the function _____.
c) The ____ begins the body of every function and the ____ ends the body of every function.
d) Every statement ends with a(n) _____.
e) The _____ standard library function displays information on the screen.
f) The escape sequence \n represents the ____ character which causes the cursor to position to the
beginning of the next line on the screen.
g) The ____ standard library function is used to obtain data from the keyboard.
h) The conversion specifier ____ is used in a scanf format control string to indicate that an integer will be
input and in a printf format control string to indicate that an integer will be output.
i) The ____ statement is to make decisions.
j) The ____ evaluates arithmetic expressions in a precise sequence determined by the rules of operator
precedence and associativity.

1.2. State whether each of the following is true or false. If false, explain why.
a) When the printf function is called, it always begins printing at the beginning of a new line.
b) Comments cause the computer to print the text enclosed between /* and */ on the screen when the
program is executed.
c) The escape sequence \n when used in a printf format control string causes the cursor to position to the
beginning of the next line on the screen.
d) All variables must be defined before they are used.
e) All variables must be given a type when they are defined.
f) C considers the variables number and NuMbEr to be identical.
g) Definitions can appear anywhere in the body of a function.
h) All arguments following the format control string in a printf function must be preceded by an ampersand
(&).
i) The remainder operator (%) can be used only with integer operands.
j) The arithmetic operators *, /, %, + and – all have the same level of precedence.

1.3. Write a single C statement to accomplish each of the following:


a) Define the variables c, thisVariable, q76354 and number to be of type int.
b) Prompt the user to enter an integer. End your prompting message with a colon (:) followed by a space
and leave the cursor positioned after the space.
c) Read an integer from the keyboard and store the value entered in integer variable a.
d) If number is not equal to 7, print “The variable number is not equal to 7.”
e) Print the message “This is a C program.” on one line.
f) Print the message “This is a C program.” on two lines so that the first line ends with C.
g) Print the message ”This is a C program.” with each word on a separate line.
h) Print the message “This is a C program.” with each word separated by tabs.

1.4. Write a statement (or comment) to accomplish each of the following:


a) State the a program will calculate the product of three integers.
b) Define the variables x, y, z and result to be of type int.
c) Prompt the user to enter three integers.
d) Read three integers from the keyboard and store them in the variables x, y and z.
e) Compute the product of the three integers contained in variables x, y, z, and assign the result to the
variable result.
f) Print “The product is” followed by the value of the integer variable result.

1.5. Using the statements you wrote in Exercise 2.4, write a complete program that calculates the product of
three numbers.
1.6. Write a program that determines if the input number is ODD or EVEN number.

ES 01A – Computer Fundamentals and Programming Page 73


Self-Review Exercises 3.

3.1. Write four different C statements that each add 1 to integer variable m.

3.2. Write a single C statement to accomplish each of the following:


a.) Assign the sum of x and y to z and increment the value of x by 1 after the calculation.
b.) Multiply the variable product by 2 using the *=operator.
c.) Multiply the variable product by 2 using the = and * operators.
d.) Test if the value of the variable count is greater than 10. If it is, print “Count is greater than 10.”
e.) Decrement the variable x by 1, then subtract it from the variable total.
f.) Add the variable x to the variable total, then decrement x by 1.
g.) Calculate the remainder after q is divided by divisor and assign the result to q. Write this statement two
different ways.
h.) Print the value 123.4567 with 2 digits of precision. What value is printed?
i.) Print the floating value 3.14159 with three digits to the right of the decimal point. What value is
printed?

3.3. Write a C statement to accomplish each of the following tasks.


a.) Define variables sum and x to be of type int.
b.) Initialize variable x to 1.
c.) Initialize variable sum to 0.
d.) Add variable x to variable sum and assign the result to variable sum.
e.) Print “The sum is: “ followed by the value of variable sum.

3.4. Combine the statements that you wrote in Exercise 3.3 into a program that calculates the sum of the
integers from 1 to 10. Use the while statement to loop through the calculation and increment statements.
The loop should terminate the value of x becomes 11.

3.5. Determine the values of variables product and x after the following calculation is performed. Assume that
product and x each have the value 5 when the statement begins executing.
product *= x++;

3.6. Write single C statements that


a) Input integer variable x with scanf.
b) Input integer variable y with scanf.
c) Initialize integer i to 1.
d) Initialize integer variable power to 1.
e) Multiply variable power by x and assign the result to power.
f) Increment variable i by 1.
g) Test I to see if it is less than or equal to y in the condition of a while statement.
h) Output integer variable power with printf.

3.7. Write a C program that uses the statements in Exercise 3.6 to calculate x raised to the y power. The program
should have a while repetition control statement.
3.8. Identify and correct the errors in each of the following:
a) while (c <= 5) {
product * = c;
++c;
b) scanf(“%.4f”, &value);
c) if (gender ==1)
printf(“Woman\n”);
else;
printf(“Man\n”);
3.9. What is wrong with the following while repetition statement (assume z has value 100), which is supposed to
calculate the sum of the integers from 100 down to 1:
while (z >= 0)
sum += z;

ES 01A – Computer Fundamentals and Programming Page 74


Self-Review Exercises 4.

4.1. Fill in the blanks in each of the following statements.


a.) The ____ statement, when executed in a repetition statement, causes the next iteration of the
loop to be performed immediately.
b.) The ____ statement, when executed in a repetition statement or a switch, causes immediate
exit from the statement.
c.) The ____ is used to test a particular variable or expression for each of the constant integral
values it may assume.
d.) ____ is a collection of variables of the same type that are referenced by a common name.

4.2. State whether the following are true or false. If the answer is false, explain why.
a.) The default case is required in the switch selection statement.
b.) The break statement is required in the default case of a switch election statement.
c.) The expression (x > y && a < b) is true if either x > y is true or a < b is true.
d.) The expression containing the || operator is true if either or both of its operands is true.
e.) The specific element in an array is accessed by an index.

4.3. Find the error in each of the following code segments and explain how to correct it.
a) x = 1;
while (x <= 10);
x++;
}
b) for (y = .1; y != 1.0; y += .1)
printf(“%f\n”, y);
c) switch (n) {
case 1:
printf(“The number is 1\n”);
case 2:
printf(“The number is 2|n”);
default:
printf(“The number is not 1 or 2\n”);
break:
}
d) The following code should print the values 1 to 10.
n = 1;
while (n < 10)
printf(“%d”, n++);

ES 01A – Computer Fundamentals and Programming Page 75

Potrebbero piacerti anche