C Programming Basics and Exercises
C Programming Basics and Exercises
HANDOUT
Detailed Lesson notes with practical exercises and applications in C-programming.
Table of Contents
TOPIC 1: GETTING STARTED WITH C PROGRAMMING ................................................... 1
I. WHAT IS A C/C++ PROGRAMMING LANGUAGE? ................................................ 2
II. C & C++: SIMILARITIES AND DIFFERENCES .................................................... 2
III. WHAT DO WE NEED? ............................................................................................. 2
IV. MY FIRST C-PROGRAM .......................................................................................... 2
V. UNDERSTANDING OF THE PROGRAM STRUCTURE ....................................... 4
EXERCISE 1 .......................................................................................................................... 5
TOPIC 2: C CONSTANTS AND VARIABLES ......................................................................... 6
I. KEYWORD .................................................................................................................... 6
II. IDENTIFIERS ............................................................................................................. 7
III. DATA TYPE ............................................................................................................... 7
IV. C VARIABLES ........................................................................................................... 9
V. C CONSTANTS AND LITERALS .......................................................................... 10
VI. INPUT AND OUTPUT............................................................................................. 13
EXERCICE 2 ....................................................................................................................... 14
TOPIC 3: OPERATORS IN C ................................................................................................ 15
I. ARITHMETIC OPERATORS ..................................................................................... 15
II. RELATIONAL OPERATORS ................................................................................. 16
III. LOGICAL OPERATORS ......................................................................................... 17
IV. BITWISE OPERATORS .......................................................................................... 18
V. ASSIGNMENT OPERATORS ................................................................................. 20
VI. OPERATORS PRECEDENCE IN C ........................................................................ 21
EXERCISE 3 ........................................................................................................................ 22
TOPIC 4: CONDITIONS(Selection) ....................................................................................... 24
I. THE IF STATEMENT ................................................................................................. 24
II. CONDITIONAL SELECTION — SWITCH ........................................................... 29
III. THE ? : OPERATOR ................................................................................................ 31
EXERCISE 4 ........................................................................................................................ 31
TOPIC 5: CONTROL STRUCTURES (Looping) ................................................................... 34
I. FOR LOOP IN C .......................................................................................................... 34
II. WHILE LOOP IN C .................................................................................................. 36
III. DO...WHILE LOOP IN C ......................................................................................... 38
IV. NESTED LOOPS IN C ............................................................................................. 39
V. BREAK STATEMENT IN C.................................................................................... 40
VI. CONTINUE STATEMENT IN C ............................................................................. 41
VII. GOTO STATEMENT IN C ...................................................................................... 42
VIII. THE INFINITE LOOP .......................................................................................... 44
EXERCISE 5 ........................................................................................................................ 44
TOPIC 6: MODULAR PROGRAMMING (Functions) ......................................................... 47
I. INTRODUCTIVE TO FUNCTION (OR PROCEDURE) ........................................... 47
II. INTRODUCTION TO USER-DEFINED FUNCTIONS ......................................... 48
III. RECURSION ............................................................................................................ 51
IV. FUNCTION ARGUMENTS ..................................................................................... 52
EXERCISE 6 ........................................................................................................................ 54
TOPIC 7: ARRAY, STRING & POINTER ............................................................................ 56
I. ARRAY......................................................................................................................... 56
II. TWO-DIMENSIONAL ARRAYS ........................................................................... 58
III. STRING .................................................................................................................... 60
IV. POINTER .................................................................................................................. 65
EXERCISE 7 ........................................................................................................................ 70
TOPIC 8: COMPLEX DATA TYPES ..................................................................................... 73
I. STRUCTURE ............................................................................................................... 73
II. ENUMERATION...................................................................................................... 78
III. UNION ...................................................................................................................... 79
IV. TYPEDEF ................................................................................................................. 80
V. FILES ........................................................................................................................ 80
EXERCISE 8 ........................................................................................................................ 83
TOPIC 1
INTRODUCTION
The C programming language, created by Dennis Ritchie in the early 1970s, evolved from
earlier languages like B, BCPL, and ALGOL to meet the demands of Unix operating system
development. Introducing concepts such as data types and structured programming, C became
the standard for systems programming in the 1980s and has influenced numerous other
languages. Today, C remains a widely-used and essential tool in software development,
forming the basis for modern computing.
C (and its object oriented version, C++) is one of the most widely used third generation
programming languages. Its power and flexibility ensure it is still the leading choice for almost
all areas of application, especially in the software development environment.
Many applications and many Operating systems are written in C or C++, including the
compilers for other programming languages, Unix, DOS and Windows. It continues to adapt
to new uses with new programming languages like Java, C#, Python, PHP, etc which lay the
foundation on C language.
Objectives
At the end of this lesson, student should be able to:
- Describe the structure of a C-program
- write, compile and execute a simple C-program using the command “printf” and
escape sequences, and containing comments
Contents
I. WHAT IS A C/C++ PROGRAMMING LANGUAGE? ........................................... 2
II. C & C++: SIMILARITIES AND DIFFERENCES ................................................ 2
III. WHAT DO WE NEED? ........................................................................................... 2
IV. MY FIRST C-PROGRAM ....................................................................................... 2
V. UNDERSTANDING OF THE PROGRAM STRUCTURE ..................................... 4
EXERCISE 1 ........................................................................................................................ 5
I. WHAT IS A C/C++ PROGRAMMING LANGUAGE?
1) Syntax: This is a language structure (or grammar) that allows humans to combine
these C commands into a program that actually does some-thing.
2) Semantics: This is a vocabulary of commands that humans can understand and that
can be converted into machine language, fairly easily, using compiler
C++, as the name suggests is a superset of C. As a matter of fact, C++ compitler can run most
of C code while C cannot run C++ code. Here are some basic differences between C++ & C...
- an editor which is what you use to write your code as you build your .C source file.
- a compiler (& linker) converts your source file into a machine-executable .EXE file
that carries out your real-world commands.
There are tools combining both compiler and editor in one called development environment.
We will use DevC++ IDE (Integrated Development Environment), version 5.5.3. It can be
downloaded freely in [Link]
The program can be now typed into the editor using the c syntax. Our first program on what
we are going to discover the functioning of a C-program is:
1 #include <stdio.h>
2 int main()
3 {
4 /* my first program in C */
5 printf("This is my first experience in C! ");
6 return 0;
7 }
3) Save the program
To save the program: The file saved is called the source file
File → save as → in the dialog box type the name and choose the type (here the type to
choose is C source code) → save.
Compiling is the process of transforming the source code (the instructions in the text file) into
the object code (instructions the computer’s microprocessor can understand). The linking step
is where the instructions are finally transformed into a program file. (Again, your compiler may
do this step automatically.)
After the compilation, if everything is ok, an executable code will be created with the same
name and in a same folder and with the extension .exe. Else the compiler will produce an error
message. In this case debug the program (check the code and correct the error(s)) and compile
the source code again.
Finally, you run the program you have created. Yes, it’s a legitimate program, like any other
on your hard drive.
To execute the program:
[Link]
Execute → Run
OF THE PROGRAM
STRUCTURE
1) #include <stdio.h>
The first line of the program #include <stdio.h> is a preprocessor command which is used to
include a library containing functions used in our program, It tells a C compiler to include
stdio.h file before going to actual compilation.
2) Main()
The C program starting point is identified by main(). This informs the computer where the
program actually starts. Two empty parentheses follow the function name. Sometimes, items
may be in these parentheses, which we will cover later.
3) { & }
All functions in C have their contents encased by curly braces. The two braces { and } signify
the begin and the end segments of the program. In general, braces are used throughout C to
enclose a block of statement to be treated as a unit.
4) Printf()
printf(...) is another function available in C which causes the message " This is my first
experience in C!" to be displayed on the screen. For printf to work, the header file “stdio.h”
must be included at the beginning of the program.
5) \n
An interesting part of the text string is \n. Together, the backslash (\) and n characters make up
an escape sequence. This particular escape sequence (\n) tells the program to add a new line.
Other example of escape sequence are: \t (Moves the cursor to the next tab), \r(Moves the
cursor to the beginning of the current line), \\( Inserts a backslash), \”( Inserts a double quote),
\’(Inserts a single quote).
6) /*… */ or //
They are use to insert comments into a C program. Comments serve for internal documentation
for program structure and functionalities. There are two types of comment: The single line
comment (by using //) and by multiple line command (by using /*….*/)
7) Return 0;
– The success of compilation does not assure in any case the good result of the execution.
Errors can still happen during the execution. This type of error is called runtime error and
will be treated further.
– C is case sensitive (main ≠ Main). All commands in C must be in lowercase.
– C has a free-form line structure. Multiple statements can be on the same line. White space
is ignored. Statements can continue over many lines.
– In C program, the semicolon is a statement terminator. That is, each individual statement
must be ended with a semicolon. It indicates the end of one logical entity.
EXERCISE 1
*
***
*****
Exercise 1.2: Write a C-program to print the following sentence:
Exercise 1.3: Using an appropriate escape sequence, write a C program that display a sample
calendar month as the following: [See Activity 1.2]
-----------------------------------------------------------------
Sun Mon Tue Wed Thu Fri Sat
----------------------------------------------------------------
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Exercise 1.4: Write a C program that prints on the screen the words “Now is the time for all
good men to come to the aid of their country”
– all on one line;
– on three lines;
– on two lines inside a box composed of * characters.
TOPIC 2
Contents
I. KEYWORD ................................................................................................................... 6
II. IDENTIFIERS ........................................................................................................... 7
III. DATA TYPE .............................................................................................................. 7
IV. C VARIABLES.......................................................................................................... 9
V. C CONSTANTS AND LITERALS ........................................................................ 10
VI. INPUT AND OUTPUT ........................................................................................... 13
EXERCICE 2 ...................................................................................................................... 14
I. KEYWORD
[See Activity 2.1]
Keywords are reserved words which have standard, predefined meaning in C. They cannot be used
as program-defined identifiers.
For example, some valid identifiers are: nb1, cons, h456787, tax_rate, _XI, FOR…
For example, some invalid identifiers are shown below: [See Activity 2.1]
Note: Generally all keywords are in lower case although uppercase of same names can be used as
identifiers.
Following table gives you details about standard integer types with its storage sizes and
value ranges:
Type Storage size Value range
Char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
Int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
Short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
Long 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295
To get the exact size of a type or a variable on a particular platform, you can use the
sizeof operator. The expressions sizeof(type) yields the storage size of the object or type in bytes.
Following is an example to get the size of int type on any machine:
#include <stdio.h>
int main()
{
printf("Storage size for int : %d \n", sizeof(int));
return 0;
}
Following table gives you details about standard floating-point types with storage sizes and
value ranges and their precision:
The header file float.h defines macros that allow you to use these values and other details about
the binary representation of real numbers in your programs. Following example will print storage
space taken by a float type and its range values:
#include <stdio.h>
#include <float.h>
int main()
{
printf("Storage size for float : %d \n", sizeof(float));
printf("Minimum float positive value: %E\n", FLT_MIN );
printf("Maximum float positive value: %E\n", FLT_MAX );
printf("Precision value: %d\n", FLT_DIG );
return 0;
}
IV. C VARIABLES
A variable declaration provides assurance to the compiler that there is one variable existing with
the given type and name so that compiler proceed for further compilation without needing
complete detail about the variable. A variable definition specifies a data type and contains a list
of one or more variables of that type as follows
The syntax for declaring variables is as follows:
int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; both declares and defines the variables i, j and k; which instructs the compiler
to create variables named i, j and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The initializer
consists of an equal sign followed by a constant expression as follows:
1. lvalue: An expression that is an lvalue may appear as either the left-hand or right-hand side
of an assignment.
2. rvalue: An expression that is an rvalue may appear on the right- but not left-hand side of an
assignment.
Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric
literals are rvalues and so may not be assigned and cannot appear on the left-hand
side.
Following is a valid statement: int g = 20; But following is not a valid statement and
would generate compile-time error: 10 = 20;
#include<stdio.h>
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main()
{
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area); printf("%c", NEWLINE);
return0;
}
When the above code is compiled and executed, it produces the following result:
value of area : 50
You can use const prefix to declare constants with a specific type as follows:
#include<stdio.h>
int main()
{
const int LENGTH =10;
const int WIDTH =5;
const char NEWLINE ='\n';
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return0;
}
When the above code is executed, it produces the following result: value of area : 50
There are certain characters in C when they are preceded by a backslash they will have special
meaning and they are used to represent like newline (\n) or tab (\t). Here, you have a list of some
of such escape sequence codes:
Escape Escape
Meaning Meaning
sequence sequence
\\ \ character \n Newline
\' ' character \r Carriage return
\" " character \t Horizontal tab
\? ? character \v Vertical tab
\a Alert or bell \ooo Octal number of one to three digits
\b Backspace \xhh . . . Hexadecimal number of one or more digits
\f Form feed
scanf is a function in C which allows the programmer to accept input from a keyboard. It obtains
a value from the user
& is confusing in beginning – for now, just remember to include it with the variable name in scanf
statements.
When executing the program the user responds to the scanf statement by typing in a number, then
pressing the Enter (return) key
The arguments to scanf must be pointers (addresses), hence the need for the & character above.
The following table show what format specifies should be used with what data types:
%c character %u unsigned
%d decimal integer %i integer
%x hexadecimal integer %e or %f or %g floating point number
%o octal integer %s string pointer to char
%ld long integer %lf long double
NB: When reading integers using the “I” conversion character, the data entered may be
preceded by 0 or 0x to indicate that the data is in octal (base 8) or hexadecimal (base16).
#include <stdio.h>
int main()
{
char me[20];
printf("What is your name?");
scanf("%s",&me);
printf("Darn glad to meet you, %s!\n",me,);
return(0);
}
int main()
{
int c;
c = getchar(); /* read a character and assign to c */
putchar(c); /* print c on the screen */
return 0;
}
getchar and putchar are used for the input and output of single characters respectively.
getchar() returns an int which is either EOF(indicating end-of-file, see later) or the next
character in the standard input stream
putchar(c) puts the character c on the standard output stream.
EXERCICE 2
Exercise 2.1: Identify keywords and valid identifiers among the following:
OPERATORS IN C
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C language is rich in built-in operators and provides the following types of
operators:
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
Objectives:
This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other
operators one by one.
Contents
I. ARITHMETIC OPERATORS ....................................................................................... 15
II. RELATIONAL OPERATORS ................................................................................... 16
III. LOGICAL OPERATORS ........................................................................................... 17
IV. BITWISE OPERATORS............................................................................................. 18
V. ASSIGNMENT OPERATORS ................................................................................... 20
VI. OPERATORS PRECEDENCE IN C ......................................................................... 21
EXERCISE 3 ........................................................................................................................... 22
I. ARITHMETIC OPERATORS
[See Activity 3.1] [See Activity 3.6]
Following table shows all the arithmetic operators supported by C language. Assume variable A
holds 15 and variable B holds 20, then:
Try the following example to understand all the arithmetic operators available in C programming
language:
#include<stdio.h>
int main()
{
int a =21; int b=10; int c ;
c = a + b; printf("Line 1 - Value of c is %d\n", c );
c = a-b; printf("Line 2 - Value of c is %d\n", c );
c = a * b; printf("Line 3 - Value of c is %d\n", c );
c = a / b; printf("Line 4 - Value of c is %d\n", c );
c = a % b; printf("Line 5 - Value of c is %d\n", c );
c = a++; printf("Line 6 - Value of c is %d\n", c );
c = a--; printf("Line 7 - Value of c is %d\n", c );
return 0;
}
When you compile and execute the above program, it produces the following result:
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 21
Line 7 - Value of c is 22
Following table shows all the relational operators supported by C language. Assume variable A
holds 10 and variable B holds 20, then:
Following table shows all the logical operators supported by C language. Assume variable A
holds 1 and variable B holds 0, then:
Try the following example to understand all the logical operators available in C programming
language:
#include<stdio.h>
int
main()
{
int a =5;int b =20;int c ;
if( a && b )
printf("Line 1 - Condition is true\n");
if( a || b )
printf("Line 2 - Condition is true\n");
/* lets change the
value of a and b */
a =0; b =10;
if( a && b )
printf("Line 3 - Condition is true\n");
else
printf("Line 3 - Condition is not true\n");
if(!(a && b))
printf("Line 4 - Condition is true\n");
}
When you compile and execute the above program, it produces the following result:
Assume if A = 60; and B = 13; now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100 A|B = 0011 1101 A^B = 0011 0001 ~A = 1100 0011
The Bitwise operators supported by C language are listed in the following table. Assume variable
A holds 60 and variable B holds 13, then:
Try the following example to understand all the bitwise operators available in C programming
language:
#include<stdio.h>
main()
{
unsigned int a =60; /* 60 = 0011 1100 */
unsigned int b =13; /* 13 = 0000 1101 */
int c =0;
c = a & b; /* 12 = 0000 1100 */
printf("Line 1 - Value of c is %d\n", c );
c = a | b; /* 61 = 0011 1101 */
printf("Line 2 - Value of c is %d\n", c );
c = a ^ b; /* 49 = 0011 0001 */
printf("Line 3 - Value of c is %d\n", c );
c =~a; /*-61 = 1100 0011 */
printf("Line 4 - Value of c is %d\n", c );
c = a <<2; /* 240 = 1111 0000 */
printf("Line 5 - Value of c is %d\n", c );
c = a >>2; /* 15 = 0000 1111 */
printf("Line 6 - Value of c is %d\n", c );
return 0;
}
When you compile and execute the above program, it produces the following result:
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15
V. ASSIGNMENT OPERATORS
[See Activity 3.3]
There are following assignment operators supported by C language:
There are few other important operators including sizeof and ? : supported by C Language.
Operator Description Example
sizeof() Returns the size of an variable. sizeof(a), where a is integer, will return 4.
& Returns the address of an variable. &a; will give actual address of the variable.
* Pointer to a variable. *a; will pointer to a variable.
If Condition is true? Then value X : Otherwise
?: Conditional Expression
value Y
#include<stdio.h>
main()
{
int a =20;int b =10;int c =15;int d =5;int e;
e =(a + b)* c / d;// ( 30 * 15 ) / 5
printf("Value of (a + b) * c / d is : %d\n", e );
e =((a + b)* c)/ d;// (30 * 15 ) / 5
printf("Value of ((a + b) * c) / d is : %d\n", e );
e =(a + b)*(c / d);// (30) * (15/5)
printf("Value of (a + b) * (c / d) is : %d\n", e );
e = a +(b * c)/ d;// 20 + (150/5)
printf("Value of a + (b * c) / d is : %d\n", e );
return0;
}
When you compile and execute the above program, it produces the following result:
Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is : 90
Value of (a + b) * (c / d) is : 90
Value of a + (b * c) / d is : 50
[See Activity 3.4]
EXERCISE 3
Exercise 3.2: Given a time in seconds (integer), print to the screen the corresponding time in
hours, minutes and seconds. The output will be formatted like: “XXXX seconds is equivalent to
XX hours, XX minutes and XX seconds”.
Exercise 3.3: Write a C code that switches the values of two variables A and B and prints the
result on the screen. How many variables do you need?
Exercise 3.4: Write a program that reads in an integer and prints out the given integer in decimal,
octal and hexadecimal formats
Exercise 3.5: Write a program that reads in a temperature expressed in Celsius (Centigrade) and
displays the equivalent temperature in degrees Fahrenheit.
Exercise 3.6: Create a new program that prompts a user for numbers and determines total revenue
using the following formula: Total Revenue = Price * Quantity.
Exercise 3.7: Build a new program that prompts a user for data and determines a commission
using the following formula: Commission = Rate * (Sales Price – Cost).
Exercise 3.8: a) Given a = 5, b = 1, x = 10, and y = 5, create a program that outputs the result of
the formula f = (a b)(x y) using a single printf() function.
b) Create a program that uses the same formula above to output the result; this time, however,
prompt the user for the values a, b, x, and y. Use appropriate variable names and naming
conventions.
Exercise 3.9: Create a program that prompts a user for her name. Store the user’s name using the
scanf() function and return a greeting back to the user using her name.
Exercise 3.10: Write a program to read in a three digit number and produce output like
3 hundreds
4 tens
7 units
For an input of 347. There are two ways of doing this. Can you think of both of them? Which do
you think is the better?
TOPIC 4
CONDITIONS(Selection)
A program is usually not limited to a linear sequence of instruction. In real life, a program usually
needs to change the sequence of execution according to some conditions. In C language, there are
many control structure that are used to handle conditions and the resultant decisions. This lesson
introduces if-else and switch construct.
Contents_Toc400143325
I. THE IF STATEMENT .................................................................................................... 24
II. CONDITIONAL SELECTION — SWITCH ............................................................ 29
III. THE ? : OPERATOR .................................................................................................. 31
EXERCISE 4 ........................................................................................................................... 31
Decision making structures require that the programmer specify one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be executed if the
condition is determined to be true, and optionally, other statements to be executed if the condition
is determined to be false.
C programming language provides following types of decision making statements.
I. THE IF STATEMENT
C programming language assumes any non-zero and non-null values as true, and if it is either zero
or null, then it is assumed as false value.
Example
#include<stdio.h>
int main ()
{
int a =10; /* local variable definition */
if( a <20) /* check the boolean condition using if statement */
{
printf("a is less than 20\n");/* if condition is true then print the following */
}
printf("value of a is : %d\n", a);
return0;
}
When the above code is compiled and executed, it produces the following result:
a is less than 20; value of a is : 10
I.2 The if-else statement [See Activity 4.2] [See Activity 4.3]
An if statement can be followed by an optional else statement, which executes when the boolean
expression is false.
if(boolean_expression)
{
statements_if_expression_true;
}/* statement(s) will execute if the boolean expression is true */
else
{
statements_if_expression_false;
}/* statement(s) will execute if the boolean expression is false */
If the boolean expression evaluates to true, then the if block of code will be executed, otherwise
else block of code will be executed.
Flow Diagram
Example
#include<stdio.h>
int main ()
{
int a =100; /* local variable definition */
if( a <20) /* check the boolean condition */
{
printf("a is less than 20\n");/* if condition is true then print the following */
}
else
{
printf("a is not less than 20\n");/* if condition is false then print the following */
}
printf("value of a is : %d\n", a);
return0;
}
When the above code is compiled and executed, it produces the following result:
a is not less than 20; value of a is : 100
Let’s consider a program displaying the student’s grade based on the following table:
Marks Grade
>=75 A
>=50 and < 75 B
>=25 and <50 C
<25 F
In this case multiple conditions are to be checked. Marks obtained by a student can only be one of
the ranges. Therefore, if-else-if can be used to implement the following program.
/* Distribution of grade */
#include<stdio.h> This is an example of execution screen
main()
{
float marks;
printf(“Enter marks: “);
scanf(“%f”,&marks);
if (marks >= 75)
printf(“\nYour grade is A”);
else if (marks >=50)
printf(“\nYour grade is B”);
else if (marks >=25)
printf(“\nYour grade is C”);
else if (marks < 25)
printf(“\nYour grade is F”);
return 0;
}
The general syntax of an if-else-if ladder is
if(boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
}
elseif( boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
}
elseif( boolean_expression 3)
{
/* Executes when the boolean expression 3 is true */
}
else
{
/* executes when the none of the above condition is true */
}
It is always legal in C programming to nest if-else statements, which means you can use one if or
else if statement inside another if or else if statement(s).
if( boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
if(boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
}
}
You can nest else if...else in the similar way as you have nested if statement.
Example
#include<stdio.h>
int main ()
{
int a =100;int b =200; /* local variable definition */
if( a ==100) /* check the boolean condition */
{
if( b ==200) /* if condition is true then check the following */
{
printf("Value of a is 100 and b is 200\n");
}
}
printf("Exact value of a is : %d\n", a );
printf("Exact value of b is : %d\n", b );
return0;
}
When the above code is compiled and executed, it produces the following result:
A switch statement allows a variable to be tested for equality against a list of values. Each value
is called a case, and the variable being switched on is checked for each switch case. The syntax is
switch(expression){
case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */
Example
#include<stdio.h>
int main ()
{
char grade ='B'; /* local variable definition */
switch(grade)
{
case'A':
printf("Excellent!\n");
break;
case'B':
case'C':
printf("Well done\n");
break;
case'D':
printf("You passed\n");
break;
case'F':
printf("Better try again\n");
break;
default:
printf("Invalid grade\n");
}
printf("Your grade is %c\n", grade );
return0;
}
When the above code is compiled and executed, it produces the following result:
Well done
Your grade is B
Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.
The value of a ? expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is
evaluated and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is
evaluated and its value becomes the value of the expression.
EXERCISE 4
Exercise 4.1: Write a program which verifies whether a number entered is odd or even.
Exercise 4.3: Write a C code that returns the sign of a multiplication of A and B without doing the
multiplication.
Exercise 4.4: Write a program which consists to say whether a student has passed a test or he has
failed, being given an average. The student has passed if the average is greater than 12.00
Exercise 4.6: A car increases it velocity from u ms -1 to v ms-1 within t seconds. Write a program
to calculate the acceleration.
Exercise 4.7: Write a program that solve an equation of second degree (in the form ax2 + bx + c
= 0). The program receive the three coefficients a, b and c. (use the function sqrt() in the library
math.h to calculate the square root of a number)
a) Display either the real solution(s) or a message when the equation has no solution in
the set ℝ.
b) When there is not a real solution, display the complex solutions in form of x ± yi
Exercise 4.8: A year is a leap year if it is divisible by 4 unless it is a century year (one that ends
in 00) in which case it has to be divisible by 400. Write a program to read in a year and report
whether it is a leap year or not.
Exercise 4.11: Develop a simple calculator to accept two floating point numbers from the
keyboard. Then display a menu to a user and let him/her select a mathematical operation to be
performed on those two numbers. Then display the answer. A sample run of your program should
be similar to the following:
Challenges
Exercise 4.12: Build a number guessing game that uses input validation (isdigit() function) to
verify that the user has entered a digit and not a non-digit (letter). Store a random number between
1 and 10 into a variable each time the program is run. Prompt the user to guess a number between
1 and 10 and alert the user if he was correct or not.
Exercise 4.13: Build a Fortune Cookie program that uses either the Chinese Zodiac or astrological
signs to generate a fortune, a prediction, or a horoscope based on the user’s input. More
specifically, the user may need to input her year of birth, month of birth, and day of birth depending
on zodiac or astrological techniques used. With this information, generate a custom message or
fortune. You can use the Internet to find more information on the Chinese Zodiac or astrology.
Exercise 4.14: Create a dice game that uses two six-sided dice. Each time the program runs, use
random numbers to assign values to each die variable. Output a “player wins” message to the user
if the sum of the two dice is 7 or 11. Otherwise output the sum of the two dice and thank te user
for playing.
TOPIC 5
There may be a situation, when you need to execute a block of code several number of times. In
general, statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on.
A loop statement allows us to execute a statement or group of statements multiple times and
following is the general form of a loop statement in most of the programming languages
Objectives: At the end of this lesson, student should have mastered the following topics:
Contents_Toc400147248
I. FOR LOOP IN C ............................................................................................................. 34
II. WHILE LOOP IN C .................................................................................................... 36
III. DO...WHILE LOOP IN C ........................................................................................... 38
IV. NESTED LOOPS IN C ................................................................................................ 39
V. BREAK STATEMENT IN C ...................................................................................... 40
VI. CONTINUE STATEMENT IN C ............................................................................... 41
VII. GOTO STATEMENT IN C ..................................................................................... 42
VIII. THE INFINITE LOOP ............................................................................................ 44
EXERCISE 5 ........................................................................................................................... 44
I. FOR LOOP IN C
[See Activity 5.3]
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.
Flow Diagram
It is also possible to decrement the counter depending on the requirement, but one has to use
suitable control expression and an initial value.
Exercise:
The while loop checks whether the test expression is true or not. If it is true, code/s inside the
body of while loop is executed, is, code/s inside the braces { } are executed. Then again the test
expression is checked whether test expression is true or not. This process continues until the test
expression becomes false.
while(condition)
{
statement(s);
}
Here, statement(s) may be a single statement or a block of statements. The condition may be any
expression, and true is any nonzero value. The loop iterates while the condition is true.
When the condition becomes false, program control passes to the line immediately following the
loop.
Flow Diagram
Here, key point of the while loop is that the loop might not ever run. When the condition is tested
and the result is false, the loop body will be skipped and the first statement after the while loop
will be executed.
Programmer is responsible for initialization and incrementation. At some point in the body of
the loop, the control expression must be altered in order to allow the loop to finish. Otherwise:
infinite loop.
A for loop can be transformed into a while loop using the following rule:
for(expr1; expr2; expr3) expr1;
{ while(expr2)
statement {
} statement
expr3
} [See Activity 5.2]
The program above consisting to calculate the sum of all the even numbers up to 100 can be
rewritten using the while loop as follow:
#include<stdio.h>
main()
{
int i, sum;
sum = 0;
i = 0;
while(i <= 100)
{
sum += i;
i += 2;
}
printf(“total : %d”, sum);
return 0;
}
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to
execute at least one time.
Flow Diagram
Example
#include<stdio.h>
int main ()
{
int a =10;
do{
printf("value of a: %d\n", a);
a = a +1;
}while( a <20);
return 0;
}
When the above code is compiled and executed, it produces the following result:
A common use of the do while statement is input error checking. A simple form is shown here
do {
printf("\n Input a positive integer: ");
scanf("%d",&n);
} while (n<=0);
[See Activity 5.8]
The user will remain in this loop continually being prompted for and entering integers until a
positive one is entered. A sample session using this loop looks like this
Syntax
The syntax for a nested for loop statement in The syntax for a nested while loop statement
C is as follows: in C programming language is as follows:
The syntax for a nested do...while loop statement in C programming language is as follows:
do{
statement(s);
do{
statement(s);}
while( condition );
}while( condition );
A final note on loop nesting is that you can put any type of loop inside of any other type of loop.
For example, a for loop can be inside a while loop or vice versa.
Example
V. BREAK STATEMENT IN C
[See Activity 5.6]
The break statement in C programming language has the following two usages:
1. When the break statement is encountered inside a loop, the loop is immediately
terminated and program control resumes at the next statement following the loop.
2. It can be used to terminate a case in the switch statement (covered in the next chapter).
If you are using nested loops (i.e., one loop inside another loop), the break statement will stop
the execution of the innermost loop and start executing the next line of code after the block.
Flow Diagram
Example
For the “for loop”, “continue” statement causes the conditional test and increment portions of
the loop to execute. For the while and do...while loops, continue statement causes the program
control passes to the conditional tests.
Flow Diagram
Example
#include<stdio.h>
int main ()
{
int a =10;
do
{
if( a ==15)
{
a = a +1;
continue; /* skip the iteration */
}
printf("value of a: %d\n", a);
a++;
}while( a <20);
return0;
}
When the above code is compiled and executed, it produces the following result:
value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 16 value of
a: 17 value of a: 18 value of a: 19
goto label;
..
. label: statement;
Here label can be any plain text except C keyword and it can be set anywhere in the C program
above or below to goto statement.
Flow Diagram
Example
#include<stdio.h>
int main ()
{
int a =10;
LOOP:
do /* do loop execution */
{
if( a ==15) /* skip the iteration */
{
a = a +1;
goto LOOP;
}
printf("value of a: %d\n", a); a++;
}while( a <20);
return0;
}
When the above code is compiled and executed, it produces the following result:
value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 16 value of
a: 17 value of a: 18 value of a: 19
When the conditional expression is absent, it is assumed to be true. You may have an
initialization and increment expression, but C programmers more commonly use the for(;;)
construct to signify an infinite loop.
EXERCISE 5
Exercise 5.1: Write a program to compute the sum of all the integers from 1 to 100.
Exercise 5.2: Create a counting program that counts from 1 to 100 in increments of 5.
Exercise 5.3: Create a counting program that counts backward from 100 to 1in decrements of 10.
Exercise 5.4: Write the program to compute the sum of all integers between any given two
numbers.
Exercise 5.5: Write the program to calculate the factorial of any given factorial number.
Exercise 5.6: Create a counting program that prompts the user for three inputs (shown next) that
determine how and what to count. Store the user’s answers in variables. Use the acquired data to
build your counting program with a “for loop” and display the results to the user.
• Beginning number to start counting from
• Ending number to stop counting at
• Increment number
Exercise 5.7: Write a C code that permits the user to specify a number of lines or branches and
then prints on
a) the shell a triangular pyramid consisting of stars (picture 1 below).
b) A picture of a Christmas tree consisting of star (figure 2 below).
Hints: all characters are printed separately and both the number of stars per line and
the number of spaces per line must be calculated. The output will look like:
Exercise 5.8: Using a loop, ask the user to enter positive integer numbers. The program will output
the number of values entered, the minimum value, the maximum value and the average of all
numbers. The code will exit once a negative integer is entered.
Exercise 5.9: Write a program where the user supplies integer values between 1 and 9 and the
program returns the sum, average and RMS of the values. The program will exit when 0 is entered.
Values outside of the bounds will be discarded.
Exercise 5.10: Write a program that returns the number of years until a father will have an age
double of its son’s age.
Exercise 5.11: Write the C code that computes xn using the three loop functions (for, while and
do-while). We will consider n to be an integer.
Exercise 5.12: Write a program that tests if a positive integer is a prime number using a
straightforward approach. You will assume that your number is smaller than 1000.
Exercise 5.13: Write a C-program to display the message “God is love!” 100000 times. The
program should allow users to terminate the execution at any time by pressing any key before it
display all the 100000 messages. The C function kbhit() can be used to check for a keystroke. If
a key has been pressed, it returns the value “1” otherwise it returns “0”. The kbhit() function is
define in the header file conio.h
Exercise 5.14: a) Write a program to prompt the user for an integer and calculate the sum of all
the integers up to and including the input value. Print out the result.
b) Modify the previous program to use floating point arithmetic to add up the reciprocals of
all the integers up to and including the input value.
c) Further modify the previous program to print out a list of reciprocal sums for every integer
up to and including the input value.
I.e. print out the sum of the reciprocals of the integers up to and including 1, up to and
including 2, up to and including 3 etc., etc.
Exercise 5.15: A program consists to the following game: The machine guesses a number between
a given intervals and ask to the student to find it. The max, the min and the number of tries should
be defined as constant values (use #define). For any number guess by the user, the machine should
see whether the number is bigger or smaller than the searched number. The program stop when
the user actually guess the right number, in which case the sentence “Bravo you win in x tries” (x
to be given) is printed, or the maximum number of tries are reached, in which case the sentence
“Sorry exceeded number of tries, you failed” is printed. The output will look like
(Use the rand() function in the library “stdlib.h” to generate a random number.)
TOPIC 6
C and C++ come with a large library of useful functions (the standard ANSI C library plus several
C++ classes), but real programming pleasure comes with writing your own functions. This chapter
examines how to define functions, convey information to them, and retrieve information from
them. After reviewing how functions work, this chapter concentrates on how to use functions this
chapter touches on recursion to functions. If you’ve paid your C dues, you’ll find much of this
chapter familiar. But don’t be lulled into a false sense of expertise. Meanwhile, let’s attend to the
fundamentals.
Contents
I. INTRODUCTIVE TO FUNCTION (OR PROCEDURE) ........................................... 47
II. INTRODUCTION TO USER-DEFINED FUNCTIONS ......................................... 48
III. RECURSION ................................................................................................................ 51
IV. FUNCTION ARGUMENTS ....................................................................................... 52
EXERCISE 6 ........................................................................................................................... 54
We have already been exposed to functions. The main body of a C program, identified by the
keyword main, and enclosed by left and right braces is a function. It is called by the operating
system when the program is loaded, and when terminated, returns to the operating system. We
have also seen examples of library functions which can be used for I/O (stdio.h), like printf and
scanf, mathematical tasks (math.h), and character/string handling (string.h).
– Don’t have to repeat the same block of code many times in your code. Make that code
block a function and call it when needed.
– Function portability: useful functions can be used in a number of programs.
– Supports the top-down technique for devising a program algorithm. Make an outline and
hierarchy of the steps needed to solve your problem and create a function for each step.
– Easy to debug. Get one function working well then move on to the others..
– Easy to modify and expand. Just add more functions to extend program capability
– For a large programming project, you will code only a small fraction of the program.
– Make program self-documenting and readable
For the above defined function add(), following is the function declaration:
int add(int a, int b);
Parameter names are not important in function declaration only their type is required, so
following is also valid declaration:
int add(int , int );
where the return_type in the function header tells the type of the value returned by the
function (default is int)
where the data type variable name list tells what arguments the function needs when it is
called (and what their types are)
where local declarations in the function body are local constants and variables the function
needs for its calculations.
void write_header(void)
{
printf("*************************************************\n");
printf("** Welcome into this program? **\n");
printf("** Developed by your name **\n");
printf("** Upper Sixth science **\n");
printf("** PCHS MANKON-BAMENDA **\n");
printf("*************************************************\n");
}
The purpose of this function is just to display a menu on the screen, then it doesn’t need any
parameter and doesn’t return any value to the main. Here:
A function whose return type is different to void must contain the keyword return enabling to
return a value to the calling program.
When a return is encountered the following events occur: execution of the function is terminated
and control is passed back to the calling program, and the function call evaluates to the value of
the return expression.
The data type of the return expression must match that of the declared return_type for the function.
sum += power(x,i);
write_header(void)
Some points to keep in mind when calling functions (your own or library’s):
– The number of arguments in the function call must match the number of arguments in the
function definition.
– The type of the arguments in the function call must match the type of the arguments in the
function definition.
– The actual arguments in the function call are matched up in-order with the dummy
arguments in the function definition.
– The actual arguments are passed by-value to the function. The dummy arguments in the
function are initialized with the present values of the actual arguments. Any changes made
to the dummy argument in the function will NOTaffect the actual argument in the main
program.
III. RECURSION
[See Activity 6.5]
Recursion is the process in which a function repeatedly calls itself to perform calculations. Typical
applications are games and sorting trees and lists. Recursive algorithms are not mandatory,
usually an iterative approach can be found.
int factorial(int n)
{
int result;
if (n<=1)
result=1;
else
result=n*factorial(n-1);
return result;
}
If a function is to use arguments, it must declare variables that accept the values of the arguments.
These variables are called the formal parameters of the function.
The formal parameters behave like other local variables inside the function and are created upon
entry into the function and destroyed upon exit.
While calling a function, there are two ways that arguments can be passed to a function:
By default, C programming language uses call by value method to pass arguments. In general, this
means that code within a function cannot alter the arguments used to call the function. Consider
the function swap() definition as follows. Commented [F1]:
Now, let us call the function swap() by passing actual values as in the following example:
#include<stdio.h>
void swap(int x,int y); /* function declaration */
int main ()
{
int a =100;int b =200; /* local variable definition */
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
swap(a, b); /* calling a function to swap the values */
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
return0;
}
Let us put above code in a single C file, compile and execute it, it will produce the following
result:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200
Which shows that there is no change in the values though they had been changed inside the
function.
The call by reference method of passing arguments to a function copies the address of an argument
into the formal parameter. Inside the function, the address is used to access the actual argument
used in the call. This means that changes made to the parameter affect the passed argument.
To pass the value by reference, argument pointers are passed to the functions just like any other
value. So accordingly you need to declare the function parameters as pointer types as in the
following function swap(), which exchanges the values of the two integer variables pointed to by
its arguments.
#include<stdio.h>
void swap(int*x,int*y); /* function declaration */
int main ()
{
int a =100;int b =200; /* local variable
definition */
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
/* calling a function to swap the values.
* &a indicates pointer to a ie. address of variable a and
* &b indicates pointer to b ie. address of variable b. */
swap(&a,&b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
return0;
}
Let us put above code in a single C file, compile and execute it, it will produce the following result:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100
Which shows that there is no change in the values though they had been changed inside the
function.
EXERCISE 6
Exercise 6.1: Write a function which take a real number and return its absolute value. Write a
program which use the function
Exercise 6.2: Write two C functions that compute f(x)=2.3*x and g(x,y)=x*y.
Exercise 6.3: Write a function that returns 1 if an integer number is prime, 0 otherwise. Use that
function to write a C program which display the list of prime number below a given integer n.
Exercise 6.4: Write a C function facto that computes the factorial of a number n (integer). The
factorial function is a typical recursive problem. Rewrite the equation defining the factorial
function in a recursive form. Write the recursive version of the code and call the function facto_rec.
Exercise 6.5: Write the function called pow to calculate xn for any real number x and integer n.
Rewrite it in its recursive form and write the associate C function that you will call pow_rec.
𝒙𝒏
Exercise 6.6: The Taylor expansion of the exponential function is given by 𝒆𝒙 = ∑∞
𝒏=𝟎 . Using𝒏!
the previous exercises (function facto and pow), write a C functions that calculates the exponential
for integer values of x. Compare its results to the results of the C exponential function defined in
<math.h>.
Exercise 6.7: Write a program that repeatedly asks the user to enter pairs of numbers until at least
one of the pair is 0. For each pair, the program should use a function to calculate the harmonic
mean of the numbers. The function should return the answer to main(), which should report the
result. The harmonic mean of the numbers is the inverse of the average of the inverses and can be
calculated as follows: harmonic mean of x and y = 2.0 × x × y / (x + y)
Exercise 6.8: Write a function which generate 50 integers between 1 and 100 randomly and do
the follow. It calculates the factorial of each number divisible by 5 of and the inverse of each
number divisible by 6. You must use two functions facto and inverse to calculate the factorial and
the inverse of any number. Static variables should be used in those functions to count the number
of time each of them has been called.
Exercise 6.9: Write a function that takes three arguments: the name of an int array, the array size,
and an int value. Have the function set each element of the array to the int value.
Exercise 6.10: Write a program that asks the user to enter up to 10 golf scores, which are to be
stored in an array. You should provide a means for the user to terminate input prior to entering 10
scores. The program should display all the scores on one line and report the average score. Handle
input, display, and the average calculation with three separate array-processing functions.
Exercise 6.11: Write a function that takes three arguments: a pointer to the first element of a range
in an array, a pointer to the element following the end of a range in an array, and an int value. Have
the function set each element of the array to the int value.
Exercise 6.12: Write a function that takes a double array name and an array size as arguments and
returns the largest value in that array. Note that this function shouldn’t alter the contents of the
array.
TOPIC 7
Your fame as a programmer is now beginning to spread far and wide. The next person to come
and see you is the chap in charge of the local cricket team. He would like to you write a program
for him which allows the analysis of cricket results. What he wants is quite simple; given a list of
cricket scores and their names he wants a list of them in ascending order. We will introduce in the
following topic the notions of arrays, string and pointers.
Objectives: At the end of this lesson, student should have mastered the following sub-topics:
- Declaration and initialization an array, string and pointer
- Character and string functions
- Pointers and arrays
Contents
I. ARRAY ............................................................................................................................. 56
II. TWO-DIMENSIONAL ARRAYS .............................................................................. 58
III. STRING......................................................................................................................... 60
IV. POINTER...................................................................................................................... 65
EXERCISE 7 ........................................................................................................................... 70
I. ARRAY
[See Activity 7.1]
I.1. Introduction to Array Variables
C programming language provides a data structure called array, which can store a fixed-size
sequential collection of elements of the same type. An array is used to store a collection of data,
but it is often more useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables. A specific element in an array is accessed by an
index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first
element and the highest address to the last element.
I.2 Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the number of
elements required by an array as follows:
This is called a single-dimensional array. The arraySize must be an integer constant greater than
zero and type can be any valid C data type. For example, to declare a 10element array called
balance of type double, use this statement:
double balance[10];
Now balance is a variable array which is sufficient to hold up-to 10 double numbers.
The number of values between braces { } can not be larger than the number of elements that we
declare for the array between square brackets [ ]. Following is an example to assign a single
element of the array:
If you omit the size of the array, an array just big enough to hold the initialization is created.
Therefore, if you write:
You will create exactly the same array as you did in the previous example.
balance[4] = 50.0;
The above statement assigns element number 5th in the array a value of 50.0. Array with 4th
index will be 5th i.e. last element because all arrays have 0 as the index of their first element
which is also called base index. Following is the pictorial representation of the same array we
discussed above:
The above statement will take 10th element from the array and assign the value to salary
variable. Following is an example which will use all the above mentioned three concepts viz.
declaration, assignment and accessing arrays:
#include <stdio.h>
int main ()
{
int n[ 10 ]; /* n is an array of 10 integers */
int i,j;
/* initialize elements of array n to 0 */
for ( i = 0; i < 10; i++ )
{
n[i] = i + 100; /* set element at location i to i + 100 */
}
/* output each array element's value */
for (j = 0; j < 10; j++ )
{
printf("Element[%d] = %d\n", j, n[j] );
}
return 0;
}
Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where a is
the name of the array, and i and j are the subscripts that uniquely identify each element in a.
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2
*/
};
The nested braces, which indicate the intended row, are optional. The following initialization is
equivalent to previous example:
#include <stdio.h>
int main ()
{
/* an array with 5 rows and 2 columns*/
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
int i, j;
/* output each array element's value */
for ( i = 0; i < 5; i++ )
{
for ( j = 0; j < 2; j++ )
{
printf("a[%d][%d] = %d\n", i,j, a[i][j] );
}
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
Assignment
III. STRING
[See Activity 7.3]
III.1 Introduction and declaration
The string in C programming language is actually a one-dimensional array of characters which is
terminated by a null character '\0'. Thus a null-terminated string contains the characters that
comprise the string followed by a null.
The following declaration and initialization create a string consisting of the word "Hello". To hold
the null character at the end of the array, the size of the character array containing the string is one
more than the number of characters in the word "Hello".
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
If you follow the rule of array initialization then you can write the above statement as follows:
char greeting[] = "Hello";
Actually, you do not place the null character at the end of a string constant. The C compiler
automatically places the '\0' at the end of the string when it initializes the array. Let us try to print
above mentioned string:
#include <stdio.h>
int main ()
{
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
printf("Greeting message: %s\n", greeting );
return 0;
}
III.2 Initializing Strings
Initializing a string can be done in three ways:
a. at declaration,
b. by reading in a value for the string, and
c. by using the strcpy function. Direct initialization using the = operator is invalid. The
following code would produce an error:
char name[34];
name = "Erickson"; /* ILLEGAL */
To read in a value for a string use the %s format identifier: scanf("%s",name);
Note that the address operator &is not needed for inputting a string variable (explained later).
The end-of-string character will automatically be appended during the input process.
III.3 Copying Strings
The strcpy function is one of a set of built-in string handling functions available for the C
programmer to use. To use these functions be sure to include the string.h header file at the
beginning of your program. The syntax of strcpy is
strcpy(string1,string2);
When this function executes, string2 is copied into string1at the beginning of string1. The previous
contents of string1 are overwritten. In the following code, strcpy is used for string initialization:
#include <string.h>
main ()
{
char job[50];
strcpy(job,"Professor");
printf("You are a %s \n",job);
return 0;
}
#include <stdio.h>
#include <string.h>
int main ()
{
char str1[12] = "Hello";
char str2[12] = "World";
char str3[12];
int len ;
strcpy(str3, str1); /* copy str1 into str3 */
printf("strcpy( str3, str1) : %s\n", str3 );
strcat( str1, str2); /* concatenates str1 and str2 */
printf("strcat( str1, str2): %s\n", str1 );
len = strlen(str1); /* total lenghth of str1 after
concatenation */
printf("strlen(str1) : %d\n", len );
return 0;
}
Examples: Here are some examples of string functions in action:
char s1[]="big sky country";
char s2[]="blue moon";
char s3[]="then falls Caesar";
Function Result
strlen(s1) 15 /* e-o-s not counted */
strlen(s2) 9
strcmp(s1,s2) negative number
strcmp(s3,s2) positive number
strcat(s2,” tonight”) blue moon tonight
#include<ctype.h>
#include<stdio.h>
main()
{
char car;
do
{
printf("\nEnter an alphabetic character: ");
car=getchar();
if(isdigit(car)) printf("\nwrong: %c is a numeric character",car);
else if (ispunct(car)) printf("\nWrong: %c is a punctuation character",car);
else if (isspace(car)) printf("\nWrong: %c is a space character",car);
else if(!isalnum(car)) printf("\nWrong: %c is special character",car);
}while(!isalpha(car));
printf("\nWell done! %c is an alphabetic character", car);
if(islower(car)) printf("\n%c in uppercase is %c.",car, toupper(car));
if(isupper(car)) printf("\n%c in lowercase is %c.",car, tolower(car));
printf("\n");
return 0;
}
IV. POINTER
Some C programming tasks are performed more easily with pointers, and other tasks, such as
dynamic memory allocation, cannot be performed without using pointers. So it becomes
necessary to learn pointers to become a perfect C programmer. Let's start learning them in simple
and easy steps.
As you know, every variable is a memory location and every memory location has its address
defined which can be accessed using ampersand (&) operator, which denotes an address in
memory.
Consider the following example, which will print the address of the variables defined:
#include <stdio.h>
int main ()
{
int var1;
char var2[10];
printf("Address of var1 variable: %x\n", &var1 );
printf("Address of var2 variable: %x\n", &var2 );
return 0;
}
When the above code is compiled and executed, it produces result something as follows:
type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of
the pointer variable. The asterisk * you used to declare a pointer is the same asterisk that you use
for multiplication. However, in this statement the asterisk is being used to designate a variable as
a pointer. Following are the valid pointer declaration:
int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */
The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is
the same, a long hexadecimal number that represents a memory address. The only difference
between pointers of different data types is the data type of the variable or constant that the
pointer points to.
#include <stdio.h>
main()
{
int a=1,b=78,*ip;
ip=&a;
b=*ip; /* equivalent to b=a */
printf("The value of b is %d\n",b);
return 0;
}
Note that b ends up with the value of a but it is done indirectly; by using a pointer to a
#include <stdio.h>
int main ()
{
int var = 20; /* actual variable declaration */
int *ip; /* pointer variable declaration */
ip = &var; /* store address of var in pointer variable*/
printf("Address of var variable: %x\n", &var );
/* address stored in pointer variable */
printf("Address stored in ip variable: %x\n", ip );
/* access the value using the pointer */
printf("Value of *ip variable: %d\n", *ip );
return 0;
}
When the above code is compiled and executed, it produces result something as follows:
The NULL pointer is a constant with a value of zero defined in several standard libraries.
Consider the following program:
#include <stdio.h>
int main ()
{
int *ptr = NULL;
printf("The value of ptr is : %x\n", &ptr );
return 0;
}
When the above code is compiled and executed, it produces the following result:
On most of the operating systems, programs are not permitted to access memory at address 0
because that memory is reserved by the operating system. However, the memory address 0 has
special significance; it signals that the pointer is not intended to point to an accessible memory
location. But by convention, if a pointer contains the null (zero) value, it is assumed to point to
nothing.
What if we would like the function to change the main variable’s contents?
The classic example of “call-by-reference” is a swap function designed to exchange the values of
two variables in the main program. Here is a swapping program
#include <stdio.h>
void swap1(int p,int q);
void swap2(int *p,int *q);
main()
{
int i=3,j=9;
printf("before the 2 swaps, i=%d j=%d\n",i,j);
swap1(i,j);
printf("\nAfter swap1, i=%d j=%d\n",i,j);
swap2(&i,&j);
printf("\nAfter swap2, i=%d j=%d\n",i,j);
return 0;
}
void swap1(int p,int q)
{
int temp;
temp=p;
p=q;
q=temp;
}
void swap2(int *p,int *q)
{
int temp;
temp=*p;
*p=*q;
*q=temp;
}
Although this may seem strange at first, in C an array name is an address. In fact, it is the base
address of all the consecutive memory locations that make up the entire array.
We have actually seen this fact before: when using scanf to input a character string variable
called name the statement looked like
Illustration
EXERCISE 7
Exercise 7.1: Write a program which reads in 10 numbers and then prints them out in the reverse
order to that which they were entered in.
Exercise 7.2: Write code that reads a list of numbers from the keyboard, store the numbers in an
array, and then:
a) print out the array in reverse order
b) calculate the average of the numbers
c) print the index of the numbers that are below the average.
Exercise 7.3: Given a two-dimensional square array of integers, with size N * N, called
numTable, write code to:
a) Initialize the array by command-line inputs
b) Calculate the statistics of the average, the minimum, and the maximum of the array
c) Calculate the sum on both diagonals.
Exercise 7.4: Consider an array X of length 25. Use the function rand() to initialized randomly
the array. Write a program that returns the position and value of the minimum.
Exercise 7.5: Write code that creates a two-dimensional intarray of size M * N and set values for
it. Write code that first calculates the sum of every column, and then the sum of every row. Specify
you are printing row sums or column sums.
Exercise 7.6: Consider 2 three-dimensional vectors X and Y whose components are specified by
the user and stored in 1D arrays. Write the C code that calculates if the two vectors are orthogonal.
Exercise 7.7: Write a program to remove all specified characters from a string.
Exercise 7.9: Build a program that uses a single-dimension array to store 10 numbers input by a
user. After inputting the numbers, the user should see a menu with two options to sort and print
the 10 numbers in ascending or descending order.
Exercise 7.10: Write a code to insert a blank every fifth character in a string
Exercise 7.11: Create a program that performs the following functions:
• Uses character arrays to read a user’s name from standard input.
• Tells the user how many characters are in his or her name.
• Displays the user’s name in uppercase.
Exercise 7.12: Write a program that will output the characters of a string backwards. For example,
given the string “computer”, the program will produce “retupmoc”.
Exercise 7.13: Consider X and Y, two sorted arrays of integers. Write a C code that concatenates
the two tables into one table Z (sorted) which contains the elements of X and Y.
Exercise 7.14: Write a small C program that prints on the screen in uppercase a text supplied by
the user. The string will not be more than 80 characters in size.
Exercise 7.15: Given a string as input, write a function that counts the numbers, the lower case,
upper case and special characters.
Exercise 7.16: Using the integer representation of a character, write a function that replaces all the
lower case characters in a string by upper case characters.
Exercise 7.17: Define two integer arrays, each 10 elements long, called array1 and array2. Using
a loop, put some kind of nonsense data in each and add them term for term into another 10 element
array named arrays. Finally, print all results in a table with an index number, for example
1- 2 + 10 = 12
2- 4 + 20 = 24
3- 6 + 30 = 36 etc.
Exercise 7.19: Create a program that allows a user to select one of the following four menu
options:
• Enter New Integer Value
• Print Pointer Address
• Print Integer Address
• Print Integer Value
For this program you will need to create two variables: one integer data type and one pointer.
Using indirection, assign any new integer value entered by the user through an appropriate
pointer.
Exercise 7.20: Build a program that uses an array of strings to store the following names:
“Florida”, “Oregon”; “California”, “Georgia” Using the preceding array of strings, write your
own sort() function to display each state’s name in alphabetical order using the strcmp()
function.
Exercise 7.21: Define a character array and use strcpy to copy a string into it. Print the string out
by using a loop with a pointer to print out one character at a time. Initialize the pointer to the first
element and use the double plus sign to increment the pointer. Use a separate integer variable to
count the characters to print. Modify the program to print out the string backwards by pointing to
the end and using a decrementing pointer
TOPIC 8
In this tutorial you will learn about C Programming - Structures and Unions, initializing structure,
assigning values to members, functions and structures, passing structure to functions, passing
entire function to functions, arrays of structure, structure within a structure and union.
Structures are slightly different from the variable types you have been using till now. Structures
are data types by themselves. When you define a structure or union, you are creating a custom
data type.
Objectives: At the end of this lesson, student should have mastered the following topics:
- Declaration and initialization of structures
- Array of structures
- Structures and functions
- files
Contents
I. STRUCTURE .............................................................................................................. 73
II. ENUMERATION .................................................................................................... 78
III. UNION...................................................................................................................... 79
IV. TYPEDEF ................................................................................................................ 80
V. FILES ....................................................................................................................... 80
EXERCISE 8 ...................................................................................................................... 83
I. STRUCTURE
C arrays allow you to define type of variables that can hold several data items of the same kind
but structure is another user defined data type available in C programming, which allows you to
combine data items of different kinds.
Unlike arrays, structure must be defined first for their format that may be used later to declare
structure variables. Let us use an example to illustrate the process of structure definition and the
creation of structure variables.
Structures are used to represent a record, suppose you want to keep track of your books in a library.
You might want to track the following attributes about each book:
• Title
• Author
• Subject
• Book ID
To define a structure, you must use the struct statement. The struct statement defines a new
data type, with more than one member for your program. The format of the struct statement is
this:
The structure tag is optional and each member definition is a normal variable definition, such as
int i; or float f; or any other valid variable definition. At the end of the structure's definition,
before the final semicolon, you can specify one or more structure variables but it is optional.
Here is the way you would declare the Book structure:
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
} book;
The above is a declaration of a data type called student. It is not a variable declaration, but a type
declaration.
The keyword struct declares a structure to hold the details of four data fields,
Book_record is the name of the structure and is called the structure tag. The tag name may
be used subsequently to declare variables that have the tag’s structure.
title, author, nb, and price are different fields of the structure. These fields are called
structure elements or members. Each member may belong to different type of data.
You can declare a structure type and variables simultaneously. Consider the following declaration:
Struct book_record
{
char title[20];
char author[15];
int nb;
float price;
} book1, book2, book3;
To access the members of a structure, you use the “”.”” (scope resolution) operator. Shown
below is an example of how you can accomplish initialization by assigning values using the
scope resolution operator:
The above declaration will create a struct book_record called book1 with a title “Quick Mastery”,
the author “Bennett CHAH”, 145 exemplars at 3500 frs.
#include<stdio.h>
#include<stdlib.h>
main()
{
struct book_record
{
char title[20];
char author[15];
int nb;
float price;
};
struct book_record book1;
printf("\nEnter the title of the book: ");
gets([Link]);
printf("\nWho is the author of that book? ");
gets([Link]);
printf("\nHow much is the book? ");
scanf("%f",&[Link]);
printf("\nHow many examplars is available? ");
scanf("%d",&[Link]);
printf("\nThe book entitled %s, written by %s cost %.2f Fcfa. %d examplars are still
available\n", [Link],[Link],[Link],[Link]);
system("pause");
}
II. ENUMERATION
enum data types are data items whose values may be any member of a symbolically declared set
of values. A typical declaration would be.
enum days {Mon, Tues, Weds, Thurs, Fri, Sat, Sun};
This declaration means that the values Mon...Sun may be assigned to a variable of type enum
days. The actual values are 0...6 in this example and it is these values that must be associated
with any input or output operations. For example the following program produced the following
output: start = 2 end = 5
#include <stdio.h>
enum days {Mon, Tue, Wed, Thu, Fri, Sat, Sun };
main()
{
enum days start, end;
start = Wed;
end = Sat;
printf ("start = %d end = %d\n",start,end);
getchar();
}
Each value of the enumerated type list is given an int value. If no extra information is provided
by the programmer, the values start at zero and increase by one from left to right. The value of
any constant in the enumeration list can be set by the programmer; subsequent enumeration
constants will be given values starting from this value. There is no need for the values given to
the enumeration constants to be unique.
The following (non-sensical) code fragment illustrates these three points:
enum day { sun=1, mon, tues, weds, thur, fri=1, sat } d1;
the values of the enumeration constants will be:
sun 1,mon 2,tues 3,weds 4,thurs 5,fri 1,sat 2
III. UNION
Unions and Structures are identical in all ways, except for one very important aspect. Only one
element in the union may have a value set at any given time. Everything we have shown you for
structures will work for unions, except for setting more than one of its members at a time. For
example, the following code declares a union data type called intfloat and a union variable called
proteus:
union intfloat
{
floatf;
inti;
};
union intfloat proteus;
Once a union variable has been declared, the amount of memory reserved is just enough to
be able to represent the largest member. (Unlike a structure where memory is reserved for
all members).
In the previous example, 4 bytes are set aside for the variable proteus since a float will take
up 4 bytes and an int only 2 (on some machines).
Data actually stored in a union’s memory can be the data associated with any of its
members. But only one member of a union can contain valid data at a given point in the
program.
It is the user’s responsibility to keep track of which type of data has most recently been
stored in the union variable.
The following code illustrates the chameleon-like nature of the union variable Proteus
defined earlier
#include <stdio.h>
main() {
union intfloat {
float f;
int i;
} proteus;
proteus.i=4 /* Statement 1 */
printf(“i:%d f:%f\n”,proteus.i,proteus.f);
proteus.f=4.0; /* Statement 2 */
printf(“i:%d f:%f\n”,proteus.i,proteus.f);
}
After Statement 1, data stored in proteus is an integer the float member is full of junk.
After Statement 2, the data stored in proteus is a float, and the integer value is meaningless
IV. TYPEDEF
It is possible to create new names for existing types with typedef . This is frequently used to give
shorter or less complicated names for types, making programming safer and hopefully easier.
The use of typedef is a simple macro-like facility for declaring new names for data types,
including user-defined data types. Typical examples are shown below :-
typedef long BIGINT;
typedef double REAL;
typedef struct point
{
double x;
double y;
} POINT;
Given the above declarations, it would be possible to write the following declarations:
POINT a,b,c;
REAL a1,a2;
V. FILES
So far, all the output (formatted or not) in this course has been written out to what is called standard
output (which is usually the monitor). Similarly all input has come from standard input (usually
associated with the keyboard).
The C programmer can also read data directly from files and write directly to files. To work with
files, the following steps must be taken:
Data structure of a file is defined as FILE in the library of standard I/O function definitions.
Therefore all files should be declared as type FILE before they are used. FILE is a defined data
type. Constants such as FILE, EOF and NULL are defined in <stdio.h>. The following is the
general format for declaring and opening a file:
FILE *fp;
fp = fopen(“filename”, “mode”);
“r+” the existing file is opened to the beginning for both reading and writing.
“w+” same as w except both for reading and writing.
“a+” same as a except both for reading and writing.
The following useful table lists the different actions and requirements of the different modes for
opening a file:
The functions fprintf and fscanf are provided by C to perform the analogous operations for the
printf and scanf functions but on a file.
Opening a file for reading requires that the file already exist. If it does not exist, the file pointer
will be set to NULL and can be checked by the program.
fscanf(fp,"%f %d",&x,&m);
When a file is opened for writing, it will be created if it does not already exist and it will be reset
if it does, resulting in the deletion of any data already there. Using the w indicates that the file is
assumed to be a text file.
The Standard I/O Library provides similar routines for file I/O to those used for standard I/O.
The routine getc(fp) is similar to getchar() and putc(c,fp) is similar to putchar(c).
Thus the statement c = getc(fp); reads the next character from the file referenced by fp and the
statement putc(c,fp); writes the character c into file referenced by fp.
Another useful function for file I/O is feof() which tests for the end-of-file condition. feof takes
one argument -- the FILE pointer -- and returns a nonzero integer value (TRUE) if an attempt has
been made to read past the end of a file. It returns zero (FALSE) otherwise. A sample use:
if (feof(fp))
printf ("No more data \n");
EXERCISE 8
Exercise 8.2: Create a structure called car with the following members:
• make
• model
• year
• miles
a) Create an instance of the car structure named myCar and assign data to each of the
members. Print the contents of each member to standard output using the printf()
function.
b) Using the car structure from challenge number one, create a structure array with three
elements named myCars. Populate each structure in the array with your favorite car
model information. Use a for loop to print each structure detail in the array.
struct comp
{
double real;
double imag;
};
Use the following prototypes to write the corresponding function
a) void printcomp(struct comp a); to print a complex number in the form x+yi
b) int mod(struct comp a); To calculate the modulus of a given complex number a
c) int compare(struct comp a, struct comp b); to compare two complex numbers
d) struct comp add(struct comp a, struct comp b); to add two complex numbers
e) struct comp add(struct comp a, struct comp b); to multiply two complex numbers
Write a main program to use these functions. A menu should be displayed to enable the user choosing the
operation he wants to perform
Struct point
{
Float x;
Float y;
}
Write a function enable you to:
a) Calculate the distance between two points
b) Calculate the coordinate of vertor AB given 2 points A and B
c) Make a translation of a point by a vector
Exercise 8.5: Write a simple database program that will store students’ information such as name, age,
mark and grade. The following instructions should be followed:
mark grade
>= 80 A
<80 and >=60 B
<60 and >=40 C
<40 F
The write codes to perform the following
a) Calculate the mark average of all the student
b) Determine the first and the last student
c) Display the students who have passed knowing that a student has passed if he has at least 60/100
d) Given a student name display his details if the name exist in the database
Exercise 8.6: Let’s consider the following code fragment. It show how a program might check if a file
could be opened appropriately. The function exit() is a special function which terminates your program
immediately.
fp = fopen (filename, “r”) ;
if ( fp == NULL)
{
printf(“Cannot open %s for reading \n”, filename );
exit(1) ; /*Terminate program: Commit suicide !!*/
}
a) Modify the code so that the a valid name of file should be entered before the execution of
the program continue
b) Modify the above code fragment to allow the user 3 chances to enter a valid filename. If a
valid file name is not entered after 3 chances, terminate the program.
Exercise 8.7: Write a program to count the number of lines and characters in a file.
Note: Each line of input from a file or keyboard will be terminated by the newline character ‘\n’.
Thus by counting newlines we know how many lines there are in our input.
Exercise 8.8: Write a program to display file contents 20 lines at a time. The program pauses after
displaying 20 lines until the user presses either Q to quit or Return to display the next 20 lines. The
following algorithm can be used
Exercise 8.9: Write a file copy program which copies the file “prog.c” to “[Link]”
Outline solution:
The step: “Read characters .... and write ..” may be refined to:
read character from prog.c
while not end of file do
begin
write character to [Link]
read next character from prog.c
end
Exercise 8.10: The following simple structure declarations might be found in a graphics environment.
struct point
{
double x;
double y;
};
struct circle
{
double rad;
struct point cen;
};
With the declarations given above write simple C function to
a) Calculate the area of a circle
b) Determine whether a given point lay inside a circle
Exercise 8.11: Write a program to compare two files specified by the user, displaying a message
indicating whether the files are identical or different. This is the basis of a compare command provided
by most operating systems. Here our file processing loop is as follows:
Exercise 8.12: By using the structure point defined in exercise 4, consider the following
structure
struct line
{
struct point start;
struct point end;
};
Using the structure above, write a code to determine if two lines are
a) Parallel
b) Perpendicular
Exercise 8.13: Redo exercise 5 using a file to store the database. A menu should be prompted to
the user to choose the operation to do
a) Display the detail of the database
b) Add a record to the database
c) Give the number of records of the database
d) Calculate the mark average of all the student
e) Etc,
BIBLIOGRAPHY