Professional Documents
Culture Documents
Csc201 CPM
Csc201 CPM
COLICT
CSC 201: Computer Programming Methodologies
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.
1
Step 3: [print the area]
print 'Area of a circle= ', Area
Step 4: [end algorithm]
Stop.
2
More Algorithm and flowchart questions – refer to textbook.
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
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
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.
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.
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.
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:
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:
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:
11
The general form is: (datatype) variable
Example:
int k = 2;
j = 1/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:
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:
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.
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.
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:
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.
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);
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:
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);
}
int a;
scanf("%d", &a);
if(a>0){
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.
• 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:
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
Syntax:
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”);
• 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.
/* 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.
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”);
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;
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);
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
#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.
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.
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 */
main ( )
{
/* local variable definition */
int a = 100;
int b = 200;
int result1;
return 0;
}
/*Function Definition */
/* A function returning the max between two numbers */
return result2;
}
Classwork: Define a function called addsums( ) that computes the sum of numbers and call the
function within your program.
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.
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.
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