You are on page 1of 30

Bells University of Technology, Ota.

COLICT
CSC 201: Computer Programming Methodologies

Lecture 1: Principles & practice of computer programming tools.


Programming methodologies deal with different methods of designing programs. This will teach
you how to program efficiently and outline the importance of structuring the programs, not only the
data pertaining to the solution but also the programs that operates on the data. In this class, you
would be restricted to the basics of programming in C.

Programming Concept
Software Development Life Cycle (SDLC). It is classified in five phases:
1. Defining the problem.
2. Designing the program (Problem analysis and logic design).
3. Coding the program.
4. Testing, debugging and formalizing the program.
5. Implementation and program maintenance. Program documentation is necessary for
program usage and maintenance.

1. Problem definition: this is the first step in computer problem-solving. The problem-solver
should understand the problem thoroughly in terms of requirements that is the input and
output operations to be performed.

2. Analysis: The given problem must be analysed before it is solved. This determines the data
items, their types and relationship. We should specify the operations (arithmetic & logical)
to be performed on them and check the suitability in terms of execution time. System
analysis also involves identifying infrastructure required to build the program, hardware,
software, personnel and consumables.

• Algorithms: it is a step-by-step finite sequence of instruction, to solve a well-defined


computational problem. It consists of English-like statements and each statement must be
precise and well-defined to perform a specific operation. When writing an algorithm, the
following notations are required – the name or title of the algorithm, the step number,
explanatory comments and termination.
• Characteristics of Algorithms
◦ Input: it may accept zero or more inputs.
◦ Output: it should produce at least one output (result).
◦ Definiteness: each instruction must be clear, well-defined and precise. There
should be not ambiguity.
◦ Finiteness: it should be a sequence of finite instructions. This means that
instructions must end after a fixed time not infinity.
◦ Effectiveness: this means that operations must be simple and carried out in a
finite time at one or more levels of complexity (time and space complexity – Big-
Oh notation etc). **Time complexity indicates how fast an algorithm runs and
space complexity refers to the amount of memory units required by the algorithm
in addition to the space needed for its input and output.

Example: An algorithm to compute the area of a circle


Step 1: Read radius
Step 2: [compute the are] //comment
Area = 3.142*radius*radius

1
Step 3: [print the area]
print 'Area of a circle= ', Area
Step 4: [end algorithm]
Stop.

Example: An algorithm to perform basic arithmetic operations such as addition, subtraction,


multiplication and division.
Step 1: [read the values of A and B]
Read A, B
Step 2: [compute the sum, difference, product and quotient]
sum = A+B
diff = A-B
prod = A*B
quot = A/B
Step 3: [print the contents of sum,diff,prod,quot]
print 'Sum of A and B= ', sum
print 'Difference of A and B= ', diff
print 'Product of A and B= ', prod
print 'Quotient of A and B= ', quot
Step 4: [end algorithm]
Stop.

• Pseudocode: It is neither an algorithm nor a program. It also consists of English-like


statements, which perform specific operations with no form of graphical representation. It is not
executable – cannot be compiled. It is defined for an algorithm.
◦ Example: Write a pseudocode to perform the basic arithmetic operations
Read n1, n2
sum = n1 + n2
diff = n1 – n2
prod= n1*n2
quot= n1/n2
print sum,diff,prod,quot
End

• Flowcharts: Flowcharts show the flow of logic involved in solving a problem. It is a


diagrammatic representation of an algorithm. They are also used during problem analysis and
logic design phase. Flowchart figure representation: Oval (Start & Stop), Parallelogram (Input
& Output), Rectangle (Processing), Diamond or Rhombus (Decision-making), Arrows
(Connections), Circle (Continuation), Hexagon (Repetition/looping).
◦ Example: Draw a flowchart to find the largest of three numbers.

2
More Algorithm and flowchart questions – refer to textbook.

• Input-Process-Output (IPO) Model


The three primary activities of a program are input, processing and output. Computer program
typically perform a three-step process of gathering inputs, performing some process on the
information gathered and then producing an output.
Input is information a program collects from the outside world; it can be sent to the program by the
user entering data from a keyboard or just using a mouse. It can also be gotten from disk files or
other connected hardware devices.

Process is the most important element of the system. The process accepts the inputs into the system
and performs some type of operation on it which transforms it into some other state. In the simplest
of terms, the process is at the heart of any system. It is involves storage retrieval and modification
of data, which is accomplished by hardware and software.The Programming process consists of
several steps, which include design, creation, testing and debugging activities.

In designing and creating a program, the following steps are recommended and show the
importance of planning. A good program always begins with planning.
1. Define what the program is to do.
2. Visualize the program running on the computer.
3. Use your design tools like flowcharts, to create a model of the program.
4. Check the model for logical errors.
5. Then, write the program source code.
6. Compile the source code.
7. Correct any errors found during compilation.
8. Link the program to executable file.
9. Run the program using test data for input.
10. Correct any more errors found while running the program.
11. Validate the results of the program.

Output is information that a program sends to the outside world. It can be alpha numeric words or
graphics displayed on a screen or a report sent to the printer or data stored in a file or information
sent to any device connected to the computer. It is the result of processing the input.

3
IPO Model

DATA and OUTPUT


INPUT PROCESSING

Steps to complete an IPO Model


