0% found this document useful (0 votes)
12 views57 pages

C Programming Practical Guide

The document is a practical tutorial on C programming, covering fundamental concepts such as the structure of a C program, data types, control statements, functions, and file management. It emphasizes the importance of coding, running, and debugging programs to understand C programming effectively. Additionally, it provides examples and explanations of basic C syntax and commands.

Uploaded by

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

C Programming Practical Guide

The document is a practical tutorial on C programming, covering fundamental concepts such as the structure of a C program, data types, control statements, functions, and file management. It emphasizes the importance of coding, running, and debugging programs to understand C programming effectively. Additionally, it provides examples and explanations of basic C syntax and commands.

Uploaded by

munashe1607
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

C Programming Practical Tutorial

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

Department of Computer Science (NUST)


C Programming Practical Tutorial

The for loop.....................................................................................................................................................30


Nested For Loops:............................................................................................................................................31
While and do while loops................................................................................................................................35
While loop.......................................................................................................................................................35

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

Department of Computer Science (NUST)


C Programming Practical Tutorial

3|Page

Department of Computer Science (NUST)


C Programming Practical Tutorial

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

Department of Computer Science (NUST)


C Programming Practical Tutorial

Introduction
What is computer programming?

Computer programming (often shortened to programming or coding) is the process of designing,


writing, testing, debugging, and maintaining the source code of computer programs. This source code is
written in a programming language. The purpose of programming is to create a program that exhibits a
certain desired behavior. The process of writing source code often requires expertise in many different
subjects, including knowledge of the application domain, specialized algorithms and formal logic.

What is a programming language?

A programming language is an artificial language designed to express computations that can be


performed by a machine, particularly a computer. Programming languages can be used to create
programs that control the behavior of a machine and/or to express algorithms precisely. Thousands of
different programming languages have been created, mainly in the computer field, with many more
being created every year. Most programming languages describe computation in an imperative style,
i.e., as a sequence of commands, although some languages, such as those that support functional
programming or logic programming, use alternative forms of description.

A programming language is usually split into the two components of syntax (form) and semantics
(meaning).

Examples of programming languages include:

 C, C++, C#, Ada, LUCID

 Pascal, Java, COBOL, Delphi, etc

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

Department of Computer Science (NUST)


C Programming Practical Tutorial

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.

Brief history of the C programming language

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

Department of Computer Science (NUST)


C Programming Practical Tutorial

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.

Basic Structure of a C program


The structure of a C program is a protocol (the rules) to the programmer, of writing a C program. The
general basic structure of C program is shown in the figure below. The whole program is controlled
within main ( ) function along with the left brace denoted by “{” and right brace denoted by “}”.
Declaration of local variables and executable program structures are enclosed within “{” and “}”
which is called the body of the main function. The main ( ) function can be preceded by
documentation, preprocessor statements and global declarations.

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

Department of Computer Science (NUST)


C Programming Practical Tutorial

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

Department of Computer Science (NUST)


C Programming Practical Tutorial

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.

Adhering to a well defined structured layout will make your programs

• 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.

Let's learn C programming.

Explanation of what each line means and does.

#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

Department of Computer Science (NUST)


C Programming Practical Tutorial

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.

printf("Let's learn C programming.");


Prints whatever is inside the quotes inside the parenthesis. This is the printf command and it prints text
on the screen. The data that is to be printed is put inside brackets. You will also notice that the words
are inside double quotes because they are what is called a string. Each letter is called a character and a
series of characters that is grouped together is called a string. Strings must always be put between
double quotes. The \n is called an escape sequence and represents a newline character and is used
because when you press ENTER it doesn't insert a new line character but instead takes you onto the
next line in the text editor. You have to put a semi-colon after every command to show that it is the end
of the command.

Table of commonly used escape sequences:

Escape Sequence Meaning


\a Audible signal
\b Backspace
\t Tab
\n Newline
\v Vertical tab
\f New page\Clear screen
\r Carriage return

10 | P a g e

Department of Computer Science (NUST)


