C - Lecture I - IV
C - Lecture I - IV
C - Lecture I - IV
1.0 INTRODUCTION
1.2 C Programming
C is a general purpose programming language. Just like any other high-level language it is
used for solving problems through a computer. Before a problem is put on a computer for
solution, several tasks have to be carried out. These tasks may include but not limited to:
Identifying the problem variables and their nature
Specifying the objectives and scope of the problem and its solution requirements
Constructing the necessary mathematical models (if needed) to depict the different
problem as accurate as possible.
Writing the program.
Compiling the program
The program written in C or any other high-level language is called the source program (or
source code). The translated program in machine code, which is the one actually operated by
the computer, is called the object program (or object code). The process of translation is
called compiling the program or compilation.
C programming was originally designed for and implemented on the UNIX Operating System
but it is not tied to any hardware or system. It can run on IBM machines, IBM compatibles and
other systems. Compilers exist for different kinds of machines.
1
Definition 1:
Definition 2:
A programming language is an english-like language that you use to write your
computer programs.
There are many programming language, the most common ones are:
o FORTRAN
o COBOL
o BASIC
o Pascal
o C
o C++
o Java
Definition 3:
A compiler translates a computer program written in programming language into a
form that a computer can execute.
C is probably the most popular and widely used programming Language because it
gives maximum control and efficiency to the programmer.
Benefits you gain from learning C programming are:
o Be able to read and write code for the largest number of platforms (i.e.
everything from micro controllers to nearly all modern operating systems)
o The jump to the object oriented (C++) language becomes much easier. C++ is
an extension of C.
o Once you know C and C++ then Java can easily be learnt. Java is built upon
C++.
2
1.3 Solving a Problem Using a Program
It is not always possible to solve real problem by closed form solution such as integral cos x-
sin x. The problem solving is a multi-process as shown in figure 1 below.
Real
Model Algorithm Programming
Problem
As seen in figure 1 above, a real problem is converted into a suitable mathematical model using
simplified assumptions. A particular algorithm is used to solve the problem and the algorithm
is programmed for a computer such that calculation may be performed. The computer gives
result in the form of the output. If some data is needed before the computation is done, the
process is called data input.
#include statements
function name()
{
Statement sequence
}
The include statements are statements written at the top of your program to incorporate some
standard library files which comes together with a C-compiler.
function name() this is a name of a function. All C programs consist of one or several
functions.
The opening brace “{” : This marks the beginning of statement sequence.
The close brace “}” : This represents the formal conclusion of the program.
3
1.5 Starting with C
Let us consider the following program that prints out the line “This is my first C- program”
save it as myfirstP
#include <stdio.h>
main()
{
printf(“This is my first C - program”);
}
If the program is wrongly typed, either it will not compile successfully or it will not run. If this
happens edit the program and correct the errors and then compile again.
Program analysis
The statement #include<stdio.h> causes the file stdio.h to be read by the C compiler
and be included in the program. It is one of the standard library files and contains information
related to the printf() function.
The statement main() is the main function. All C programs must have a main function.
The character “;” is used as a statement terminator. It indicates the end of a statement. Every
statement must be ended by a semicolon.
Exercise 1
Q1. Write a simple code to print your name. Save the file as MyFirstname
Q2. Write a program to display First and Second names, Age, Gender and address in the
following format:
Name: Anderson James,
Age: 30yrs,
Address: P.O. Box 176,
City: IRINGA.
Hint: Use the code \n in your printif() function to indicate a request for a new
line e.g. printif (“Name: Anderson James.\n”);
Save the program as Myaddress
4
1.6 Variables and Variable Types
Definition:
A variable is a named memory location that may contain some value.
A variable is an identifier that is used to represent some specified type of information within a
designated portion of the program.
In C a variable represents a single data Item that can be a numeric quantity or a character
constant. The data item must be assigned to a variable at some point in the program. The data
item can be accessed later by referring to the variable name. A given variable can be assigned
different data items at various places within the program. The information represented by the
variable can change during the execution of the program. However, the data type associated to
the variable cannot change.
Variable Declarations
A declaration associates a group of variables with specific data type. All variables must be
declared before they can appear in executable statements.
A declaration consists of a data type followed by one or more variable names separated by a
comma and ending with a semi-colon.
Thus, a, b and c are declared to be integer variables and root1 and root2 are floating-point
variables.
In C, all variables must be declared before they can be used. A variable declaration
tells the compiler what type of variable is being used. C supports 5 different basic data
types:
Note:
In C a variable declaration is treated as a statement and it must end with a
semicolon (;). The programme may contain the following declarations:
e.g. int x; Here the variable x is declared as an integer data type
int y; Here the variable y is declared as an integer data type
5
float z; Here the variable z is declared as a floating point value
char ch; Here the variable ch is declared as a character data type
double d; Here the variable d is declared as a double precision data type
There are two places where variables are declared; inside a function, called local
variable or outside the function, called global variable.
A local variable is known to and may be accessed by only the function in which it is
declared. Local variables cease to exist once the function that created them is
completed. They are recreated each time a function is executed or called. Local
variables are sometimes called automatic variables.
A global variable can be accessed by any function in the program. These variables can
be accessed (i.e. known) by any function comprising the program. They are
implemented by associating memory locations with variable names. They do not get
recreated if the function is recalled.
C is case-sensitive; i.e. x and X are two completely different variables names
To assign the variables x and y some values, we write,
x = 10;
y = 20;
To assign the variable z and ch we write:
z = 5.6;
ch = „N‟;
Note that z being a floating point variable is assigned a real number (i.e. floating point
value 5.6, and
ch being a character variable data type is assigned a single character „N‟
enclosed in single quotes.
You can use printf() to display value of character integers and floating-point
values. e.g. printf(“The answer is %d”, 20);
Examples
1. This program declares a variable x as integer, assign it a value 10 and uses the
printf() function to display the statement “The value of x is 10”
(Save the program as OneInt)
#include <stdio.h>
main()
{
int x;
x = 10;
printf(“The value of x is %d”,x);
}
6
2. OneInt is modified to include one variable (Save the program as MoreInt)
The program declares a variables x and y as integers and assigns to them the values 10
and 2 respectively. It then uses the printf() function to display the statement
“The value of x is 10” and the statement “The value of y is 2”
#include<stdio.h>
main()
{
int x, y;
x = 10;
y = 2;
printf(“The value of x is %d”,x);
printf(“The value of y is %d”,y);
}
3. This program declares two different variables, count as integer, and y as float. The two
variables are assigned some values and hence displayed on a screen.
(Save the program as var.c)
#include <stdio.h>
main()
{
int count;
char ch;
float y;
count = 12;
y = 200.5;
printf (“This is CNN\n”);
printf(“with %d channels \n”, count);
printf (“pay $ %f for free installation”, y);
}
Exercise 2
Q1. Modify MoreInt and add another printf() so that it prints the value of x and y on
the same line.
i.e. printf(“The value of x is %d and y is %d”,x, y);
Q2. Write a program that declares one integer variable called num. Give this variable the
value 100 and then, using one printf() statement, display the value on the screen
as follows:
100 is the value of num.
(Save the program as num)
Q3. Write a program to display your name, age, gender, address and region. Use variables
for your age and gender. (Save the program as mycv)
7
1.7 Input Numbers from the Keyboard
There are several ways to input numeric values from the keyboard one of the easiest is
to use another C‟s standard library functions called scanf()
e.g. int num;
scanf(“%d”, &num);
where the “&” allows a function to place a value into one of its arguments.
Exercise 3
Q1. Write a program that will compute the area of a rectangle given its dimensions. Let the
program first prompts the user for the length and width of the rectangle and then display
the area. (Save the program as rectangle_area)
Q.2 Write a program that computes the area of a circle. Have the program prompt the user for
each dimension (Save the program as Circle).
Q.3 Write a program that computes the number of seconds in a year. (Save the program as
year.c)
Q.4 Write a program to compute the volume of a cylinder (Hint: use the mathematical model
v = r2h). (Save the program as cylinder)
1.8 Comments
Definition:
A comment is a note to yourself (or others) that you put into your source code.
Comments are used primarily to document the meaning and purpose of your source
code so that you can later remember the code.
In C, comments starts by the symbol /* and ended by the symbol */
e.g. / * This is a C comment */
Comments can extend over several lines.
e.g. /* This program computes
the area of a rectangle */
8
2.0 FUNCTIONS
Functions are the building blocks of C or block of statements that performs a specific
task. Most real world programs will contain many functions. Before we can use a
function, we define a function prototype.
A function prototype consists of a functions name, its return types and its parameter
lists. Examples of a function prototype are:
void myfunct(void);
int func(void);
void sum(int x, int y);
When you call a function, the compiler needs to know the type of data returned by that
function. If you use a function that is not prototyped, then the compiler will simply
assume that the returned value is an integer.
void is the return type, sum is a function name and int x, int y are parameters.
9
The only function that does not need a prototype is main() since it is predefined by
the C language.
When a function is called, execution transfers to that function. When a function ends,
execution resumes at the point in your program immediately following the call to the
function.
The value that a called function computes may be returned to the calling function by
using the return statement
A function need not return a value. A return statement with no expression causes
control, but no useful value to be returned to the caller.
Since main is a function like any other, it may return a value to its caller, which is in
effect the environment in which the program was executed.
A return value of zero implies normal termination. Non-zero values signal unusual or
erroneous termination condition
The function prototype declaration
means that power is a function that expects two int arguments and returns an int.
This declaration has to agree with the definition and uses of power.
Any function inside a program may call any other function within the same program
Traditionally, main() is not called by any other function.
Remember a function call is a statement, so a semicolon must terminate it.
Examples
Example 1
This program uses two functions, main() and funct1(). Also notice the usage of
comments (Save the program as Hello.c)
10
Note: This program will display:
Hello world. This is a program involving two functions
Example 2
/* A program that returns a value */
# include <stdio.h>
int funct(void); /*Function prototype*/
main( )
{
int num;
num = funct(); /* calling funct()*/
printf(“The number is %d”, num);
}
int funct(void) /* Called function */
{
return 10;
}
Note: In this program, funct() returns an integer value to the calling main()
function and 10 is assigned to num.
Definition:
A functions argument is a value that is passed to the function when the function is
called.
A function in C can have from zero to several arguments. (The upper limit is determined by
the compiler you are using, but the standard ANSI specifies that a function must be able to take
at least 31 arguments).
Examples
1. This program demonstrates the use of arguments and how to pass arguments to the called
function. (Save the program as argument.c)
#include <stdio.h>
void sum(int x,int y); /* The function sum() receives two integer values x and y */
main( )
{
sum(2, 20); /* sending 2 and 20 to sum ( ) as values of x and y respectively */
sum(40, 5);
}
void sum(int x, int y)
{
printf(“%d\n”, x + y);
}
11
Note: When sum() is called, the value of each argument is copied into its marching
parameter.
In the first call sum(2,20), 2 is copied into x and 20 into y, in the second call
sum(40,5), 40 is copied to x and 5 is copied to y.
Exercise 4
Q.1 The moons gravity is about 17% of the Earths gravity. Write a program that allows you
to enter your weight and computes your effective weight on the moon.
You may use only one function, i.e. main() or you may add another function dedicated
for computation) (save the program as gravity)
Q.2 Write a program to convert temperatures from degrees Fahrenheit to degree centigrade
[you may use the formula C = (5/9)(F – 32)]. Let the program prompts the user to input
values of Fahrenheit, F from the key board. Use only one main functions main. (Save the
program as degree)
Q.3 Modify question two (Q2) above using another function, other than main, to do the
conversion. (Save the program as degree_modified)
Q4. Write a program with two functions; the first one is the main(). This will prompt the
user to input radius of a sphere and the second one, myvol(), will calculate the volume
of a sphere and return a value to main() that will print the result. (Save the program as
Sphere_volume)
Q.5 Write a program that displays the square of a number entered from the keyboard.
The square number is computed using the function squared( ). (Save the program as
square)
#include<stdio.h>
float convert(void);
main()
{
float USD, TSH;
TSH = convert();
printf("USD %f = TSH %f",USD,TSH);
}
float convert()
12
{
float dollar;
printf("Enter amount in USD: ");
scanf("%f", &dollar);
return dollar * 2500;
}
Re-write the code so that it can work properly
More examples
1. To see how a function prototype can catch an error, try to compile this program
(save it as vol.cpp)
#include <stdio.h>
float volume(float S1, float S2, float S3);
main ()
{
float vol;
vol = volume (20.5, 5.5, 10.5, 15.5); /*error*/
printf(“Volume = %f”, vol);
}
/*compute volume*/
float volume(float S1 float S2, float S3)
{
return S1*S2*S3;
}
Note: This program will not compile because the volume () function is declared as having
only 3 parameters, but the program is attempting to call it with 4 parameters
2. Analyze the following program and state whether it is correct or not. If not state why?
#include<stdio.h>
foat myfunc( float num);
main()
{
printf(“%f”, myfunc(10.5);
}
float myfunc(float num);
{
return num * num;
}
13
Exercise 5
Q1. Write a program that uses a function called myvolume(), let the program compute the
volume of a cylinder from the formula v = πr2h. Have the main() function sends the
values of r and h to myvolume() which perform the calculation and return the result to
main to be displayed (Save the program as cylinder)
Q2. Write a program with two functions; the first one is the main( ). This will prompt the
user to input radius of a sphere and the second one, myvol( ), will calculate the volume of
a sphere and return a value to main( ) that will print the result.
(The Volume of a sphere is given by: 4/3 * π * r3 ) (Save the program as
SphereVolume)
14
3.0 CHARACTER SET
C uses Uppercase letters A to Z, the lowercase letters a to z, the digits 0 to 9, and certain
special characters as building blocks to form basic program elements, e.g. constants, variables,
operators and expressions
! * + \ “ <
# ( = | { >
„ ) ~ ; } /
@ - [ : , ?
& _ ] „ . (blank)
C uses combination of these characters such as \b, \n, and \t to represent special conditions as
shown below:
3.1 Identifiers
Identifiers
Identifies are names given to various program elements such as variables, function and arrays.
Identifiers consist of letters and digits, in any order, except that the first character must be a
letter. Lowercase and uppercase are permitted, though common usage favors the use of
lowercase letters. Upper and lower case letters are not inter changeable (i.e. an uppercase is
not equivalent to the corresponding lowercase) An underscore ( _ ) can also be included as it is
considered to be a letter, and can take any position, even though commonly is used in the
middle of an identifier. A character space is not used in identifier.
Examples:
The fallowing names are valid identifiers
x, y1, dog_1, _temperature
name, area, tax_rate, TABLE
The following names are not valid identifiers for the reasons stated.
1_day the first character must be a letter
“x” illegal character (“)
Order-no illegal character (-)
tax rate illegal character (blank space)
15
An identifier can be arbitrary long up to 31 characters. It is good practice, however, to use at
most 8 characters in an identifier.
As a rule an identifies should contain enough characters so that its meaning is readily apparent.
On the other hand excessive number of characters should be avoided.
3.2 Keywords
Keywords in C are reserved words that have standard pre-defined meaning. Keywords are
used for their intended purpose only, and can not be used as programmer-defined identifiers.
3.3 Constants
The C programming language has four basic types of constants. These are:
i) integer constants
ii) floating point constants
iii) character constants
iv) string constants
Integer and floating point constants represent numbers. They are both referred to as
numeric-type constants
A decimal integer constant can consist of any combination of digits 0 through 9. If the constant
contains two or more digits, the first digit must be something other than zero.
16
Valid decimal integer constants are shown below:
0. 1. 0.2 827.602
50000. 0.000743 12.3 315.0066
2E-8 0.006e-3 1.6667E+8
.12121212e12
The interpretation of a floating-point constant with exponent is essentially the same as for
scientific notation except that the base 10 is replaced by E (or e). Thus
Example 1
The quantity 3 x 105 can be reprinted in C by any of the following floating-point constants:
17
Example 2
The quantity 5.026 x 10-17 can be represented in C by any of the following floating-point
constants:
5.026E-17 .5026e-16 50.26e-18 0.0005026E –13
Example
The following are character constants and their corresponding values as defined by the ASCII
character set.
Constant Value
„A‟ 65
„X‟ 120
„5‟ 53
„$‟ 36
“ 32
18
3.5 ASCII Character Set
All personal computers make use of the American Standard Code for Information Interchange
(ASCII) character set, in which each individual character is numerically encoded with its own
unique 7-bit combination (Hence a total of 27 =128 different characters. The table 1 below
contains the ASCII character set.
19
4.0 OPERATORS
In C programming language we have five Arithmetic operators
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
Note: The modulo operator (%) can be used with integer types only
The modulus operator produces the remainder of an integer division
e.g. 5 % 2 = 1
4%2=0
Operator Meaning
> Greater than
>= Greater than or equal
< Less than
<= Less than or equal
== Equal
!= Not equal
The Logical Operators connect together true/false results and these are:-
Operator Action
&& AND
|| OR
! NOT
Practical examples on usage of relational and logical operators are covered in the next chapter
20
4.2 Order of Precedence
a+b*c
(a + b) * C
or
a + (b * c)
All operators have a priority. High priority operators are evaluated before lower priority ones.
Operators of the same priority are evaluated from left to right, so that
a - b - c
is evaluated as
( a - b ) - c
as you would expect.
From high priority to low priority, the order for all C operators is as given in the table below:
21
Suppose that x, y and z are variables which have been assigned the value 2, 3, and 4
respectively. Then the expression
x *= -2 * (y + z) / 3
x = (x * ( -2 * (y + z) / 3))
is interpreted as
(i) Expressions
An expression represents a single data item, such as number or a character. The expression
may consist of a single entity, such as a constant, a variable an array element or a reference to a
function. An expression may also consist of a combination of such entities connected by one
or more operators.
Expression can also represent logical conditions that are either TRUE or FALSE. In C the
conditions TRUE and FALSE are represented by the integer values 1 and 0, respectively.
22
Examples of expression
a + b
x = y
c = a + b
c == y
x <= y
++i
The third expression combines the features of the first two expressions. In this case the value
of the expression a + b is assigned to the variable c
The fourth expression is the test of equality. Thus, the expression will have the valve 1
(TRUE) if the value of x is equal to the value of y. Otherwise, the expression will have the
value 0 (FALSE).
The last expression causes the value of the variable 1 to be increased by 1. The expression.
++i
is thus equivalent to
i = i +1
23
(ii) Statements
A statement causes a computer to carry some action. There are three different types of
statements in C.
i. Expression statement
ii. Compound statement
iii. Control statement
a = 3;
c = a + b;
++i;
printf(“Area = %f”, area);
;
{
pi = 3.141593;
circumference = 2 * pi * radius;
area = pi * radius * radius;
}
Note that compound statement does not end with a semicolon after the brace.
Control statements are used to create special program features such as logical tests, loops and
branches. Many control statement require that other statements embedded within them as
shown in the example below:
24
Example
This statement consists of a compound statement, which in turn contains four expressions
statements. The compound statement will continue to execute as long as long as the value of
count does not exceed the value of n.
#define PI 3.141592
#define GOLDENRATIO 1.6
#define MAX 500
Exercise 6
Q.1 Summarizes the rules for naming identifiers. Are upper case letters equivalent to
lowercase letters?
Q.2 What are the keywords in C? What restrictions apply for their use?
Q.5 Describe two different ways that floating-point constants can be described?
Q.7 suppose a, b, and c are integer variables that have been assigned the values a = 8, b = 3
and c = -5. Determine the value of each of the following.
25
(a) a + b + c (b) 2 * b + 3 + (a – c) (c) a / b
(d) a % b (e) a * (c % b) (f)(a * c) % b
(g) a / c (h) a % c (i) a * b / c
Q. 9 Given
x = 1, y = 4, z=2
Determine the following.
x + y mod z * 5 – y
Q. 10 Given x = 4; b = 6, c=8
Deter Determine the value of the following:
(a +b * c) < (4 * 6+ 8)
26
Q. 13. Given x = TRUE
y = TRUE
z = FALSE
Find the value of the following:
(i) x && y
(ii) (x && y) && z
(iii) x && (y && z)
(iv) x < y ¦¦ y > z
(v) (x ¦¦ y) ¦¦ z
int i = 8, j =5, k;
float x = 0.005, y = -0.01, z;
char a, b, c = „c‟, d = „d‟;
Determine the value of each of the following:
(a) k = ( i + j) (b) z = k = x (c) i = j
(d) k = (x + y) (e) i = j = 1.1 (f) k = c
(g) z = i / j (h) i += 2 (i) i /= j
(j) i %= j (k) y - = x (l) i += (j - 2 )
27