• Read and understand the problem.
• Identify the outputs.
• Decide what data (the inputs) is required in order to get the required output.
• Determine how the inputs would be transformed.
This process or steps are dynamic which means you may need to continually return to previous
steps.
Examples:
1. Analysis for Celsius to Fahrenheit program. Construct an IPO chart:
Input: degrees in Celsius
Process: Fahrenheit = Celsius * 9/5 + 32
Output: degrees in Fahrenheit

2. Problem Statement: A student's final grade for a course is a weighted average of two tests, a
final exam and four projects. Each test is worth 15%, the final exam is worth 30% and the
projects are worth a total of 40% (10% each). Given a student's grades for all of these,
calculate the final score. Construct an IPO chart of the input(s), output(s) and process(es)
required to solve this problem.
Solution:
Input Process Output
Get result of test 1 Calculate final score Final score.
Get result of test 2 Final score =
Get result of final exam {(test 1 + test 2) * 15/100} +
Get result of project 1 (final exam score * 30/100) +
Get result of project 2 {(project 1 + project 2 +
Get result of project 3 project 3 + project 4) * 40/100}
Get result of project 4

3. Coding and Running the program


After the analysis phase, the computer needs a way to process all the data in a language it
understands. The computer does not know how to process algorithms or flowcharts or IPO models
but executes the program. The process of writing a program is called coding. Programs are written
using high level programming languages and fed to the computer.

The CPU is where all the processing takes place. The written program is executed (or ran) in the
CPU. Three steps are involved in this phase:
• Understand the instructions
• Store data and instructions
• Perform computations.

4
Once the programmer is done writing the program, it is ready for execution. Instructions stored in
the RAM (Random Access Memory) are fetched one by one by ALU (Arithmetic Logic Unit) to
perform the corresponding operations, then finally the processed data (results) are transferred to the
output devices.

The process of translating high level language (source code) program into machine language
requires an intermediary program called the translator. The complier and interpreter are two
translator programs used. The source code or program is translated (by a complier or interpreter)
into an object program.

Differences between a complier and an interpreter


Complier Interpreter
It takes the entire source code as input and It takes only one statement from the source code
translates it into machine language and executed at a time, translates it to machine language and
it. then executes it.
All errors that occur within the entire program Only errors that occur in each executed
are listed and displayed. statement are displayed.
Debugging is faster. Debugging is slower.
It requires more memory. Less memory is required.
Expensive Less expensive.

4. Debugging and Testing


The process of detecting and correcting errors in a program is known as debugging. Programmers
commit three types of errors:
• Syntax error – which occurs as a result of violation of the rules of programming language. It
is encountered during the compilation process. Example of syntax error is when you miss
out the semicolon (;) at the end of an assignment statement in your C program.
• Logical error – occurs during the coding process. It occurs as a result of wrong logical
thinking on the side of the programmer. The program runs but displays a wrong result. It is
difficulty to debug as the computer doesn't display it. So, tracing and running it with a
sample data is a way to eliminate this error.
• Run-time error – occurs as a result of ambiguous instructions: like running an infinite loop
in a program sequence, which causes no output or a data overflow or dividing by zero. It can
also occur due to device error, system software error, incorrect data input and so on. An error
message is displayed.

The process of executing the program to check for correctness of the output (result) of the problem
is called testing. Different sets of data are used to test the program. A technique used in software
testing called decision table.

Decision Tables: these tables are a good way to deal with inputs (sets of data). They provide a
systematic way of testing the program and exploring the effects of combination of different inputs.
It is used when there are multiple actions that should be taken under certain sets of condition and
many possible combinations of conditions to test. In practice, when the specification has many IF-
THEN-ELSE type conditions. Decision tables are made up of conditions, actions and rules. The
number of rules is calculated by 2n where n = number of conditions.

5
Example:
Let’s take an example scenario for an ATM where a decision table would be of use. A customer
requests a cash withdrawal. One of the business rules for the ATM is that the ATM machine pays
out the amount if the customer has sufficient funds in their account or if the customer has the credit
granted. Already, this simple example of a business rule is quite complicated to describe in text. A
decision table makes the same requirements clearer to understand:
Conditions Rule 1 Rule 2 Rule 3 Rule 4
Withdrawal T F T F
amount<=Balance
Credit granted F T T F
Actions
Withdrawal T T T F
Granted

Example:
If you are a new customer and you want to open a credit card account then there are three
conditions first you will get a 15% discount on all your purchases today, second if you are an
existing customer and you hold a loyalty card, you get a 10% discount and third if you have a
coupon, you can get 20% off today (but it can’t be used with the ‘new customer’ discount).
Discount amounts are added, if applicable.

5. Implementation, Documentation and Maintenance


Good programming practice involves making an explanatory note on the program or program
segment you have written. The explanatory note is a comment that explains how the program works
and how to interact with it. This helps other programmers to understand the program, easily
maintain (modify and improve) it even when the original written isn't present. Two types of
documentation: Internal (within the program) and External (Message to the user to respond to the
program requirements).

Assignment 1:
1. What are the major differences between machine level language, Assembly language and
High level language.
2. List and discuss briefly on three types each of Interpreters and Compliers
3. Write an algorithm, construct a flowchart and an IPO chart for a program to output a
student's grade from five courses based on the letter grades:
A: 70 - 100
B: 60 – 69
C: 50 – 59
D: 45 – 49
F: 0 – 44

6
Lecture 2: C – Fundamentals

C has emerged as the most widely used programming language. Its features has made it possible to
use the language for system programming like the development of compliers, operating systems,
interpreters and so on.