C Programming Practical Tutorial

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:

/* Author: Your name


Date: yyyy/mm/dd
Description:
Writes the words "Let’s learn C programming" on the screen */

#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

Department of Computer Science (NUST)


C Programming Practical Tutorial

Constants, variables, data types, specifiers and comments

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.

To declare an integer we use int.


int x, y;
This declares the integer variables x and y.

To declare a floating point we use float.


float a, b;
This decalres the floating point variables a and b.

12 | P a g e

Department of Computer Science (NUST)


C Programming Practical Tutorial

To declare a double floating point we use double.


double c, d;
This declares the double floating point variables c and d.

To declare a character we use char.


char s, t;
This declares character variable s and t.

To declare a string we use character array.


char u[8], v[8];
This declares character variables array u and v of 7 characters. It's only seven characters because the
last one contains the terminating character. Just remember that expected number of characters is
always one less than the number specified.

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.

Signed and unsigned variables

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;
}

Using variables in calculations

To assign a value to a variable you use the equals sign.

int main()
{
int a;
char b;
a = 3;

13 | P a g e

Department of Computer Science (NUST)


C Programming Practical Tutorial

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;
}

Reading and printing variables

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

Department of Computer Science (NUST)


C Programming Practical Tutorial

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

Variable naming conventions

• 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

Department of Computer Science (NUST)


C Programming Practical Tutorial

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

The following is a list of valid variable names,


summary
exit_flag
iJerry7
Number_of_moves
_valid_flag

The #define statement


The define statement is a preprocessor statement used to make programs more readable. Consider the
following examples,
#define TRUE 1 /* Don't use a semi-colon , # must be first character on line */
#define FALSE 0
#define NULL 0
#define AND &
#define OR |
#define EQUALS ==

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.

In general, preprocessor constants are written in UPPERCASE.


The #define pre-processor statements can be used to replace the following constants
16 | P a g e

Department of Computer Science (NUST)


C Programming Practical Tutorial

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>

#define TAX_RATE 0.10

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>

#define TAX_RATE 0.10

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

Department of Computer Science (NUST)


C Programming Practical Tutorial

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

enclosing them as follows,

/* bla bla bla bla bla bla */

Note that the/* opens the comment field and*/ closes the comment field. Comments may span

multiple lines. Comments may not be nested one inside another.

/* this is a comment. /* this comment is inside */ wrong */

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.

Comments can also be placed in the following way:

// bla bla bla bla

18 | P a g e

Department of Computer Science (NUST)


C Programming Practical Tutorial

What Comments Are Used For

• documentation of variables and their usage

• explaining difficult sections of code

• describes the program, author, date, modification changes, revisions etc

• copyrighting

Now, here's an example.

#include <stdio.h>
#include <conio.h>

char name[8]; //the name should be seven characters or less


int a,b,sum;

main()
{
clrscr();

printf("What is the name of your college: ");/*you can use abbreviation*/


scanf("%s", &name);

printf("Please enter two numbers:");/*press enter after each number*/


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

sum=a+b;

printf("\nYou atttend %s.\n", name);


printf("%d + %d = %d", a, b, sum);

getch();
return(0);
}

Here's the output.

What is the name of your college: NUST


Please enter two numbers: 1 2

You attend NUST.


1 + 2 = 3

19 | P a g e

Department of Computer Science (NUST)


C Programming Practical Tutorial

Explanation of the code:

printf("What is the name of your college: ");


scanf("%s", &name);
The first line ask the user the name of their college and the scanf gets the input from the user. We use
the specifier %s because it is a string variable. There should be an ampersand before the variable
where inputted data will be stored. C considers a space as a terminating character only your first name
can be saved. To be able to have spaces you can replace the scanf with name=gets();.

printf("Please enter two numbers:");


scanf("%d %d", &a, &b);
Here, the user is asked to input two numbers and the numbers will be stored in variables a and b. We
used %d for integers and there should always be an ampersand in front of the variable.

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.

printf("You attend %s.\n", name);


