C Programming Practical Guide
C Programming Practical Guide
Preamble...............................................................................................................................................................3
Introduction..........................................................................................................................................................4
What is computer programming?......................................................................................................................4
What is a programming language?....................................................................................................................4
What is C programming?...................................................................................................................................4
Brief history of the C programming language....................................................................................................5
Why Use C?.......................................................................................................................................................5
Basic Structure of a C program..........................................................................................................................6
.............................................................................................................................................................................. 6
A Simple C Program...........................................................................................................................................8
Using comments..............................................................................................................................................10
Constants, variables, data types, specifiers and comments.................................................................................11
Constants.........................................................................................................................................................11
Variables..........................................................................................................................................................11
Variables vs constants......................................................................................................................................12
Signed and unsigned variables........................................................................................................................12
Using variables in calculations.........................................................................................................................12
Reading and printing variables........................................................................................................................13
Variable naming conventions..........................................................................................................................14
The #define statement....................................................................................................................................15
Specifiers.........................................................................................................................................................17
Comments.......................................................................................................................................................17
What Comments Are Used For ...................................................................................................................18
Conditional Statements.......................................................................................................................................21
The if statement..............................................................................................................................................21
if-else statement..............................................................................................................................................23
if-else-if............................................................................................................................................................26
The case switch statement..............................................................................................................................27
The Switch-Case statement explained.........................................................................................................28
Looping................................................................................................................................................................30
1|Page
do while loop...................................................................................................................................................36
............................................................................................................................................................................ 37
Arrays.................................................................................................................................................................. 38
Declaration of arrays:......................................................................................................................................38
Initialization of arrays: ....................................................................................................................................40
Multi dimensional Arrays: ...............................................................................................................................41
Elements of multi dimension arrays: ..........................................................................................................42
Initialization of multidimensional arrays: ....................................................................................................42
Functions or procedures......................................................................................................................................44
Structure of a Function....................................................................................................................................44
Function Header..........................................................................................................................................44
Function Body..............................................................................................................................................45
Function Prototypes........................................................................................................................................45
Types of functions...........................................................................................................................................46
Nesting of functions: ......................................................................................................................................46
Recursion: .......................................................................................................................................................47
Calculating the factorial value using recursion............................................................................................47
File management in C..........................................................................................................................................50
File operation functions in C: ..........................................................................................................................50
Defining and opening a file: ............................................................................................................................51
Closing a file: ..................................................................................................................................................52
The getw and putw functions: ........................................................................................................................53
The fprintf & fscanf functions: ........................................................................................................................54
Random access to files: ..................................................................................................................................55
Refs...................................................................................................................................................................... 56
2|Page
3|Page
Preamble
Welcome to the basic C programming practical tutorial. These lessons are part of the Introduction to
Computer Science course (SCS1101) dealing with the practical programming section of the course.
Please ensure you code, run and debug all the programs covered in this tutorial as this will help you
understand the concepts of the programming language chosen.
For this tutorial you should to have Turbo C (TC) running. Copy the TC folder onto your C:/ drive…
To access the compiler, open your c drive then open the TC folder, go to BIN then click on TC
NB: All assignments are to be handed in on time to avoid marks being deducted. A zero mark
will be recorded for assignments not submitted.
4|Page
Introduction
What is computer programming?
A programming language is usually split into the two components of syntax (form) and semantics
(meaning).
What is C programming?
C is a computer programming language. That means that you can use C to create lists of instructions
for a computer to follow. C is one of thousands of programming languages currently in use. C has been
around for several decades and has won widespread acceptance because it gives programmers
maximum control and efficiency. C is an easy language to learn. It is a bit more cryptic in its style than
some other languages, but you get beyond that fairly quickly.
5|Page
C is what is called a compiled language. This means that once you write your C program, you must
run it through a C compiler to turn your program into an executable that the computer can run
(execute). The C program is the human-readable form, while the executable that comes out of the
compiler is the machine-readable and executable form. What this means is that to write and run a C
program, you must have access to a C compiler.
The C programming language was developed at Bell Labs during the early 1970's. Quite unpredictably
it derived from a computer language named B and from an earlier language BCPL. Initially designed
as a system programming language under UNIX, it expanded to have wide usage on many different
systems. The earlier versions of C became known as K&R C after the authors of an earlier book, "The
C Programming Language" by Kernighan and Ritchie. As the language further developed and
standardized, a version know as ANSI (American National Standards Institute) C became dominant.
Although it is no longer the language of choice for most new development, it still is used for some
system and network programming as well as for embedded systems and mostly it is said as the
"Mother of all programming languages". More importantly, there is still a tremendous amount of
legacy software still coded in this language and this software is still actively maintained.
Why Use C?
In today's world of computer programming, there are many high-level languages to choose from, such
as Pascal, BASIC, and Java. But C stands apart from all these languages. This is due to its many
desirable qualities. It is a robust language whose rich set of built-in functions and operators can be
used to write any complex logic program. The C language compiler combines the capabilities of a low
level language with the features of a high level language. Therefore the language is suitable for writing
both system software as well as business packages & other software. You will see many compilers
available in the market written in C.
• Programs written in c are very efficient and fast. This is due to its variety of data types and
powerful operators. It is many times faster than BASIC. This helps developers in saving their
valuable time.
• C is a powerful and flexible language which helps system developers to deliver various
complex tasks with ease. C is used for diverse projects as operating systems, word processors,
graphics, spreadsheets, and even compilers for other languages.
• C is popular among professional programmers for programming, as a result, a wide variety of
C compilers and helpful accessories are available.
• C is highly portable language. This means that a C program written for one computer system
(an IBM PC, for example) can be run on another system (a DEC VAX system, perhaps) with
little or no modification. Portability is enhanced by the ANSI standard for C, the set of rules for
C compilers.
• C’s other striking feature is its ability to extend itself. A C program is basically a collection of
various functions supported by C library (also known as header files). We can also add our own
6|Page
functions to the C library. These functions can be reused in other applications or programs by
passing pieces of information to the functions, you can create useful, reusable code.
• Writing C program with user-defined functions makes program more simple and easy to
understand. Breaking a problem in terms of functions makes program debugging, maintenance
and testing easier.
Documentations - The documentation section consist of a set of comment lines giving the name of the
program, the other name and other details, which the programmer would like to use later.
Preprocessor Statements - The preprocessor statements begin with # symbol and are also called the
preprocessor directives. These statements instruct the compiler to include C preprocessors such as
header files and symbolic constants before compiling the C program. Some of the preprocessor
statements are listed below.
7|Page
Global Declarations - These variables are declared before the main ( ) function. These global
variables can be accessed by all the user defined functions including main ( ) function.
The main ( ) function - Each and every C program should contain only one main ( ) function. The C
program execution starts with main ( ) function. No C program is executed without the main function.
The main ( ) function should be written in small (lowercase) letters and it should not be terminated by
semicolon. Main ( ) executes user defined program statements, library functions and user defined
functions and all these statements should be enclosed within left and right braces.
Braces - Every C program should have a pair of curly braces ({, }). The left brace indicates the
beginning of the main ( ) function and the right brace indicates the end of the main ( ) function. These
braces can also be used to indicate the user-defined functions beginning and ending. These two braces
can also be used in compound statements.
Local Declarations - The variable declaration is a part of C program and all the variables that are used
in the main ( ) function should be declared in the local declarations section. These variables are called
local variables. Not only variables, we can also declare arrays, functions, pointers etc. These variables
can also be initialized with basic data types.
For example
Code:
Main ( )
{
int sum = 0;
int x;
float y;
}
Here, the variable sum is declared as integer variable and it is initialized to zero. Other variables declared as int
and float and these variables inside any function are called local variables.
Program statements - These statements are building blocks of a program. They represent instructions
to the computer to perform a specific task (operations). An instruction may contain an input-output
statement, arithmetic statements, control statements, simple assignment statements and any other
statements and it also includes comments that are enclosed within /* and */ . The comment statements
8|Page
are not compiled and executed and each executable statement should be terminated with semicolon.
User defined functions - These are subprograms. Generally, a subprogram is a function written by the
user and is called a user-defined function. These functions perform user specific tasks and also contain
a set of program statements. They may be written before or after a main () function and called within
the main () function. This is optional to the programmer.
• easy to read
• easy to modify
• consistent in format
• self documenting
A Simple C Program
#include <stdio.h>
#include <conio.h>
int main()
{
clrscr();
printf("Let's learn C programming.\n");
getch();
return 0;
}
This little program outputs the phrase "Let's learn C programming" on the screen.
#include <stdio.h>
#include <conio.h>
These lines are called the preprocessors. Commands, like printf, are contained in these preprocessors,
not the compiler itself. Just remember you need the stdio.h, or standard input & output header file, to
be able to use printf, scanf and such. The conio.h, or console input and output header file is needed for
the clrscr or clear screen and getch or get character commands in this case.
9|Page
int main()
This where the actual program begins and ends. int is what is called the return value which will be
explained in a while. main is the name of the point where the program starts and the brackets are there
for a reason that you will learn in the future but they have to be there.
{}
The 2 curly brackets are used to group all the commands together so it is known that the commands
belong to main. These curly brackets are used very often in C to group things together.
clrscr();
Clears the screen.
10 | P a g e
Another command similar to printf is scanf which allows for the user's input.
getch();
This allows you to time to read the ouput on the screen. Without it the program would just exit quickly
and you wouldn't be able to see the output.
return 0;
The int in int main() is short for integer which is another word for number. We need to use the return
command to return the value 0 to the operating system to tell it that there were no errors while the
program was running. Notice that it is a command so it also has to have a semi-colon after it.
One thing you should notice are the semicolons (;) at the end of each statement except for main().
These semicolons indicate where the statement ends. A statement is one complete command just like
printf("Let's learn C programming.");. A statement can have many statements within itself and is
contained in within the curly brace ({}) just like main().
Using comments
Comments are a way of explaining what a program does. They are put after // or between /* */.
Comments are ignored by the compiler and are used by you and other people to understand your code.
You should always put a comment at the top of a program that tells you what the program does
because one day if you come back and look at a program you might not be able to understand what it
does but the comment will tell you. You can also use comments in between your code to explain a
piece of code that is very complex. Here is an example of how to comment the Hello World program:
#include<stdio.h>
int main()
{
printf("Let’s learn C programming \n"); //prints " Let’s learn C programming "
return 0;
}
11 | P a g e
Constants
A constant can be defined as a quantity that does not change during the execution of a program. For
example, the value of Pi in mathematics is always 3.14.
Types of Constants
Integer Constant - An integer constant must have at least one digit and should not have
decimal point. It could either be positive or negative.
Real Constant - A real constant must have at least one digit and must have a decimal point.
Character Constant - A character constant should be only one character and must be enclosed
in single quotes e.g. ‘A, ‘B’, etc.
Variables
Variables, just like in Algebra are the letters representing a number. For the computer, variables are
little storage places inside the memory. In C there are four types of variables: integer, float point,
double floating point and character.
The first one is the integer or counting numbers or numbers without decimals. The second is floating
point which is the fractional numbers or numbers with decimals. Double is just like float except it can
handle bigger numbers and has more precision, it could hold more decimals places. The last one is
characters, these are the letters and numbers.
To be able to use the variables they must be first declared. We must tell the program that they exist,
and create a location for them in the memory.
12 | P a g e
Variables vs constants
The difference between variables and constants is that variables can change their value at any time but
constants can never change their value. Constants can be useful for items such as Pi or the charge on
an electron. Using constants can stop you from changing the value of an item by mistake.
The difference between signed and unsigned variables is that signed variables can be either be
negative or positive but unsigned variables can only be positive. By using an unsigned variable you
can increase the maximum positive range. When you declare a variable in the normal way it is
automatically a signed variable. To declare an unsigned variable you just put the word unsigned before
your variable declaration or signed for a signed variable although there is no reason to declare a
variable as signed since they already are.
int main()
{
unsigned int a;
signed int b;
return 0;
}
int main()
{
int a;
char b;
a = 3;
13 | P a g e
b = 'H';
return 0;
}
There are a few different operators that can be used when performing calculations which are listed in
the following table:
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
Modulus(Remainder of
%
integer division)
To perform a calculation you need to have a variable to put the answer into. You can also use both
variables and normal numbers in calculations.
int main()
{
int a,b;
a = 5;
b = a + 3;
a = a - 3;
return 0;
}
You can read a variable from the keyboard with the scanf command and print a variable with the printf
command.
#include<stdio.h>
int main()
{
int a;
scanf("%d",&a);
a = a * 2;
printf("The answer is %d",a);
return 0;
}
14 | P a g e
The %d is for reading or printing integer values and there are others as shown in the following table:
%d or %i int
%c char
%f float
%lf double
%s string
• Variables must begin with a character or underscore, and may be followed by any combination
of characters, underscores, or the digits 0 - 9.
• Names with leading and trailing underscores are reserved for system purposes and should not
be used for any user-created names. Most systems use them for names that the user should not
have to know. If you must have your own private identifiers, begin them with a letter or two
identifying the package to which they belong.
Enum constants are Capitalized or in all CAPS
Function, typedef, and variable names, as well as struct, union, and enum tag names should be
in lower case.
Many macro "functions" are in all CAPS. Some macros (such as getchar and putchar) are in
lower case since they may also exist as functions. Lower-case macro names are only acceptable
if the macros behave like a function call, that is, they evaluate their parameters exactly once
and do not assign values to named parameters. Sometimes it is impossible to write a macro that
behaves like a function even though the arguments are evaluated exactly once.
Avoid names that differ only in case, like foo and Foo. Similarly, avoid foobar and foo_bar.
The potential for confusion is considerable.
Similarly, avoid names that look like each other. On many terminals and printers, 'l', '1' and 'I'
look quite similar. A variable named 'l' is particularly bad because it looks so much like the
constant '1'.
In general, global names (including enums) should have a common prefix identifying the module that
they belong with. Globals may alternatively be grouped in a global structure. Typedeffed names often
have "_t" appended to their name.
Avoid names that might conflict with various standard library names. Some systems will include more
library code than you want. Also, your program may be extended someday.
15 | P a g e
You should ensure that you use meaningful names for your variables. The reasons for this are,
• meaningful names for variables are self documenting (see what they do at a glance)
• they are easier to understand
• there is no correlation with the amount of space used in the .EXE file
• makes programs easier to read
Get into the habit of declaring variables using lowercase characters. Remember that C is case
sensitive, so even though the two variables listed below have the same name, they are considered
different variables in C.
sum
Sum
game_over = TRUE;
while( list_pointer != NULL )
................
Note that preprocessor statements begin with a # symbol, and are NOT terminated by a semi-colon.
Traditionally, preprocessor statements are listed at the beginning of the source file.
Preprocessor statements are handled by the compiler (or preprocessor) before the program is actually
compiled. All # statements are processed first, and the symbols (like TRUE) which occur in the C
program are replaced by their value (like 1). Once this substitution has taken place by the
preprocessor, the program is then compiled.
Pi
W
37 as follows:
#define Pi 3.14
#define letter 'W'
#define smallint 37
Lets now examine a few examples of using these symbolic constants in our programs. Consider the
following program which defines a constant called TAX_RATE.
#include <stdio.h>
main(){
float balance;
float tax;
balance = 72.10;
tax = balance * TAX_RATE;
printf("The tax on %.2f is %.2f\n", balance, tax );
}
The pre-processor first replaces all symbolic constants before the program is compiled, so after
preprocessing the file (and before its compiled), it now looks like,
#include <stdio.h>
main(){
float balance;
float tax;
balance = 72.10;
tax = balance * 0.10;
printf("The tax on %.2f is %.2f\n", balance, tax );
}
17 | P a g e
The whole point of using #define in your programs is to make them easier to read and modify.
Considering the above programs as examples, what changes would you need to make if the
TAX_RATE was changed to 20%?
Obviously, the answer is once, where the #define statement which declares the symbolic constant and
its value occurs. You would change it to read
#define TAX_RATE = 0.20
Without the use of symbolic constants, you would hard code the value 0.20 in your program, and this
might occur several times (or tens of times). This would make changes difficult, because you would
need to search and replace every occurrence in the program. However, as the programs get larger,
what would happen if you actually used the value 0.20 in a calculation that had nothing to do
with the TAX_RATE!
Specifiers
Now we need to know specifiers. Specifiers are used when we want to input or output values of
variables using printf and scanf. A specifier specifies the type of variable being used, and is always a
percent sign (%) followed by a letter. For integers the specifier is %d (percent decimal), for float and
double %f (percent float), for characters %c (percent character) and for strings %s (percent string).
Comments
The addition of comments inside programs is desirable. These may be added to C programs by
Note that the/* opens the comment field and*/ closes the comment field. Comments may span
In the above example, the first occurrence of*/ closes the comment statement for the entire line,
meaning that the text wrong is interpreted as a C statement or variable, and in this example, generates
an error.
18 | P a g e
• copyrighting
#include <stdio.h>
#include <conio.h>
main()
{
clrscr();
sum=a+b;
getch();
return(0);
}
19 | P a g e
sum=a+b;
Adds the two numbers together and store the answer in the variable sum. The basic mathematical
operators are plus(+), minus(-), multiply(*), divide(/) and modulus(%). What's modulus you ask, it
returns the remainder. You should know what the rest of them do. When performing division using
integers the decimals are cut off.
Practice 1: Create a program that prompts for your name and three numbers,
compute for the sum and average and outputs your name, the sum and average.
[10 marks]
20 | P a g e
Conditional Statements
Conditional statements control the sequence of statement execution, depending on the value of an
integer expression (condition). They work with the following operators:
== is equal to
!= not equal to
Complex logical operators: can combine expressions to get complex logical expressions
&& and
|| or
The if statement
The basic conditional-testing statement in C is the if statement. It executes if the condition is true. The
syntax of if is
if (expression) statement
21 | P a g e
if ( statement is TRUE )
Execute this line of code
if ( 5 < 10 )
printf( "Five is less than ten" );
Start
Condition No
Yes
Perform
Task
Exit
Example:
#include <stdio.h>
#include<conio.h>
22 | P a g e
main()
int a,b;
scanf(“%d %d”,&a,&b);
if(a>b)
OUTPUT:
a is greater than b
if-else statement
Sometimes when the condition in an if statement evaluates to false, it would be nicer to execute some
code instead of only the code executed when the statement evaluates to true. The "else" statement
effectively says that whatever code after it (whether a single line or code between brackets) is executed
if the if statement is FALSE.
if ( TRUE ) {
/* Execute these statements if TRUE */
}
else {
/* Execute these statements if FALSE */
}
statement(s);
)
Flow chart for else-if statement
Start
No
Condition
Yes
Yes
Perform Perform
Exit
Example:
#include <stdio.h>
#include<conio.h>
main()
{
int a,b;
if(a>b)
printf(“\n a is greater than b”);
else
printf(“\n b is greater than a”);
}
OUTPUT:
24 | P a g e
b is greater than a
25 | P a g e
if-else-if
Another use of else is when there are multiple conditional statements that may all evaluate to true, yet
you want only one if statement's body to execute. You can use an "else if" statement following an if
statement and its body; that way, if the first statement is true, the "else if" will be ignored, but if the if
statement is false, it will then check the condition for the else if statement. If the if statement was true
the else statement will not be checked. It is possible to use numerous else if statements to ensure that
only one block of code is executed.
In other words, the if-else-if executes IF condition is [Link] condition is FLASE it checks ELSE IF
part .ELSE IF is true then execute ELSE IF PART. This is also false it goes to ELSE part.
Example:
#include <stdio.h>
#include<conio.h>
main()
{
int a,b;
printf(“Enter a,b values, separated by enter:”);
scanf(“%d %d”,&a,&b);
if(a>b)
printf(“\n a is greater than b”);
else if(b>a)
printf(“\n b is greater than a”);
else
printf(“a is equal to b”);
}
26 | P a g e
OUTPUT:
a is equal to b
The switch statement is a form of flow control, often used to replace repetitive if-else blocks. It takes a
single integral value and performs a series of comparisons against programmer-supplied values. As
soon as one of the values matches, execution of supplied code begins. This is useful in instances like
menus where there are several choices that can be made. Case Switch cannot work with ranges like in
our last homework.
#include <stdio.h>
#include <conio.h>
char choice;
void main() {
clrscr();
printf("What is the weather like today?");
printf("\n\ta) Sunny and hot");
printf("\n\tb) Wet and windy");
printf("\n\tc) Wet and cold");
printf("\n\td) Windy\n: ");
choice=getch();
switch (choice) {
case 'a': printf("\nGet an umbrella and shades."); break;
case 'b': printf("\nGet a raincoat."); break;
case 'c': printf("\nGet a coat and an umbrella."); break;
case 'd': printf("\nStay indoors."); break;
default: printf("Invalid choice! Select choice between a and d?");
}
getch();
}
27 | P a g e
In the "switch" command each 'case' acts like a simple label. A label determines a point in the program
which execution must continue from. The switch statement will choose one of the 'case' sections. After
entering a case portion, execution continues until it reaches a break statement.
"break" statements have vital role in switch structures. If you remove these statements, program
execution will continue to next case sections and all commands until the end of "switch" block will be
executed. This is because each 'case' acts exactly as a label. When program execution is transferred to
a case section it will continue running to the end of switch block. The only way to end execution of
statements in the switch block is using break statements at the end of each section.
We can replace the last ‘case’ break statement with the termination command “exit(0)”.
The "default" section will be executed if none of the case sections match switch comparison.
The parameter inside switch statement must be of type int (or char).
Using a variable in case sections is not allowed. This means that you are not allowed to use a statement
like below in your switch block.
case i: something;
break;
A variable named choice of type char is declared for the program. This variable is going to be used
when the user makes their choice when the program is running. The first printf statement displays the
text “What is the weather like today” to the user. The menu will then be displayed and it will comprise
of the text in the next four printf statements. \n is the newline character; it will display text that comes
after it in a new line. \t is a new tab character which will display the text that comes after it in a new
tab, i.e., there will be a certain number of spaces left to the left of the text, sort of like a margin. After
all has been said and done, the other printf statemenst will display the following text:
d) Windy
28 | P a g e
The statement: choice=getch(); will accept any value of type char (since our variable choice is
declared to be of type char) as input from the user. The getch() function gets a character from the user.
The statement: switch (choice)is the beginning of our switch statement. Our variable choice will
hold the character that the user input as they made their choice. The program will then jump to the case
statements to see if the user’s choice matches any of the programmed choices. If it does, the statement
with the value that matches the user’s choice is displayed. For example, if the user had selected “d” for
their weather choice, the statement “Stay indoors” will be displayed as a response to the user’s choice.
If any letter that is out of the range of the given choices is selected, the default statement will be
displayed.
29 | P a g e
Looping
If you want to do the same thing many times you can use a loop. In C, there are three different kinds of
loops. These are the “for” loop, “while” loop, and the “do while” loop. They come in handy in
certain conditions. Right now we'll focus on the “for” loop.
The “for” loop is good for looping a definite amount of times. That is you already know how many
times to loop. More importantly “for” loop can count. You can start from any number, end in any
number, and count in multiples for example, counting in odd or even numbers.
Example program:
#include<stdio.h>
#include<conio.h>
int i;
void main() {
clrscr();
printf("Prints my college three times.\n");
for (i=0; i<3; i++) printf("National University of Science and Technology\n");
printf("\nCounts from 1 to ten.\n");
for (i=1; i<=10; i++) printf("%d ", i);
30 | P a g e
Multiple statements.
0 C programming is fun
1 C programming is fun
2 C programming is fun
You can put a loop inside a loop. This is called a nested loop. You can nest as many loops as you can
but keep it to a minimum as it could get confusing especially when trying to debug your program.
Here's an example:
#include<stdio.h>
#include<conio.h>
#define max 5
void main() {
31 | P a g e
clrscr();
printf("Prints the value of i and j as it goes through the loop.\n");
for (int i=0; i<max; i++) for (int j=0; j<max; j++) printf("(%d, %d)\n",i,j);
getch();
}
#include<stdio.h>
#include<conio.h>
#define max 1024
void main() {
clrscr();
printf("Every loop doubles the value until it is %d.\n", max);
for (int i=1; i<=max; i*=2) printf("%d ", i);
getch();
}
32 | P a g e
B. Create a program that allows the user to input a number and find its factorial. Use float instead
of int since you will be getting large number.
#include<stdio.h>
#include<conio.h>
void main() {
clrscr();
printf("Enter a number to find the factorial.");
scanf("%f", &num);
for (int i=num; i>0; i--) fact*=i;
printf("The factorial of %.0f is %.0f.", num, fact);
getch();
}
33 | P a g e
Create a program that uses a nested for loop to simulate counting in 4-bit binary.
#include<stdio.h>
#include<conio.h>
#define max 2
int a,b,c,d;
void main() {
clrscr();
printf("Counts in binary.\n");
for (a=0; a<max; a++)
for (b=0; b<max; b++)
for (c=0; c<max; c++)
for (d=0; d<max; d++)
printf("%d%d%d%d\n",a,b,c,d);
getch();
}
Counts in binary.
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111
Practice 2: For each of the programs A to C above, explain the code in your
own understanding. [30 marks]
34 | P a g e
For loop is great for loops that you know how many times to loop. The others are good for if you don't
know or don't need to know how many the program goes to the loop for example when a user want to
continue or to quit when they are prompted. There is no need for a counter.
While loop
The simplest of all looping structures in C is the while statement. The general format of the while
statement is:
Here the given test condition is evaluated and if the condition is true then the body of the loop is
executed. After the execution of the body, the test condition is once again evaluated and if it is true, the
body is executed once again. This process of repeated execution of the body continues until the test
condition finally becomes false and the control is transferred out of the loop. On exit, the program
continues with the statements immediately after the body of the loop. The body of the loop may have
one or more statements. The braces are needed only if the body contained two or more statements
Example program for generating ‘N’ Natural numbers using while loop:
In the above program the looping concept is used to generate n natural numbers. Here n and i are
declared as integer variables and i is initialized to value zero. A message is given to the user to enter
the natural number till where he wants to generate the numbers. The entered number is read and stored
by the scanf statement. The while loop then checks whether the value of i is less than n i.e., the user
entered number if it is true then the control enters the loop body and prints the value of i using the
35 | P a g e
printf statement and increments the value of I to the next natural number this process repeats till the
value of i becomes equal to or greater than the number given by the user.
do while loop
The do while loop is also a kind of loop, which is similar to the while loop in contrast to while loop,
the do while loop tests at the bottom of the loop after executing the body of the loop. Since the body of
the loop is executed first and then the loop condition is checked we can be assured that the body of the
loop is executed at least once.
Do
{
statement;
}
while(expression);
Here the statement is executed, then expression is evaluated. If the condition expression is true then
the body is executed again and this process continues till the conditional expression becomes false.
When the expression becomes false the loop terminates.
To realize the usefulness of the do while construct consider the following problem: The user must be
prompted to press Y or N. In reality the user can press any key other than y or n. IN such case the
message must be shown again and the user should be allowed to enter one of the two keys, clearly this
is a loop construct. Also it has to be executed at least once. The following program illustrates the
solution.
36 | P a g e
37 | P a g e
Arrays
In this part of the tutorial you will learn about C Programming - Arrays - Declaration of arrays,
Initialization of arrays, Multi dimensional Arrays, Elements of multi dimension arrays and
Initialization of multidimensional arrays.
The C language provides a capability that enables the user to define a set of ordered data items known
as an array.
Suppose we had a set of grades that we wished to read into the computer and suppose we wished to
perform some operations on these grades, we will quickly realize that we cannot perform such an
operation until each and every grade has been entered since it would be quite a tedious task to declare
each and every student grade as a variable especially since there may be a very large number.
In C we can define a variable called grades, which represents not a single value of grade but a entire
set of grades. Each element of the set can then be referenced by means of a number called as index
number or subscript.
Declaration of arrays:
Like any other variable arrays must be declared before they are used. The general form of declaration
is:
type variable-name[50];
The type specifies the type of the elements that will be contained in the array, such as int float or char
and the size indicates the maximum number of elements that can be stored inside the array for
example:
float height[50];
Declares height to be an array containing 50 real elements of type float. Any subscripts 0 to 49 are
valid. In C the array elements index or subscript begins with number zero. So height [0] refers to the
first element of the array. (For this reason, it is easier to think of it as referring to element number zero,
rather than as referring to the first element).
An individual array element can be used anywhere like a normal variable with a statement such as
G = grade [50];
The statement assigns the value stored in the 50th index of the array to the variable g.
More generally if I is declared to be an integer variable, then the statement g=grades [I];
38 | P a g e
Will take the value contained in the element number I of the grades array to assign it to g. so if I were
equal to 7 when the above statement is executed, then the value of grades [7] would get assigned to g.
A value stored into an element in the array simply by specifying the array element on the left hand side
of the equals sign. In the statement
grades [100]=95;
The value 95 is stored into the element number 100 of the grades array.
The ability to represent a collection of related data items by a single array enables us to develop
concise and efficient programs. For example we can very easily sequence through the elements in the
array by varying the value of the variable that is used as a subscript into the array. So the for loop
will sequence through the first 100 elements of the array grades (elements 0 to 99) and will add the
values of each grade into sum. When the for loop is finished, the variable sum will then contain the
total of first 100 values of the grades array (Assuming sum were set to zero before the loop was
entered)
In addition to integer constants, integer valued expressions can also be inside the brackets to reference
a particular element of the array. So if low and high were defined as integer variables, then the
statement
Just as variables arrays must also be declared before they are used. The declaration of an array
involves the type of the element that will be contained in the array such as int, float, char as well as
maximum number of elements that will be stored inside the array. The C system needs this latter
information in order to determine how much memory space to reserve for the particular array.
The declaration int values[10]; would reserve enough space for an array called values that could hold
up to 10 integers. Refer to the below given picture to conceptualize the reserved storage space.
values[0]
values[1]
39 | P a g e
values[2]
values[3]
values[4]
values[5]
values[6]
values[7]
values[8]
values[9]
Initialization of arrays:
We can initialize the elements in the array in the same way as the ordinary variables when they are
declared. The general form of initialization off arrays is:
The values in the list are separated by commas, for example the statement
int number[3]={0,0,0};
40 | P a g e
Will declare the array size as a array of size 3 and will assign zero to each element if the number of
values in the list is less than the number of elements, then only that many elements are initialized. The
remaining elements will be set to zero automatically.
In the declaration of an array the size may be omitted, in such cases the compiler allocates enough
space for all initialized elements. For example the statement
int counter[]={1,1,1,1};
will declare the array to contain four elements with initial values 1. This approach works fine as long
as we initialize every element in the array.
Often there is a need to store and manipulate two dimensional data structure such as matrices & tables.
Here the array has two subscripts. One subscript denotes the row & the other the column.
The declaration of two dimension arrays is as follows:
41 | P a g e
data_type array_name[row_size][column_size];
int m[10][20]
A 2 dimensional array marks [4][3] is shown below figure. The first element is given by marks [0][0]
contains 35.5 & second element is marks [0][1] and contains 40.5 and so on.
Like the one dimension arrays, 2 dimension arrays may be initialized by following their declaration
with a list of initial values enclosed in braces
Example:
int table[2][3]={0,0,0,1,1,1};
initializes the elements of first row to zero and second row to 1. The initialization is done row by row.
The above statement can be equivalently written as
int table[2][3]={{0,0,0},{1,1,1}}
By surrounding the elements of each row by braces, C allows arrays of three or more dimensions. The
compiler determines the maximum number of dimension. The general form of a multidimensional
array declaration is:
42 | P a g e
date_type array_name[s1][s2][s3]…..[sn];
int survey[3][5][12];
float table[5][4][5][3];
Survey is a 3 dimensional array declared to contain 180 integer elements. Similarly table is a
four dimensional array containing 300 elements of floating point type.
/* example program to add two matrices & store the results in the
3rd matrix */
#include< stdio.h >
#include< conio.h >
void main()
{
int a[10][10],b[10][10],c[10][10],i,j,m,n,p,q;
clrscr();
printf(“enter the order of the matrixn”);
scanf(“%d%d”,&p,&q);
if(m==p && n==q)
{
printf(“matrix can be addedn”);
printf(“enter the elements of the matrix a”);
for(i=0;i < m;i++)
for(j=0;j < n;j++)
scanf(“%d”,&a[i][j]);
printf(“enter the elements of the matrix b”);
for(i=0;i < p;i++)
for(j=0;j < q;j++)
scanf(“%d”,&b[i][j]);
printf(“the sum of the matrix a and b is”);
for(i=0;i < m;i++)
for(j=0;j < n;j++)
c[i][j]=a[i][j]+b[i][j];
for(i=0;i < m;i++)
{
for(j=0;j < n;j++)
printf(“%dt”,&a[i][j]);
printf(“n”);
}
}
43 | P a g e
Functions or procedures
A function is a block of code that has a name and it has a property that it is reusable i.e. it can be
executed from as many different points in a C Program as required.
A function groups a number of program statements into a unit and gives it a name. This unit can be
invoked from other parts of a program. A computer program cannot handle all the tasks by itself.
Instead its requests other program like entities – called functions in C – to get its tasks done. A
function is a self contained block of statements that perform a coherent task of same kind
The name of the function is unique in a C Program and is Global. It means that a function can be
accessed from any location within a C Program. We pass information to the function called, using
arguments specified when the function is called. And the function either returns some value to the
point it was called from or returns nothing.
We can divide a long C program into small blocks which can perform a certain task. A function is a
self contained block of statements that perform a coherent task of same kind.
Structure of a Function
There are two main parts of the function, the function header and the function body.
Function Header
44 | P a g e
Function Body
Whatever is written within { } in the above example is the body of the function.
Function Prototypes
The prototype of a function provides the basic information about a function which tells the compiler
that the function is used correctly or not. It contains the same information as the function header
contains. The prototype of the function in the above example would be like
The only difference between the header and the prototype is the semicolon (;) there must be a
semicolon at the end of the prototype.
#include<stdio.h>
#include<conio.h>
void input() {
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);}
void main()
{
clrscr();
input();
output();
getch();
}
In the program above there are two functions namely input() and output() defined by the programmer.
The input() function allows the user to input data while the output() function is used to display the
processed information from the raw data input by the user. The functions are first defined and are then
called into action by the main function. The order of calling the functions is of utmost importance…try
calling the output() function first and see what will happen.
Notice how the main function is at the bottom and it calls the input and output function above. The
output function calls the sum function.
45 | P a g e
Types of functions
There are five types of functions and these are:
Nesting of functions:
C permits nesting of functions freely. There is no limit how deeply functions can be nested. Suppose a
function a can call function b and function b can call function c and so on. Consider the following
program:
main()
{
int a,b,c;
float ratio();
scanf(“%d%d%d”,&a,&b,&c);
printf(“%fn”,ratio(a,b,c));
}
float ratio(x,y,z)
int x,y,z;
{
if(difference(y,z))
return(x/y-z));
else
return(0,0);
}
difference(p,q)
{
int p,q;
{
if(p!=q)
return(1);
else
return(0);
}
the above program calculates the ratio a/b-c; and prints the result. We have the following three
functions:
46 | P a g e
main()
ratio()
difference()
main reads the value of a,b,c and calls the function ratio to calculate the value a/b-c) this ratio cannot
be evaluated if(b-c) is zero. Therefore ratio calls another function difference to test whether the
difference(b-c) is zero or not.
Recursion:
Recursive function is a function that calls itself. When a function calls another function and that
second function calls the third function then this kind of a function is called nesting of functions. But a
recursive function is the function that calls itself repeatedly.
A simple example:
main()
{
printf(“this is an example of recursive function”);
main();
}
when this program is executed. The line is printed reapeatedly and indefinitely. We might have to
abruptly terminate the execution.
3. A recursive function must have recursive conditions, terminating conditions, and recursive
expressions.
Factorial of n = n(n-1)(n-2)……1.
Example :
Factiorial of 5 = 5x4x3x2x1
=120
47 | P a g e
#include<stdio.h>
#include<conio.h>
int factorial(int);
int f;
if(i==1)
return 1;
else
f = i* factorial (i-1);
return f;
void main()
int x;
clrscr();
scanf("%d",&x);
getch();
48 | P a g e
Explanation of code: Spaces to be considered as lines…So from line no. 6 – 14 is a user defined
recursive function “factorial” that calculates factorial of any given number. This function accepts
integer type argument/parameter and return integer value.
In line no. 9 we are checking that whether value of i is equal to 1 or not; i is an integer variable which
contains value passed from main function i.e. value of integer variable x. If user enters 1 then the
factorial of 1 will be 1. If user enters any value greater than 1 like 5 then it will execute statement in
line no. 12 to calculate factorial of 5. This line is extremely important because in this line we
implemented recursion logic.
Let’s see how line no. 12 exactly works. Suppose value of i=5, since i is not equal to 1, the statement:
f = i* factorial (i-1);
f = 5* factorial (5-1);
will be evaluated. As you can see this statement again calls factorial function with value i-1 which will
return value:
4*factorial(4-1);
This recursive calling continues until value of i is equal to 1 and when i is equal to 1 it returns 1 and
execution of this function stops. We can review the series of recursive call as follow:
f = 5* factorial (5-1);
f = 5*4*3*2*1;
f = 120;
49 | P a g e
File management in C
In this part of the tutorial you will learn about C Programming - File management in C, File operation
functions in C, Defining and opening a file, Closing a file, The getw and putw functions, The fprintf &
fscanf functions, Random access to files and fseek function.
C supports a number of functions that have the ability to perform basic file operations, which include:
[Link] a file
2. Opening a file
[Link] from a file
[Link] data into a file
[Link] a file
Real life situations involve large volume of data and in such cases, the console oriented I/O
operations pose two major problems
It becomes cumbersome and time consuming to handle large volumes of data through
terminals.
The entire data is lost when either the program is terminated or computer is turned off therefore
it is necessary to have more flexible approach where data can be stored on the disks and read
whenever necessary, without destroying the data. This method employs the concept of files to store
data.
If we want to store data in a file into the secondary memory, we must specify certain things about the
file to the operating system. They include the fielname, data structure, purpose.
FILE *fp;
fp=fopen(“filename”,”mode”);
The first statement declares the variable fp as a pointer to the data type FILE. As stated earlier, File is a
structure that is defined in the I/O Library. The second statement opens the file named filename and
assigns an identifier to the FILE type pointer fp. This pointer, which contains all the information about
the file, is subsequently used as a communication link between the system and the program.
The second statement also specifies the purpose of opening the file. The mode does this job.
51 | P a g e
In these statements the p1 and p2 are created and assigned to open the files data and results
respectively the file data is opened for reading and result is opened for writing. In case the results file
already exists, its contents are deleted and the files are opened as a new file. If data file does not exist,
an error will occur.
Closing a file:
The input output library supports the function to close a file; it is in the following format.
fclose(file_pointer);
A file must be closed as soon as all operations on it have been completed. This would close the file
associated with the file pointer.
Observe the following program.
….
FILE *p1 *p2;
p1=fopen (“Input”,”w”);
p2=fopen (“Output”,”r”);
….
…
fclose(p1);
fclose(p2)
The above program opens two files and closes them after all operations on them are completed, once a
file is closed its file pointer can be reversed on other file.
The getc and putc functions are analogous to getchar and putchar functions and handle one character at
a time. The putc function writes the character contained in character variable c to the file associated
with the pointer fp1. example putc(c,fp1); similarly getc function is used to read a character from a
file that has been open in read mode. c=getc(fp2).
The program shown below displays use of a file operations. The data enter through the keyboard and
the program writes it. Character by character, to the file input. The end of the data is indicated by
entering an EOF character, which is control-z. the file input is closed at this signal.
52 | P a g e
{
file *f1;
printf(“Data input output”);
f1=fopen(“Input”,”w”); /*Open the file Input*/
while((c=getchar())!=EOF) /*get a character from key board*/
putc(c,f1); /*write a character to input*/
fclose(f1); /*close the file input*/
printf(“nData outputn”);
f1=fopen(“INPUT”,”r”); /*Reopen the file input*/
while((c=getc(f1))!=EOF)
printf(“%c”,c);
fclose(f1);
}
These are integer-oriented functions. They are similar to get c and putc functions and are used to read
and write integer values. These functions would be usefull when we deal with only integer data. The
general forms of getw and putw are:
putw(integer,fp);
getw(fp);
fclose(f1);
fclose(f2);
fclose(f3);
f2=fopen(“ODD”,”r”);
f3=fopen(“EVEN”,”r”);
printf(“nnContents of the odd filenn”);
while(number=getw(f2))!=EOF)
printf(“%d%d”,number);
printf(“nnContents of the even file”);
while(number=getw(f3))!=EOF)
printf(“%d”,number);
fclose(f2);
fclose(f3);
}
The fprintf and fscanf functions are identical to printf and scanf functions except that they work on
files. The first argument of these functions is a file pointer which specifies the file to be used. The
general form of fprintf is
Where fp is a file pointer associated with a file that has been opened for writing. The control string is
file output specifications list may include variable, constant and string.
fprintf(f1,%s%d%f”,name,age,7.5);
Here, name is an array variable of type char and age is an int variable. The general format of fscanf is
fscanf(fp,”controlstring”,list);
This statement would cause the reading of items in the control string.
Example:
fscanf(f2,”5s%d”,item,&quantity”);
Like scanf, fscanf also returns the number of items that are successfully read.
float price,value;
char item[10],filename[10];
printf(“Input filename”);
scanf(“%s”,filename);
fp=fopen(filename,”w”);
printf(“Input inventory datann”0;
printf(“Item namem number price quantityn”);
for I=1;I< =3;I++)
{
fscanf(stdin,”%s%d%f%d”,item,&number,&price,&quality);
fprintf(fp,”%s%d%f%d”,itemnumber,price,quality);
}
fclose (fp);
fprintf(stdout,”nn”);
fp=fopen(filename,”r”);
printf(“Item name number price quantity value”);
for(I=1;I< =3;I++)
{
fscanf(fp,”%s%d%f%d”,item,&number,&prince,&quality);
value=price*quantity”);
fprintf(“stdout,”%s%d%f%d%dn”,item,number,price,quantity,value);
}
fclose(fp);
}
Sometimes it is required to access only a particular part of the and not the complete file. This can be
accomplished by using the following function:
1 > fseek
fseek function:
This function is used to move the file position to a desired location within the file. Fileptr
is a pointer to the file concerned. Offset is a number or variable of type long, and position in an integer
number. Offset specifies the number of positions (bytes) to be moved from the location specified bt the
position. The position can take the 3 values.
Value Meaning
0 Beginning of the file
1 Current position
2 End of the file.
55 | P a g e
Refs
1. [Link]
2. [Link]
3. [Link]
4. History of Programming Languages-II ed. Thomas J. Bergin, Jr. and Richard G. Gibson, Jr. ACM Press
(New York) and Addison-Wesley (Reading, Mass), 1996; ISBN 0-201-89502-1.
5. [Link]
6. [Link]
7. Eckel, B. (2000). Thinking in C++, Volume 1: Introduction to Standard C++ (2nd Edition), Prentice
8. Hall.
9. [Link]
10. Hanly, J. R., Ko_man, E. B. & Horvath, J. C. (1997). C Program Design for Engineers, Addison-Wesley.
12. Holmes, S. (1995). C programming, Internet tutorial, University of Strathclyde Computer Centre.
13. [Link]
15. Kernighan, B. W. & Ritchie, D. (1988). C Programming Language (2nd Edition), Prentice Hall PTR.
16. Knuth, D. E. (1999). The Art of Computer Programming, Volumes 1-3 Boxed Set, Addison-Wesley
18. [Link]
20. [Link]
21. Pozo, R. & Remington, K. (n.d.). C++ programming for scientists, NIST.
56 | P a g e
22. [Link]
23. Raymond, E. S. (1999). The Cathedral and the Bazaar: Musings on Linux and Open Source by an
24. Raymond, E. S. (2004). The Art of Unix Programming, Professional Computing Series, Addison-Wesley.
25. [Link]
26. van der Linden, P. (1994). Expert C Programming: Deep C Secrets, Prentice Hall.
27. [Link]
28. [Link]
29. [Link]
30. [Link]
31. [Link]
57 | P a g e