Brief History of C
C language was developed by Dennis Ritchie and Ken Thompson at the Bell Laboratory in MIT.
The idea of C language was derived as an improved version of the B language and BCPL ( Basic
Combining Programming Language).

Advantages/Features of C
– It has power and flexibility.
– Portability- it can run on several systems with little modifications.
– Efficiency- it doesn't require as much memory as others and it runs fast.
– Programmer oriented- has flexible control structure that gives access to hardware and
enables manipulation of individual bits of memory.

Characteristics of C
– It is a general purpose programming language.
– It is a structured programming language.
– It helps in the development of system softwares like operating systems, compliers etc.
– It has a rich set of operators.
– It provides compact representation for expression.
– It allows manipulation of internal processor registers.
– It doesn't have a rigid format, that is, any number of statements can be written in a single
line.
– It supports a rich set of data types.
– It has less number of reserved words.
– It has the ability to extend itself by adding functions to its library.

Application of C
C is used to develop system and application softwares.
System software: operating system, compilers, editors, linkers, interpreters, assemblers, loaders.
Application software: Graphics packages, word processors, office automation tools, database
systems, spreadsheets, office automation tools, scientific and engineering applications.

Every programming language has its own set of characters to form the lexical elements. The
character set of C programming language can be grouped into three categories:
– Alphabets (upper and lower case alphabets)
– Digits (0-9)
– Special characters (, . ; “ ' = + _ & % # and so on)

The basic and smallest units of a C program are called C tokens. There are six types of tokens in C:
1. Keywords: these are reserved words that have standard pre-defined meanings. They are
only used for special actions or intended purposes. They cannot be used as a programmer's
defined identifier. All keywords are written in lower case letters. Examples of keywords
used in C: int , void, if , else, return, for, do, long, goto, char, while etc.

7
2. Identifiers:
3. Strings:
4. Operators:
5. Special symbols:
6. Constants: these are identifiers that do not change their value during the execution of the
program. The value associated with the storage will always be constant. There four basic
types of constants –
1. Integer constant- has only numbers 0 to 9. e.g 0, 111, 235
2. floating point constant- is a numeric constant with a decimal point or an exponent or
both. e.g 0.5, 1.56 e+9
3. character constant- is a single character which can be stored in memory. It is denoted by
single quotes. e.g 'A'
4. string constant- is a group of characters represented by double quotes. e.g “College”

Other elements of C include: datatypes- this defines a set of values that a variable can store along
with a set of operations that can be performed on the variable.There are basically two types of data
types: fundamental (int, char, float, double etc) and derived (short int, long int etc) data types.

Basic Structure of a C program


Different programming languages have their own format of coding. The basic components of a C
program are:
1. Preprocessor statements:
2. Main ():
3. A pair of curly braces {}:
4. Declarations:
5. Statements:
6. User defined functions:

/*Example number 1*/


#include<stdio.h>
main() {
Printf(“Welcome to C programming \n ”);
return 0;
}
Note: Every program statements must end with a semi colon (;). All programming statements must
lie within curly braces. Comment statements doesn’t compile by the computer.
Comments (/*........*/ or //.........//): In C, /* is called opening comment mark and */ is closing
comment mark. The C compiler ignores everything between the opening comment mark and closing
comment mark. The comment is used for program documentation.
Preprocessor Statements (#include directory):
In C, #include is a preprocessor directive that tells the C preprocessor to look for a file and place the
file in the location where #include indicates. The preprocessor includes the header file such as
stdio.h, conio.h, string.h etc. Other examples of preprocessor directives are:
#define – to define a macro(macro substitution is replacing an identifier of a C program by a
constant or symbolic constatnt)
#undef – to undefine a macro

8
Header Files
These files are placed at the header portion of your program before main(). The standard header
files in C have the .h extension.The header files are used to provide the necessary information in
support of the various library functions. Table below shows some header files and the library
function they are declared for:
Header File Declaration For
stdio.h Input/output functions
math.h Mathematical functions
conio.h Console input/output functions
graphics.h Graphic functions
string.h String manipulation functions
time.h Time computing functions
Angular <> braces: In C, the angular bracket asks the C preprocessor to look for a header file in
directory other than the current one. If we want to let the C preprocessor look into current directory
first for header file before it starts to work, we can use double quotes to surround the name of the
header file. Normally, the header file are saved in a sub directory called include.
Main ( ) function: Every C program must have one and only one main functions. The main
function can be put anywhere but the execution of a program starts with main function. The main
function starts and end with curly braces {}.
Declarations: this is a part of the program where all variables, arrays, functions etc used in the C
program are declared and they may be initialized with their basic data types.
Statements: they are instructions given to the computer to perform specific operations. They may
be I/O statements, arithmetic or control statements.
User defined functions: there are subprograms that contain a set of instructions to specific tasks for
the user. They are written by the user of a program in a context where the usual assumption is built
in the program or environment. They may be written before or after the main ( ) function.
Printf functions and new line character: The printf function is used to print the character string.
The new line character which is usually sufficient at the end of the message, tells the system to
move the cursor to the beginning of next line.
Return statements: all function in C can return value. The main function itself returns an integer
value. So, return 0 indicates that 0 is returned from main function and the program is terminated
normally. We can return values other than 0 to tell the system that there is an error.
Compiling a C program means translating it into machine language. The program to be compiled
must be typed in using an editor. An editor is a program that allows the programmer to type in the
program and modify it. C compilers are available with or without editors.The environment where
you find the compiler, the editor, debugging tools, linking facilities, tracing and testing tools is
called Integrated Development Environment (IDE).

9
Lecture 3: Format Specifiers, Escape Sequence & Operators in C

Format Specifiers: they are character strings with the percent sign (%) followed by a character.
They specify the type of data that is being processed. They are also refer to a conversion specifiers.
When a data is being output or input, it must be specified with the identifier (variable) and their
format specifier. Some examples of format specifiers are:

Format specifier Meaning


%c Read a single character
%d Read an integer
%f Read a floating-point number
%h Read a short-int number
%s Read a string

Escape Sequence: these are special characters denoted by a backslash (\) and a character after it. It
is called escape sequence because it causes an escape from the normal way character are being
represented or interpreted. Some examples of escape sequence are:

Escape sequence Meaning


\n New line
\t Tab horizontal
\b Move the character to the left, one space
\r Return or enter key
\\ Backslash
\' Single quote

Operators and Expressions


An expression is a sequence of operators and operands that computes a value. An operator in C is a
symbol that tells the computer to perform mathematical or logical manipulation on data.Operators
are used to perform basic arithmetic operations, comparison, logical manipulation of bits and so
on.The data items that operators act upon are called operands. In C, operators may operate on one or
two operands. C operators are classified into three categories:

1. Unary operators: they act upon only one operand. Examples are Logical NOT operator and
bitwise complementation.
2. Binary operators: they act upon two or more operands and can be classified into four
categories; Arithmetic, logical relational and bitwise operators.
Example: X x Y = (X * Y)/Z
Z
(2x + 1) (3y + 2) = [(2 * x) + 1
3. Ternary operators

10
Lecture 4: Precedence and associativity of all C operators.
All C operators have some form of precedence (that is, an order or rank). C specifies the precedence
of operators in the evaluation of an expression with the highest precedence first. The associativity of
operators defines the order in which an operator evaluates its operands. Note that the use of
parentheses raises the precedence of the operator within parentheses. Here is a summary of C
operators with their precedence and associativity in the given table:

Operator Category Operator Precedence Associativity


Parentheses, braces ( ), { } 1 Left to Right
Unary operators - - , ++, !, & 2 Right to Left
Multiplicative *, /, % 3 Left to Right
operators
Additive operators +, - 4 Left to Right
Shift operators <<, >> 5 Left to Right
Relational operators <, >, <=, >= 6 Left to Right
Equality operators !, =, = = 7 Left to Right
Bitwise operators ^, | 8 Left to Right
Logical operators &&, || 9 Left to Right
Conditional operators ?, : 10 Right to Left
Assignment operators +=, -=, /=, <<=, >>= 11 Right to Left
Comma operator , 12 Left to Right

Shorthand Assignment Operators


C provides a compact way of writing assignment statements in an expression. It is basically
associated with all arithmetic and bitwise operators. The general form of a shorthand assignment in
C is as follows:
variable operator = expression;
Example:
/* A program that illustrates the use of some shorthand assignment operators */
#include<stdio.h>
main ( )
{
int x = 3, y = 4, z = 1;
x += y;
y -= x;
z *= x;
printf (“%d \n”, x);
printf (“%d \n”, y);
printf (“%d \n”, z);
}
Output:
7
-3
7
Data Type Conversion
In some applications, we may want to change the data type of our variables. To do that, we change
the nature of the data stored in the variable. It is also know as Type Casting.

11
The general form is: (datatype) variable

Example:
int k = 2;
j = 1/k;

Type casting: j = 1/(float)k;

Please refer the students back to their previous classwork, using arithmetic operators. Let
them use type casting with arithmetic operators. You can also give more examples.

Mathematical Functions
C provides a large number of library functions which perform specific operations. Mathematical
functions are part of this library functions. Mathematical functions are defined in C using the header
file (math.h). So, you must include the math.h file if you intend to use mathematical functions
within your program. Some of these functions are stated in the table below:

Functions Return Type


cos(variable) double
sin(variable) double
sqrt(variable) double
tan(variable) double
log(variable) double
pow(variable1, variable2) double

Example:
/* A program that illustrates the use of some mathematical functions*/
#include<stdio.h>
#include<math.h>
main( )
{
float x, y, sq, sin_value, cos_value, tan_value;
x = 4.0;
y = 30.0;
sq = sqrt (x);
y = 30.0 * (3.142/180.0); /* convert to radians */
sin_value = sin (y);
cos_value = cos (y);
tan_value = tan (y);
printf(“Square root of x = %f \n”, sq);
printf(“Sine value of y = %f \n”, sin_value);
printf(“Cosine value of y = %f \n”, cos_value);
printf(“Tangent value of y = %f \n”, tan_value);
}
Output:
Square root of x = 2.00000
Sine value of y = 0.5000059
Cosine value of y = 0.865991
Tangent value of y = 0.577441

12
Input- Output Statements
C is a functional programming language and so it has no exclusive built-in statements to perform
basic input-output operations. The standard input-output library is used in performing input-output
operations. The header file containing these library functions is called stdio.h. Some standard input-
output functions are as follows:

Input Statement Output Statement


Formatted scanf( ) printf( )
Unformatted getchar( ) putchar( )
gets( ) puts( )

Formatted I/O statements enable the user to specify the type of data and the way in which it should
be read in or written out while unformatted I/O statements do not specify.

Entering Input Data: the scanf ( )Function


Input data can be entered from a standard input device (like your keyboard) by means of the C
library function scanf. This function can be used to enter any combination of numeric values, single
characters and strings. The function returns the number of data items that have been entered
successfully. In general terms, the scanf function is written as:

scanf(“control 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 data items. (Actually the arguments
represent pointers that indicate the addresses of the data items within the computer’s memory.
The control string consists of the individual group of characters called format specifiers, with one
character group for each input data item. Within the control string, multiple character groups can be
contiguous, or they can be separated by whitespace characters (ie, white spaces, tabs or newline
characters).
The arguments to a scanf function are written as variables or arrays whose types match the
corresponding character groups in the control string. Each variable name must be preceded by an
ampersand (&). However, character array names do not begin with an ampersand. The actual
values of the arguments must correspond to the arguments in the scanf function in number, type and
order.
If two or more data items are entered, they must be separated by whitespace characters. The data
items may continue onto two or more lines, since the newline character is considered to be a
whitespace character and can therefore separate consecutive data items.

Example using scanf function:

scanf(“%d %c %f”, &x, &y, &z);

In reading numbers using scanf function, you can specify the field width. The consecutive non-
whitespace characters that define a data item collectively define a field. To limit the number of such
characters for a data item, an unsigned integer indicating the field width precedes the conversion
character. The input data may contain fewer characters than the specified field width. Extra
characters will be ignored.

Example: If a and b are two integer variables and the following statement is being used to read their

13
values:

scanf( "%3d %3d", &a, &b);

If the input data is: 1 4 then a will be assigned 1 and b 4.


If the input data is 123 456 then a=123 and b=456.
If the input is 1234567, then a=123 and b=456. 7 is ignored.
If the input is 123 4 56 (space inserted by a typing mistake), then a=123 and b=4. This is because
the space acts as a data item separator.

Writing Output Data: the printf ( )Function


The printf function is used to output any combination of numerical values, single characters and
strings. The general form of the printf function is:

printf(“control string”, arg1, arg2, … , argN)

The control string consists of one or more of the following items: Characters that are simply printed
as they are; ie, messages or prompts, format specifiers and escape sequences. The control string
indicates the type of arguments that follow. The arguments arg1, arg2, … , argN are the variables
whose values are formatted and printed according to the specifications of the control string. The
arguments must match in number, order and type with the format specifications.

Example using printf function:


printf(“Programming is fun”);
printf(“%d”, number);

In printf function, you can also specify field width. A minimum field width can be specified by
preceding the conversion character with an unsigned integer. If the number of characters in the
corresponding data item is less than the specified field width, the data item will be preceded by
enough leading blanks to fill the specified field. If the number of characters exceeds the field width,
additional space will be allocated to the data item, so that the entire data item can be displayed. This
is just the opposite of the scanf function where a maximum field width is specified.

For example:
printf(“%6d”, x);

If the value of x is 678612, then the output would be 678612.


If the value of x is 678, then the output would be three white spaces then 678

printf(“%-5d”, x);
The output would be 678 with three white spaces in memory.

printf(“%05d”, x);
Then the output would be 00678 in memory.

14
Lecture 5: Control Statements
Normally, statements in a program are executed in the order in which they appear (sequential
order). But in some programs, it is necessary to select a set of statements from several alternatives
or skip certain statements or repeat a set of statements for a number of time. In such conditions we
make use of control statements.

Control statements enable us to specify the flow of program control; ie, the order in which the
instructions in a program must be executed. They make it possible to make decisions, to perform
tasks repeatedly or to jump from one section of code to another.
There are four types of control statements in C:

• Decision making statements


• Selection statements
• Iteration statements
• Jump statements

Decision Making Statements:


• The if and if-else Statements
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 test (ie, whether the outcome is true or false).

If the condition specified in the if statement evaluates to true, the statements inside the if-block are
executed and then the control gets transferred to the statement immediately after the if-block. Even
if the condition is false and no else-block is present, control gets transferred to the statement
immediately after the if-block.

The else part is required only if a certain sequence of instructions needs to be executed if the
condition evaluates to false.It is important to note that the condition is always specified in
parentheses and that it is a good practice to enclose the statements in the if block or in the else-
block in braces, whether it is a single statement or a compound statement.

Syntax:
if (condition)
{
statements;
}
AND
if (condition)
{
statements;
}
else
{
statements;
}
Examples:
1.Write a program that accepts a number and prints if it is an odd number.
#include <stdio.h>
main( ){
int numb;
printf (“Enter the number \n”);

15
scanf(“%d”, &numb);
if ((numb%2) != 0);
printf (“%d, is an odd number \n”,numb);
}

2.Write a program to check whether the enter number is positive or negative.


#include<stdio.h>
main( ){

int a;

printf("n Enter a number:");

scanf("%d", &a);

if(a>0){

printf( "n The number %d is positive.",a);


}
else{

printf("n The number %d is negative.",a);


}
return 0;

• Nested if and if-else Statements


It is also possible to embed or to nest if-else statements one within the other. Nesting is useful in
situations where one of several different courses of action need to be selected. It is also called the if-
else ladder. During the execution of a nested if-else statement, as soon as a condition is
encountered which evaluates to true, the statements associated with that particular if-block will be
executed and the remainder of the nested if-else statements will be bypassed. If neither of the
conditions are true, either the last else-block is executed or if the else-block is absent, the control
gets transferred to the next instruction present immediately after the else-if ladder.

Syntax:
if(condition1)
{
// statement(s);
}
else if(condition2)
{
//statement(s);
}
.
else if (conditionN)
{
//statement(s);
}
else
{
//statement(s);
}

16
Example:
Write a program that finds the greatest of the three numbers. (You can also modify your program to accept
the three numbers as input).
#include<stdio.h>
main( ){
int a, b,c;
a=6,b= 5, c=10;
if(a>b)
{
if(b>c)
{
printf("nGreatest is: " , a);
}
else if(c>a)
{
printf("nGreatest is: ", c);
}
}
else if(b>c) //outermost if-else block
{
printf("nGreatest is: " , b);
}
else
{
printf( "nGreatest is: " , c);
}
return 0;
}

Selection Statement:
• The Switch-case Statements
A switch statement is used for multiple way selections that will branch into different code segments
based on the value of a variable or expression. This expression or variable must be of integer data
type.

The value of the “expression” is either generated during program execution or read in as user input.
The case whose value is the same as that of the expression is selected and executed. The optional
default label is used to specify the code segment to be executed when the value of the expression
does not match with any of the case values.The break statement is present at the end of every case.
If it were not so, the execution would continue on into the code segment of the next case without
even checking the case value

Syntax:
switch (expression)
{
case value1:
code segment1;
break;
case value2:
code segment2;
break;
.
.
.

17
case valueN:
code segmentN;
break;
case default:
default code segment;
}

Example:
Write a program to print the day of the week.

#include<stdio.h>
main( )
{
int day;
printf("nEnter the number of the day:");
scanf("%d",&day);

switch(day)
{
case 1:
printf("Sunday");
break;
case 2:
printf("Monday");
break;
case 3:
printf("Tuesday");
break;
case 4:
printf("Wednesday");
break;
case 5:
printf("Thursday");
break;
case 6:
printf("Friday");
break;
case 7:
printf("Saturday");
break;
default:
printf("Invalid choice");
}
return 0;

18
Lecture 6: Iterative or Repetitive Statements:
They are used to execute a particular set of instructions repeatedly until a particular condition is met
or for a fixed number of iterations. The repetitive mechanism is also referred to as looping. A loop
in a program essentially consists of 2 parts; one part is called the body of the loop and the other part
is the control statement. The control statement performs a logical test where the result is either true
or false. If the result of this logical test is true, then the statement contained in the body of the loop
are executed otherwise the loop is terminated.

There are three types of repetitive or iterative statements:


1. While Statements
2. Do-While Statements
3. For Statements

• While Statements
The while statement executes a block of statements repeatedly while a particular condition or
logical expression is true.

Syntax:
while (logical expression or condition)
{
statement;
}

Example:
Write a program that finds the sum of the first n integers.
/*A program that finds the sum of the first n integers*/
#include<stdio.h>
main ( )
{
int num, counter, sum = 0;
printf(“Enter the value of integers you want: \n”);
scanf(“%d”, &num);
counter = 1;
while (counter <= num)
{
sum+ = counter;
counter++;
}
printf(“Sum = %4d \n”, sum);
}
Output:
Enter the value of integers you want:
10
Sum = 55

• Do-while Statements
The do-while statement evaluates the condition at the end of the loop after executing the block of
statements at least once. If the condition is true the loop continues, else it terminates after the first
iteration. It executes the set of statements repeatedly until the logical test result is false.

19
Syntax:

do
{
statements;
}
while (logical expression or condition);

Example:
Write a program that prints the sum of all odd integers between 1 to 50
/*A program to find the sum of all odd integers between 1 to 50*/
#include<stdio.h>
main ( )
{
int oddnum = 1; int sum = 0;
do
{
sum+= oddnum;
oddnum+=2;
}
while (oddnum<=50);
printf(“Sum = %4d \n”, sum);
}
Output:
Sum = 625

• For Statements
The For statement or For loop repeatedly executes the set of instructions that comprise the body of
the for loop until a particular condition is satisfied. The statement is used when the programmer
knows how many knows how many times a set of statements are to be executed.

Syntax:

for (expression1; expression2; expression3)


{
statement;
}

Expression1 represents initialization (it initializes the loop index before the loop begins).
Expression2 represents conditional expression or termination that tests whether the loop index
reached the fixed value. ( that is whether to continue or not).
Expression3 represents increment or decrement (modifying the loop index after every iteration).

Example:
Write a program that finds the sum of the first 50 natural numbers.
/* A program to find the sum of the first 50 natural numbers*/
#include<stdio.h>
main ( )
{
int num, sum = 0;
for (num = 1; num <= 50; num++)
sum+ = num;

20
printf(“Sum = %5d \n”, sum);
}
Output:
Sum = 1275

• Nested For Statements


Nested For statements are used in a case where many data items are to be processed against a set of
elements repeatedly.

Syntax:

for (expression11; expression12; expression13)


{
for (expression21; expression22; expression23)
{
statement1;
statement2;
}/*Inner Loop*/
}/*Outer Loop*/
The statement1 & 2 are repeatedly executed the number of times specified by the maximum limit of
the inner loop, for each index value of the outer loop.

Example 1:
Write a program that displays a number pattern- it prints the number 5, five times; number 4, four
times; number 3, three times; number 2, two times and number 1, once.
/*A program to print a number pattern*/
#include <stdio.h>
main( )
{
int a, b, num = 5;
printf(“Number Pattern \n”);
for (a = num; a >= 1; a--)
{
for (b = 1; b <= a; b++)
{
printf(“%d”, a);
}
printf(“\n”);
num –;
}
}
Output:
55555
4444
333
22
1

21
Example 2:
Write a program that prints the following pattern
*
**
***
****
*****
/*A program to print a pattern*/
#include<stdio.h>
main ( )
{
int x, y;
char ch = '*';
for (x = 0; x < 5; x++)
{
for (y = 0; y<=x; y++)
{
printf(“%c”, ch);
}
printf(“\n”)
}
}

Jump Statements:
They are rarely used for application level programming because they make the program confusing,
less readable and complex. They make testing and debugging difficult because tracing the control of
the program is not easy. Type of Jump statements are: Goto Statements, Break, Continue
Statements.

• Break Statements
It is used to terminate the execution of a loop or statement and exit from the particular switch label
(refer to Switch-case statements).

• Go to Statements
These are unconditional control statements that transfer control from one point to another in a C
program. The go to statement is a branching statement and it requires a label.

Syntax:
goto Label_name:
…..........
…..........
Label_name: statements;

Example:
Write a C program that displays the eligibility to vote of a person 18 years and above.
/* A program to check voting eligibility*/
#include<stdio.h>
main ( )
{
int age;
Vote:

22
printf(“You are eligible to vote \n”);

No_Vote:
printf(“You are not eligible to vote \n”);

printf(“Please enter your age: \n”);


scanf(“%d”, &age);
if (age >= 18)
{
goto Vote;
else
goto No_Vote;
return 0;
}

• Continue Statements
These statements are used for skipping a part of a loop in a C program. The control does not come
out of the loop, instead it skips the remaining statements within the body of that loop and transfers
to the beginning of the loop.

Example: A program illustrating the use of continue statements.


#include <stdio.h>
main ()
{
/* local variable definition */
int a = 10;

/* do loop execution */
do
{
if( a = = 15)
{
/* skip the iteration */
a = a + 1;
continue;
}
printf("value of a: %d\n", a);
a++;

}while( a < 20 );

return 0;
}
Output:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

23
Lecture 7: Structures and Preprocessors
A structure is a meaningful collection of data items of different types under a unique name. It allows
the programmer to create and manipulate a set of different types of data items. The keyword struct
is used to declare a structure.

The general form of structure definition and declaration is as follows:

struct name
{
data type1 data item1;
data type2 data item2;
data type3 data item3;
}

Structures could also be embedded in one another that is a structure within a structure.

Example 1: A program that illustrates the use of structures in C. A program that accepts the
information of a C book such as book number, author, publisher, and price and then displays it.

#include <stdio.h>
#include <string.h>

main ( )
{
struct C_Book
{
int book_name;
char author [20];
char publisher [20];
float price;
};
struct C_Book bookinfo;
printf(“Enter the book number: \n”);
scanf(“%d”, &bookinfo.book_num);
printf(“Enter the author of the book: \n”);
scanf(“%s”, &bookinfo.author);
printf(“Enter the publisher of the book: \n”);
scanf(“%s”, &bookinfo.publisher);
printf(“Enter the price of the book: \n”);
scanf(“%f”, &bookinfo.price);
printf(“......................................... \n”);
printf(“C_Book \n”);
printf(“......................................... \n”);

printf(“Book Number: %d \n”, bookinfo.book_num);


printf(“Author: %s \n”, bookinfo.author);
printf(“Publisher: %s \n”, bookinfo.publisher);
printf(“Book Price: N.%6.2f \n”, bookinfo.price);
printf(“......................................... \n”);

return 0;
}

24
Example 2:
#include <stdio.h>
#include <string.h>

struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};

main( )
{
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */

/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;

/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;

/* print Book1 info */


printf( "Book 1 title : %s\n", Book1.title);
printf( "Book 1 author : %s\n", Book1.author);
printf( "Book 1 subject : %s\n", Book1.subject);
printf( "Book 1 book_id : %d\n", Book1.book_id);

/* print Book2 info */


printf( "Book 2 title : %s\n", Book2.title);
printf( "Book 2 author : %s\n", Book2.author);
printf( "Book 2 subject : %s\n", Book2.subject);
printf( "Book 2 book_id : %d\n", Book2.book_id);

return 0;
}

Preprocessor Directives
Preprocessor directives are placed before the main ( ) function and they are no semicolons at the
end of such statements. They are three types of preprocessor directives:
1. Macro substitution directives
2. File Inclusion directives
3. Conditional compilation directives
Macro substitution is a process of replacing an identifier of a C program by a constant or symbolic
constant. The directive #define is a macro definition statement.
Syntax:
#define identifier constant or expression or symbolic constant

25
Example: Write a program to calculate the area of circle using the directive #define

#include <stdio.h>
#define PI 3.142
main ( )
{
float radius, area;
printf(“Enter the radius:\n”);
scanf(“%f”, &radius);

area = PI * radius * radius;


printf(“The area of a circle is: %f\n”, area);
}

File Inclusion directives allow programmers insert external files containing functions or macro
definitions into the current program. The avoids rewriting of those functions over again. The
directive #include is used for file inclusion.
Syntax:
#include <filename> or #include “filename”

Example: Write a program to calculate the cube of a number illustrating the use of file inclusion
directives.

Since the function for finding cubes is not available in the standard library, you can create a seperate
program file for cube function.

cube (int x)
{
return ( x * x * x);
}
Save this function in a file called cube.C

Using file inclusion, we can insert cube.C in our program below:

#include <stdio.h>
#include “cube.C”
main ( )
{
int num, cube_value;
printf(“Enter the number: \n”);
scanf(“%d”, &num);
cube_value = cube(num);
printf(“The cube of the number is: %d\n”, cube_value);
}

Conditional compilation directives are used to select alternate segments of a code in a C program.
The #ifdef, #else, #endif and so on are examples of conditional compilation directives.

26
Lecture 8: C- Functions and Strings
A function is a group of statements that together perform a task. Every C program has at least one
function, which is main( ) function. Functions are generally classified into standard and user-
defined functions. The standard functions are also called library functions or built-in functions
(examples are sqrt ( ), abs ( ), log ( ), pow ( ) etc). The C standard library also provides numerous
built-in functions that your program can call like function strcat() to concatenate two strings,
function memcpy() to copy one memory location to another location and many more functions.
User-defined functions are written by the user (programmers) themselves.

You can divide up your lengthy programs into separate functions (a number of smaller unit or
modules), this is referred to as modularization. How you divide up your code among different
functions is up to you, but logically the division usually is so each function performs a specific task.

• Function Definition and Declaration

A function definition provides the actual body of the function while a function declaration tells the
compiler about a function's name, return type, and parameters. It means specifying the function as a
variable depending upon the return value. A function is known with various names like a method or
a sub-routine or a procedure, etc.

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

return_type function_name( parameter list )


{
/* body of the function*/
variable declarations;
Statement 1;
Statement 2;

return (value_computed);
}
A function definition in C programming language consists of a function header and a function body.
Here are all the parts of a function:

• Return Type: A function may return a value. The return_type is the data type of the value
the function returns. Some functions perform the desired operations without returning a
value. In this case, the return_type is the keyword void.
• Function Name: This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
• Parameters: A parameter is like a placeholder. When a function is invoked, you pass a
value to the parameter. This value is referred to as actual parameter or argument. The
parameter list refers to the type, order, and number of the parameters of a function.
Parameters are optional; that is, a function may contain no parameters.
• Function Body: The function body contains a collection of statements that define what the
function does.
• Return (value_computed): The value to be returned to the calling function after
processing.

27
Example: A function that returns the maximum of two numbers.

#include <stdio.h>

/* Function Declaration */

int max(int num1, int num2);

/* can also be written */


/* int max (num1, num2) */
/* int num1, num2; */

main ( )
{
/* local variable definition */
int a = 100;
int b = 200;
int result1;

/* calling a function to get max value */


result1 = max(a, b);

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

return 0;
}

/*Function Definition */
/* A function returning the max between two numbers */

int max(int num1, int num2)


{
/* local variable declaration */
int result2;

if (num1 > num2)


result2 = num1;
else
result2 = num2;

return result2;
}

Classwork: Define a function called addsums( ) that computes the sum of numbers and call the
function within your program.

• Function Arguments and Parameters


Arguments and parameters are variables used by a function. They are written within parentheses
followed by the name of the function. Parameters are not the accepted values, they receive values
from the calling function. Functions are categorized into the following:
1. Functions with no arguments and no return value: here the called function does not receive
any data from the calling function. And, it does not return any data back to the calling
function.

28
2. Functions with arguments but no return value: here the called function receives data from
the calling function. The arguments and parameters should match in number, data type and
order. The called function does not return any value back to the calling function, instead it
prints the data in its scope only.
3. Functions with no arguments but return value: here the called function does not receive data
from the calling function, it manages its local data to carry out the specified task. Then it
returns the computed data to the calling function.

C-Strings
Strings are represented by an array of characters. The end of a string is marked with a special
character called the null character.

Lecture 9: C- Arrays
An array is defined as an ordered list of homogeneous data elements. These elements may be of
type int, float, char or double. All these elements are stored in consecutive memory locations (in the
RAM).The array can store a fixed-size sequential collection of elements of the same type. It is often
more useful to think of an array as a collection of variables of the same type.

Instead of declaring individual variables,such as number0,number1,...,and number99,you declare


one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to
represent individual variables.

An array is described by a single name or an identifier. Each individual data item in the array is
referenced by a subscript ( or an index)enclosed in a pair of square brackets. This index indicates
the position of the particular data item in the array.

Classification of Arrays
Arrays can be classified into:
1. One dimensional array
2. Multi-dimensional array (two dimensional, three dimensional........n-dimensional array)

Declaration of Arrays
Arrays must be declared with the specific datatype before they can appear in a program. The size of
the array must also be specified to allow the compiler to decide on how much memory is to be
reserved for that array.

One – dimensional array


It is a linear list of fixed number of data items of the same type. It is similar to a row or column
matrix. All the data items are accessed using the same name and a single subscript (the subscript
ranges from zero to one less than the maximum size of the array). To declare a single or one -
dimensional array in C, a programmer specifies the type of the elements and the number of
elements required by an array as follows:

data_type arrayName [ arraySize ];

The arrayName is any identifier name given to the array, arraySize must be an integer constant

29
greater than zero and type can be any valid C data type.
Example: int list [10]; char name [20]; float abc [5];

Example:

References:
• Fundamentals of C by Surabhi Saxena: http://www.sitepoint.com/an-introduction-to-c/
• Fundamentals of Computer and Programming in C by S.K Jha ( Katson Student Edition).
• The C Programming Tutorial by http://www.tutorialspoint.com/cprogramming/index.htm
• Computer Concepts and C Programming by Dr Nalini N, Professor and Head, Department
of CSE, NMIT, Bangalore (For VTU Learning).

30

You might also like