printf("%d + %d = %d", a, b, sum);
When displaying variables, you have the comment inside the string and you replace where you want
the value of a variable to be with a specifier. The string is followed by a comma and the variable. The
order of the variable from left to right follows the order of the specifier respectively.

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]

The output should look similar to this.

What is your name: Lio


Please enter two numbers: 1 2 3

Your name is Lio.


1 + 2 + 3 = 6
6 / 3 = 2

20 | P a g e

Department of Computer Science (NUST)


C Programming Practical Tutorial

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:

Relational operators: allow comparing two values.

== is equal to

!= not equal to

< less than

> greater than

<= less than or equal to

>= greater than or equal to

Complex logical operators: can combine expressions to get complex logical expressions

&& and

|| or

Tip: Take particular note of how braces { } are used.

Tip: Note where ; is NOT used in these constructs.

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

The condition to be tested is any expression enclosed in parentheses. It is followed by a statement.


The expression is evaluated, and if its value is true, the statement is executed as follows:

21 | P a g e

Department of Computer Science (NUST)


C Programming Practical Tutorial

if ( statement is TRUE )
Execute this line of code

Here is a simple example that shows the syntax:

if ( 5 < 10 )
printf( "Five is less than ten" );

If statement flow chart

Start

Condition No

Yes
Perform

Task

Exit

Example:

#include <stdio.h>

#include<conio.h>

22 | P a g e

Department of Computer Science (NUST)


C Programming Practical Tutorial

main()

int a,b;

printf(“Enter a,b values:”);

scanf(“%d %d”,&a,&b);

if(a>b)

printf(“\n a is greater than b”);

OUTPUT:

Enter a,b values:20 10

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.

It can look like this:

if ( TRUE ) {
/* Execute these statements if TRUE */
}
else {
/* Execute these statements if FALSE */
}

The syntax of if-else is


if (expression)
{
statement(s);
}
else
{
23 | P a g e

Department of Computer Science (NUST)


C Programming Practical Tutorial

statement(s);
)
Flow chart for else-if statement

Start

No
Condition
Yes

Yes

Perform Perform

Task else part

Exit

Example:

#include <stdio.h>
#include<conio.h>

main()
{
int a,b;

printf(“Enter a,b values:”);


scanf(“%d %d”,&a,&b);

if(a>b)
printf(“\n a is greater than b”);
else
printf(“\n b is greater than a”);
}

OUTPUT:

Enter a,b values:20 40

24 | P a g e

Department of Computer Science (NUST)


C Programming Practical Tutorial

b is greater than a

25 | P a g e

Department of Computer Science (NUST)


C Programming Practical Tutorial

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.

The syntax of if-else-if is


if (expression)
{
statement(s);
}
else if (expression)
{
statement(s);
else if (expression)
{
statement(s);
else
statement(s)
}

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

Department of Computer Science (NUST)


C Programming Practical Tutorial

OUTPUT:

Enter a,b values:10 10

a is equal to b

The case switch statement

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.

The syntax is:


switch (variable) {
case constant expression: statement; break;
default: statement;
}

Now here is an example.

#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

Department of Computer Science (NUST)


C Programming Practical Tutorial

The Switch-Case statement explained

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;

Explanation of the code:

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:

a) Sunny and hot

b) Wet and windy

c) Wet and cold

d) Windy

28 | P a g e

Department of Computer Science (NUST)


C Programming Practical Tutorial

for the user to make their choice.

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

Department of Computer Science (NUST)


C Programming Practical Tutorial

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

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.

The syntax is:

for (initialization; condition; incrementation) statement;

or for multiple statements:

for (initialization; condition; incrementation)


{
statement 1
statement 2
}

The For Loop works with the following short cuts:

The long Way i=i+1 i=i-1 i=i+2 i=i-2 i=i*2 i=i/2


The short cut i++ i-- i+=2 i-=2 i*=2 i/=2

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

Department of Computer Science (NUST)


C Programming Practical Tutorial

printf("\n\nCounts down from 10 to 0.\n");


for (i=10; i>=0; i--) printf("%d ", i);
printf("\n\nCounts the odd numbers from 1 to 21.\n");
for (i=1; i<=21; i+=2) printf("%d ", i);
printf("\n\nMultiple statements.\n");
for (i=0; i<3; i++)
{
printf("%d ", i);
printf("C programming is fun\n");
}
getch();
}`

Prints my college three times.


National University of Science and Technology
National University of Science and Technology
National University of Science and Technology

Counts from 1 to ten.


1 2 3 4 5 6 7 8 9 10

Counts down from 10 to 0.


10 9 8 7 6 5 4 3 2 1 0

Counts the odd numbers from 1 to 21.


1 3 5 7 9 11 13 15 17 19 21

Multiple statements.
0 C programming is fun
1 C programming is fun
2 C programming is fun

Nested For Loops:

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

Department of Computer Science (NUST)


C Programming Practical Tutorial

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();
}

Prints the value of i and j as it goes through the loop.


(0, 0)
(0, 1)
(0, 2)
(0, 3)
(0, 4)
(1, 0)
(1, 1)
(1, 2)
(1, 3)
(1, 4)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 0)
(3, 1)
(3, 2)
(3, 3)
(3, 4)
(4, 0)
(4, 1)
(4, 2)
(4, 3)
(4, 4)

Other programs to run:


A. Create a program that uses a for loop that doubles the value of i starting from 1 to 1024. The
output should be 1 2 4 8 16 32 64 ... 1024.

#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

Department of Computer Science (NUST)


C Programming Practical Tutorial

Every loop doubles the value until it is 1024.


1 2 4 8 16 32 64 128 256 512 1024

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>

float num, fact=1;

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();
}

Enter a number to find the factorial.8


The factorial of 8 is 40320.

33 | P a g e

Department of Computer Science (NUST)


C Programming Practical Tutorial

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

/* This is a comment code.


Anything between the slash and asteriks is
ignored by the compiler and does not run.*/

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

Department of Computer Science (NUST)


C Programming Practical Tutorial

While and do while loops

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:

while (test condition)


{
body of the loop
}

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:

# include < stdio.h > //include the stdio.h file


void main() // Start of your program
{
int n, i=0; //Declare and initialize the variables
printf(“Enter the upper limit number”); //Message to the user
scanf(“%d”, &n); //read and store the number
while(i < = n) // While statement with condition
{ // Body of the loop
printf(“\t%d”,i); // print the value of i
i++; increment i to the next natural number.
}
}

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

Department of Computer Science (NUST)


C Programming Practical Tutorial

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.

The syntax of the do while loop is:

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.

/* Program to illustrate the do while loop*/


#include < stdio.h > //include stdio.h file to your program
void main() // start of your program
{
char inchar; // declaration of the character
do // start of the do loop
{
printf(“Input Y or N”); //message for the user
scanf(“%c”, &inchar); // read and store the character
}
while(inchar!=’y’ && inchar != ‘n’); //while loop ends
if(inchar==’y’) // checks whether entered character is y
printf(“you pressed u\n”); // message for the user
else

36 | P a g e

Department of Computer Science (NUST)


C Programming Practical Tutorial

printf(“You pressed n\n”);


} //end of for loop

37 | P a g e

Department of Computer Science (NUST)


C Programming Practical Tutorial

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

Department of Computer Science (NUST)


C Programming Practical Tutorial

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

for(i=0;i < 100;++i);


sum = sum + grades [i];

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

next_value=sorted_data[(low+high)/2]; would assign to the variable next_value


indexed by evaluating the expression (low+high)/2. If low is equal to 1 and high were equal to 9,
then the value of sorted_data[5] would be assigned to the next_value and if low were
equal to 1 and high were equal to 10 then the value of sorted_data[5] would also be referenced.

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

Department of Computer Science (NUST)


C Programming Practical Tutorial

values[2]

values[3]

values[4]

values[5]

values[6]

values[7]

values[8]

values[9]

The array values stored in the memory.

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:

type array_name[size]={list of values};

The values in the list are separated by commas, for example the statement

int number[3]={0,0,0};

40 | P a g e

Department of Computer Science (NUST)


C Programming Practical Tutorial

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.

The initialization of arrays in c suffers two draw backs


1. There is no convenient way to initialize only selected elements.
2. There is no shortcut method to initialize large number of elements.

/* Program to count the no of positive and negative numbers*/


#include< stdio.h >
void main( )
{
int a[50],n,count_neg=0,count_pos=0,I;
printf(“Enter the size of the array\n”);
scanf(“%d”,&n);
printf(“Enter the elements of the array\n”);
for I=0;I < n;I++)
scanf(“%d”,&a[I]);
for(I=0;I < n;I++)
{
if(a[I] < 0)
count_neg++;
else
count_pos++;
}
printf(“There are %d negative numbers in the array\n”,count_neg);
printf(“There are %d positive numbers in the array\n”,count_pos);
}

Multi dimensional Arrays:

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

Department of Computer Science (NUST)


C Programming Practical Tutorial

data_type array_name[row_size][column_size];
int m[10][20]

Here m is declared as a matrix having 10 rows( numbered from 0 to 9) and 20 columns(numbered 0


through 19). The first element of the matrix is m[0][0] and the last row last column is m[9][19]

Elements of multi dimension arrays:

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.

marks [0][0] Marks [0][1] Marks [0][2]


35.5 40.5 45.5

marks [1][0] Marks [1][1] Marks [1][2]


50.5 55.5 60.5

marks [2][0] Marks [2][1] Marks [2][2]

marks [3][0] Marks [3][1] Marks [3][2]

Initialization of multidimensional arrays:

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

Department of Computer Science (NUST)


C Programming Practical Tutorial

date_type array_name[s1][s2][s3]…..[sn];

where s is the size of the ith dimension. Some examples are:

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

Department of Computer Science (NUST)


C Programming Practical Tutorial

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.

int sum(int x, int y)//function header


{//function body
int ans = 0; //holds the answer that will be returned
ans = x + y; //calculate the sum
return ans; //return the answer
}

Function Header

It is the first line of the above code

int sum(int x, int y)

It has three main parts

1. The name of the function i.e. sum


2. The parameters of the function enclosed in paranthesis
3. Return value type i.e. int

44 | P a g e

Department of Computer Science (NUST)


C Programming Practical Tutorial

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

int sum (int x, int y);

The only difference between the header and the prototype is the semicolon (;) there must be a
semicolon at the end of the prototype.

Example program with functions

#include<stdio.h>
#include<conio.h>

int num1, num2;

void input() {
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);}

int sum(int x, int y) {return(x+y);}

void output() {printf("%d + %d = %d", num1, num2, sum(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

Department of Computer Science (NUST)


C Programming Practical Tutorial

Types of functions
There are five types of functions and these are:

1. Functions with no arguments and no return values.


2. Functions with arguments and no return values.

3. Functions with arguments and return values.

4. Functions that return multiple values.

5. Functions with no arguments and return values.

NB: Read further to understand what is meant by these types of functions

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

Department of Computer Science (NUST)


C Programming Practical Tutorial

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.

Before we move to another example lets have attributes of “recursive function”:-

1. A recursive function is a function which calls itself.


2. The speed of a recursive program is slower because of stack overheads. (This attribute is
evident if you run above C program.)

3. A recursive function must have recursive conditions, terminating conditions, and recursive
expressions.

Calculating the factorial value using recursion


To understand how recursion works lets have another popular example of recursion. In this example
we will calculate the factorial of n numbers. The factorial of n numbers is expressed as a series of
repetitive multiplication as shown below:

Factorial of n = n(n-1)(n-2)……1.

Example :

Factiorial of 5 = 5x4x3x2x1
=120

47 | P a g e

Department of Computer Science (NUST)


C Programming Practical Tutorial

#include<stdio.h>

#include<conio.h>

int factorial(int);

int factorial (int i)

int f;

if(i==1)

return 1;

else

f = i* factorial (i-1);

return f;

void main()

int x;

clrscr();

printf("Enter any number to calculate factorial :");

scanf("%d",&x);

printf("\nFactorial : %d", factorial (x));

getch();

48 | P a g e

Department of Computer Science (NUST)


C Programming Practical Tutorial

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);

will be executed with i=5 i.e.

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* factorial (4-1);

f = 5*4*3* factorial (3-1);

f = 5*4*3*2* factorial (2-1);

f = 5*4*3*2*1;

f = 120;

49 | P a g e

Department of Computer Science (NUST)


C Programming Practical Tutorial

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.

File operation functions in C:


Function Operation
Name

fopen() Creates a new file for use


Opens a new existing file for use

fclose Closes a file which has been opened for use

getc() Reads a character from a file

putc() Writes a character to a file


50 | P a g e

Department of Computer Science (NUST)


C Programming Practical Tutorial

fprintf() Writes a set of data values to a file

fscanf() Reads a set of data values from a file

getw() Reads a integer from a file

putw() Writes an integer to the file

fseek() Sets the position to a desired point in the file

ftell() Gives the current position in the file

rewind() Sets the position to the begining of the file

Defining and opening a file:

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.

The general format of the function used for opening a file is

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

Department of Computer Science (NUST)


C Programming Practical Tutorial

R open the file for read only.


W open the file for writing only.
A open the file for appending data to it.

Consider the following statements:

FILE *p1, *p2;


p1=fopen(“data”,”r”);
p2=fopen(“results”,”w”);

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.

#include< stdio.h >


main()

52 | P a g e

Department of Computer Science (NUST)


C Programming Practical Tutorial

{
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);
}

The getw and putw functions:

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);

/*Example program for using getw and putw functions*/


#include< stdio.h >
main()
{
FILE *f1,*f2,*f3;
int number I;
printf(“Contents of the data filenn”);
f1=fopen(“DATA”,”W”);
for(I=1;I< 30;I++)
{
scanf(“%d”,&number);
if(number==-1)
break;
putw(number,f1);
}
fclose(f1);
f1=fopen(“DATA”,”r”);
f2=fopen(“ODD”,”w”);
f3=fopen(“EVEN”,”w”);
while((number=getw(f1))!=EOF)/* Read from data file*/
{
if(number%2==0)
putw(number,f3);/*Write to even file*/
else
putw(number,f2);/*write to odd file*/
}
53 | P a g e

Department of Computer Science (NUST)


C Programming Practical Tutorial

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 & fscanf functions:

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

fprintf(fp,”control string”, list);

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.

/*Program to handle mixed data types*/


#include< stdio.h >
main()
{
FILE *fp;
int num,qty,I;
54 | P a g e

Department of Computer Science (NUST)


C Programming Practical Tutorial

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);
}

Random access to files:

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:

The general format of fseek function is as follows:

fseek(file pointer,offset, position);

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

Department of Computer Science (NUST)


C Programming Practical Tutorial

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.

11. classmark 518.567.5 HAN.

12. Holmes, S. (1995). C programming, Internet tutorial, University of Strathclyde Computer Centre.

13. [Link]

14. Hunt, A. & Thomas, D. (1999). The Pragmatic Programmer, Addison-Wesley.

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

17. McGrath, M. (2006). C programming, In Easy Steps, Computer Step.

18. [Link]

19. Pike, R. (n.d.). Notes on programming in c.

20. [Link]

21. Pozo, R. & Remington, K. (n.d.). C++ programming for scientists, NIST.

56 | P a g e

Department of Computer Science (NUST)


C Programming Practical Tutorial

22. [Link]

23. Raymond, E. S. (1999). The Cathedral and the Bazaar: Musings on Linux and Open Source by an

Accidental Revolutionary (O'Reilly Linux), O'Reilly.

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

Department of Computer Science (NUST)

You might also like