0% found this document useful (0 votes)
3 views27 pages

ccs-2101-introduction-to-programming-in-c-notes-1-3-1

The document provides an introduction to programming in C, covering basic concepts such as programming languages, structured programming, and the steps involved in program development. It explains the C language's features, advantages, and components, including keywords, functions, and the standard library. Additionally, it discusses algorithms, flowcharts, and the importance of documentation in programming.

Uploaded by

meshackkibet8078
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
3 views27 pages

ccs-2101-introduction-to-programming-in-c-notes-1-3-1

The document provides an introduction to programming in C, covering basic concepts such as programming languages, structured programming, and the steps involved in program development. It explains the C language's features, advantages, and components, including keywords, functions, and the standard library. Additionally, it discusses algorithms, flowcharts, and the importance of documentation in programming.

Uploaded by

meshackkibet8078
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 27

lOMoARcPSD|48268036

CCS 2101 Introduction to Programming in C notes 1-3-1

MECHANICAL ENGINEERING (Dedan Kimathi University of Technology)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036

CHAPTER 1-BASIC CONCEPTS

Introduction
Literally speaking, a language is a vehicle of communication amongst human beings.
To communicate, a given procedure is followed which may normally be dictated by grammar.
A computer language is not very different. Computers do not understand any of the natural languages for
transfer of data and instructions. So there are languages specially developed so that you could pass your
data and instructions to the computer to do a specific job.

This chapter introduces structured approach to programming which the rest of this guide is all about. The
chapter also presents a quick overview of C language. The goal is to give you sufficient working
knowledge of C language so that you can understand more concrete concepts in later chapters.

Programming defined
Programming is the translation of user ideas into a representation or form that can be understood by the
computer. The tools of writing programs are called programming languages.

Programming language defined


A programming language is a set of rules used to write computer programs. Like human languages,
computer languages have a syntax which defines the language grammar.

Structured Programming defined


Structured programming is an approach to writing programs that are easier to read, test, debug and modify.
The approach assists in the development of large programs through stepwise refinement and modularity.
Programs designed this way can be developed faster. When modules are used to develop large programs,
several programmers can work on different modules, thereby reducing program development time.
In short, structured programming serves to increase programmer productivity, program reliability
(readability and execution time), program testing, program debugging and serviceability.

Steps in program development


a. Design program objectives-It involves forming a clear idea in terms of the information you want to
include in the program, computations needed and the output. At this stage, the programmer should
think in general terms, not in terms of some specific computer language.
b. Design program-The programmer decides how the program will go about its implementation, what
should the user interface be like, how should the program be organized, how to represent the data
and what methods to use during processing. At this point, you should also be thinking generally
although some of your decisions may be based on some general characteristics of the C language.
c. Develop the program-Developing a program in a compiled language such as C requires at least four
steps:
 Editing (or writing) the program
 Compiling it
 Linking it
 Executing it

Editing
You write a computer program with words and symbols that are understandable to human beings. This is
the editing part of the development cycle. You type the program directly into a window on the screen and
save the resulting text as a separate file. This is often referred to as the source file. The custom is that the
text of a C program is stored in a file with the extension .c for C programming language e.g. hello.c

1
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036

Compiling
You cannot directly execute the source file. To run on any computer system, the source file must be
translated into binary numbers understandable to the computer's Central Processing Unit. This process
produces an intermediate object file - with the extension .obj e.g hello.obj
Compiling
 Regardless of the HL Language, all HL programs need to be translated to machine code so
that a computer can process the program.
 Some programs are translated using a compiler. When programs are compiled, they are
translated all at once. Compiled programs typically execute more quickly than interpreted
programs, but have a slower translation speed.

Interpreting
 Some programs are translated using an interpreter. Such programs are translated line-by-line
instead of all at once (like compiled programs). Interpreted programs generally translate
quicker than compiled programs, but have a slower execution speed.

Linking
The main reason for linking is that many compiled languages come with library routines which can be
added to your program. Theses routines are written by the manufacturer of the compiler to perform a
variety of tasks, from input/output to complicated mathematical functions. In the case of C the standard
input and output functions are contained in a library (stdio.h) so even the most basic program will require a
library function. After linking, the file extension is .exe which is an executable file e.g. hello.exe

You can then run .exe files as you run applications, simply by typing their names at the DOS prompt or run
using Windows menu.

d. Test the program


This involves checking whether the system does what it is supposed to do. Programs may have bugs
(errors). Debugging involves the finding and fixing of program errors.

e. Maintain the program


Occasionally, changes become necessary to make to a given program. You may think of a better way to do
something in a program, a clever feature or you may want to adapt the program to run in a different
machine. These tasks are simplified greatly if you document the program clearly and follow good program
design practices.

Algorithm
 An algorithm is a procedure or formula for solving a problem.
 A specific set of instructions for carrying out a procedure or solving a problem, usually with the
requirement that the procedure terminate at some point.
 A set of instructions that leads to a predictable result
 An algorithm is programming language independent

An Algorithm to add two numbers:


 Read the Value of A and B.
 SUM = A+B.
 Display SUM.
 Stop.

Algorithm to multiply two numbers.

2
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036

 Read the Value of A and B.


 PRODUCT = A*B.
 Display PRODUCT.
 Stop.

Example
Write an algorithm to determine a student’s final grade and indicate whether it is pass or fail. The final
grade is calculated as the average of four marks. Fail is average below 50
 Start
 Step 1: Input M1,M2, M3, M4
 Step 2: GRADE = (M1+M2+M3+M4)/4
 Step 3: if (GRADE < 50) then Print “FAIL”
 Step 4: if (GRADE > 50) then Print “PASS”
 Stop

Characteristics of algorithm
i. Finiteness-An algorithm must terminate after a finite number of steps and further each step must be
executable in finite amount of time.
ii. Each step of an algorithm must be precisely defined; the action to be carried out must be rigorously
and unambiguously specified for each case.
iii. Input: An algorithm has zero or more, but only finite number of inputs.
iv. Output: An algorithm has one or more output.
v. Effectiveness: Should be effective that means each of the operation to be performed in an algorithm
must be sufficiently basic that it can, in principle, be done exactly and in a finite length of time, by
a person using pencil and paper and should be computer programming language independent

The Flowchart
A Flowchart
 shows logic of an algorithm
 emphasizes individual steps and their interconnections e.g. control flow from one action to the next

Basic Flow chart symbols:

3
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036

Example 1
Draw a flowchart to find the sum of the first 50 natural numbers.
Algorithm
 Start.
 Step 1: Initialize n and sum to zero (n=0; sum=0).
 Step 2: Add 1 to n (n=n+1).
 Step 3: Add n to sum (sum=sum + n).
 Step 4: Is n=50? If no go to step 2.
 Step 5: Print sum.
 Stop.

Flowchart

Example 2
Draw a flow chart to determine a student’s final grade and indicate whether it is fail or pass. The final
grade is calculated as the average of four marks. Fail is average below 50

Flow chart below

Advantages of Using Flowchart

4
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036

i. Communication: Flowcharts are better way of communicating the logic of a system to all
concerned.
ii. Effective analysis: With the help of flowchart, problem can be analyzed in more effective way.
iii. Proper documentation: Program flowcharts serve as a good program documentation, which is
needed for various purposes.
iv. Efficient Coding: The flowcharts act as a guide or blueprint during the systems analysis and
program development phase.
v. Proper Debugging: The flowchart helps in debugging process.

Limitations of using flowcharts


i. Complex logic: Sometimes, the program logic is quite complicated. In that case, flowchart
becomes complex and clumsy.
ii. Alterations and Modifications: If alterations are required the flowchart may require re-drawing
completely.
iii. The essentials of what is done can easily be lost in the technical details of how it is done.

C language basic features


C is a general-purpose language which has been closely associated with the Unix operating system for
which it was developed - since the system and most of the programs that run it are written in C. C supports
the traditional programming style of structured programming and is one of the most popular and certainly
the most powerful language in this class.
C is often referred to as a middle level language. This refers to the fact that C can be used to write low level
programs as well as high level languages. Low level languages are machine oriented but provide greater
efficiency than high level languages. High level languages provide various control structures, I/O
commands and so on which make programming easier and faster.
Before C, assembly languages were used to write computer programs. The shortcomings of the assembly
languages were one reason that C was initially designed.
It successfully combines the features of a high-level language and the power and efficiency of assembly
language.
Initially C was used for creating systems software. Systems software consists of those programs which help
run the computer. These include operating systems, compilers and editors. However, as C gained
popularity, it began to be used for general purpose programming. Today, C is used by programmers for
virtually any programming task.

Advantages of C Language
i. C Supports structured programming design features - It allows programmers to break down their
programs into functions. It also supports the use of comments, making programs readable and
easily maintainable.
ii. Efficiency - C is a concise language that allows you to say what you mean in a few words. The final
code tends to be more compact and runs quickly.
iii. Portability - C programs written for one system can be run with little or no modification on other
systems.
iv. Power and flexibility
Power - C has been used to write operating systems (such as Unix and Windows), Language
Compilers, Assemblers ,Text Editors, Print Spoolers, Network Drivers, Application packages (such
as WordPerfect and Dbase), Language Interpreters, Utilities, etc.
Flexibility-It has (and still is) been used to solve problems in areas such as physics and engineering.
v. Programmer orientation - C is oriented towards the programmer’s needs. It gives access to the
hardware. It lets you manipulate individual bits of memory. It also has a rich selection of operators
that allow you to expand programming capability.

5
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036

C Program components
Keywords
These are reserved words that have special meaning in a language. The compiler recognizes a keyword as
part of the language’s built – in syntax and therefore it cannot be used for any other purpose such as a
variable or a function name. C keywords must be used in lowercase otherwise they will not be
recognized.

Examples of keywords

A typical C program is made of the following components:


 Preprocessor directives
 Functions
 Declaration statements
 Comments
 Expressions
 Input and output statements

Example
This program will print out the message: This is a C program.
#include<stdio.h>
main()
{
printf("This is a C program\n");
return 0;
}

 #include<stdio.h> allows the program to interact with the screen, keyboard and file system of your
computer.
 main() declares the start of the function. This is the start point of the program.
 The two curly brackets ({ }) show the start and finish of the function. They are used to group
statements together as in a function, or in the body of a loop. Such a grouping is known as a compound
statement or a block.
 printf("This is a C program \n"); prints the words on the screen. The text to be printed is enclosed in
double quotes. The \n at the end of the text tells the program to print a new line as part of the output.

Most C programs are written in lower case letters. You will usually find upper case letters used in
preprocessor definitions (which will be discussed later) or inside quotes as parts of character strings.
C is case sensitive, that is, it recognizes a lower case letter and it's upper case equivalent as being different.

The following program demonstrates the C program components.


#include<stdio.h>
main()
{

6
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036

int num; /* define a variable called num */


num = 1; /* assignment */
printf(“This is a simple program ”);
printf(“to display a message. \n”);
printf (“My favorite number is %d because ”, num);
printf(“ it is first.\n ”);
return 0;
}

On running the above program, you get the following output.

Functions
All C programs consist of one or more functions, each of which contains one or more statements. In C, a
function is a named subroutine that can be called by other parts of the program. Functions are the building
blocks of C.

A statement specifies an action to be performed by the program. All C statements must end with a
semicolon.
Although a C program may contain several functions, the only function that it must have is main( ).

The main( ) function is the point at which execution of your program begins. That is, when your program
begins running, it starts executing the statements inside the main( ) function, beginning with the first
statement after the opening curly brace. Execution of your program terminates when the closing brace is
reached.
Another important component of all C programs is library functions. The ANSI C standard specifies a
minimal set of library functions to be supplied by all C compilers, which your program may use. This
collection of functions is called the C standard library. The standard library contains functions to perform
disk I/O (input / output), string manipulations, mathematics, and much more. When your program is
compiled, the code for library functions is automatically added to your program.
One of the most common library functions is called printf( ). This is C’s general purpose output function.
Its simplest form is
printf(“string – to – output”);

In C, one or more characters enclosed between double quotes is called a string. The quoted string between
printf( )’s parenthesis is called an argument to printf( ). In general, information passed to a function is
called an argument.

In the above program, line 6 causes the message enclosed in speech marks “ ” to be printed on the screen.
Line 7 does the same thing. The \n in line 7 tells the computer to insert a new line after printing the
message. \n is an example of an escape sequence.
Line 8 prints the value of the variable num (1) embedded in the phrase. The %d instructs the computer
where and in what form to print the value. %d is a type specifier used to specify the output format for
integer numbers.
Line 9 has the same effect as line 7.
Line11 indicates the value to be returned by the function main( ) when it is executed.

7
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036

By default any function used in a C program returns an integer value (when it is called to execute).
Therefore, line 2 could also be written int main( ). If the int keyword is omitted, still an integer is returned.
Then, why return (0); ? Since all functions are subordinate to main( ), the function does not return any
value.

Note
i) Since the main function does not return any value, line 3 can alternatively be written as : void
main( ) – void means valueless. In this case, the statement return 0; is not necessary.
ii) While omitting the keyword int to imply the return type of the main( ) function does not disqualify
the fact that an integer is returned (since int is default), you should explicitly write it in other
functions, especially if another value other than zero is to be returned by the function.

Preprocessor directives and header files


A preprocessor directive performs various manipulations on your source file before it is actually compiled.
Preprocessor directives are not actually part of the C language, but rather instructions from you to the
compiler
The preprocessor directive #include is an instruction to read in the contents of another file and include it
within your program. This is generally used to read in header files for library functions (See line 1 in
sample program above).
Header files contain details of functions and types used within the library. They must be included before
the program can make use of the library functions.
Library header file names are enclosed in angle brackets, < >. These tell the preprocessor to look for the
header file in the standard location for library definitions.

Comments
Comments are non – executable program statements meant to enhance program readability and allow
easier program maintenance, i.e. they document the program.
They can be used in the same line as the material they explain (see lines 4 and 5 in sample program).
A long comment can be put on its own line or even spread on more than one line.
Comments are however optional in a program. The need to use too many comments can be avoided by
good programming practices such as use of sensible variable names, indenting program statements, and
good logic design. Everything between the opening /* and closing */ is ignored by the compiler.

Declaration statements
In C, all variables must be declared before they are used. Variable declarations ensure that appropriate
memory space is reserved for the variables, depending on the data types of the variables. Line 4 is a
declaration for an integer variable called num.

Assignment and expression statements


An assignment statement uses the assignment operator “=” to give a variable on the operator’s left side the
value to the operator’s right or the result of the expression on the right. The statement num =1; (Line 5) is
an assignment statement.

Escape sequences
Escape sequences (also called back slash codes) are character combinations that begin with a backslash
symbol (\) used to format output and represent difficult-to-type characters.
One of the most important escape sequences is \n, which is often referred to as the new line character.

Below are other escape sequences:


Escape sequence Meaning
\a audible alert/bell

8
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036

\b backspace
\f form feed
\n new line
\v vertical tab
\t horizontal tab
\\ back slash ( \ )
\’ Single quote (‘)
\” Double quote (“ ”)
\0 null
\? Question mark (?)

Example
The program below displays the following output on the screen.

#include<stdio.h>
main()
{
printf(“This is line one \n”);
printf(“This is line two \n”);
printf(“This is line three”);
return 0;
}

Example
The program below sounds the bell.
#include<stdio.h>
main()
{
printf(“\a”);
return 0;
}
Remember that the escape sequences are character constants. Therefore to assign one to a character
variable, you must enclose the escape sequence within single quotes, as shown in this fragment.
char ch;
ch = ‘\t ’ /*assign ch the tab character */

Program errors and debugging


There are three types of errors: Syntax, Semantic and Logic errors.

Syntax errors
They result from the incorrect use of the rules of programming. The compiler detects such errors as soon as
you start compiling. A program that has syntax errors can produce no results. You should look for the error
in the line suggested by the compiler.
Syntax errors include;

9
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036

 Missing semi colon at the end of a statement e.g. Area = Base * Length
 Use of an undeclared variable in an expression
 Illegal declaration e.g. int x, int y, int z;
 Use of a keyword in uppercase e.g. FLOAT, WHILE
 Misspelling keywords e.g. init instead of int
Note
The compiler may suggest that other program line statements have errors when they may not. This will be
the case when a syntax error in one line affects directly the execution of other statements, for example
multiple use of an undeclared variable.
Declaring the variable will remove all the errors in the other statements.

Logic Errors
These occur from the incorrect use of control structures, incorrect calculation, or omission of a procedure.
Examples include: An indefinite loop in a program, generation of negative values instead of positive
values. The compiler will not detect such errors since it has no way of knowing your intentions. The
programmer must dry run the program so that he/she can compare the program’s results with already
known results.

Semantic errors
They are caused by illegal expressions that the computer cannot make meaning of.
Usually no results will come out of them and the programmer will find it difficult to debug such errors.
Examples include a data overflow caused by an attempt to assign a value to a field or memory space
smaller than the value it requires, division by zero, etc.

Guidelines to good C programming


 Ensure that your program logic design is clear and correct. Avoid starting to code before the logic is
clearly set out .Good logic will reduce coding time and result in programs that are easy to
understand, error free and easily maintainable.
 Declare all variables before using them.
 Use sensible names for variables. Use of general names such as n instead of net_sal for net salary
makes variables vague and may make debugging difficult.
 Use a variable name in the case that it was declared in.
 Never use keywords in uppercase.
 Terminate C declarations, expressions and input/output statements with a semi colon.
 Always save your program every time you make changes.
 Proof read your program to check for any errors or omissions
 Dry run you design with some simple test data before running the code, then compare the two.

Revision Exercise
1. Outline the logical stages of C programs’ development.
2. From the following program, suggest the syntax and logical errors that may have been made.The
program is supposed to find the square and cube of 5, then output 5, its square and cube.
#include<stdio.h>
main()
{
int, int n2, n3;
n = 5;
n2 = n *n
n3 = n2 * n2;
printf(“ n = %d, n squared = %d, n cubed = %d \ n”, n, n2, n3);
return 0;

10
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036

}
3. Give the meaning of the following, with examples
i) Preprocessor command
ii) Keyword
iii) Escape sequence
iv) Comment
v) Linking
vi) Executable file
4. C is both ‘portable’ and ‘efficient’. Explain.
5. C is a ‘case sensitive’ language. Explain.
6. The use of comments in C programs is generally considered to be good programming practice.
Why?

CHAPTER 2 - DATA HANDLING


Introduction
Almost every program you write performs some sort of data manipulation, however basic. These data are
stored and understood differently in your program depending on how you have defined them.
The aim of this chapter is to help you understand what is required to use data items in a C program.

Variables
A variable is a memory location whose value can change during program execution. In C, a variable must
be declared before it can be used. Variables can be declared at the start of any block of code.
A declaration begins with the data type, followed by the name of one or more variables.
That is:
datatype variable; or
datatype variable1,variable2,….variablen; (where there are n variables)
For example:
int high, low, results[20];

Declarations can be spread out, allowing space for an explanatory comment. That is:
Variables can also be initialised when they are declared. This is done by adding an equals sign and the
required value after the declaration.
int high = 250; /* Maximum Temperature */
int low = - 40; /* Minimum Temperature */
int results[20]; /* Series of temperature readings */

Variable names
Every variable has a name and a value. The name identifies the variable and the value stores data. There is
a limitation on what these names can be. Every variable name in C must start with a letter; the rest of the
name can consist of letters, numbers and underscore characters.
C recognizes upper and lower case characters as being different (C is case- sensitive).

Finally, you cannot use any of C's keywords like main, while, switch etc as variable names.

Examples of legal variable names

It is conventional to avoid the use of capital letters in variable names. These are used for names of
constants. The rules governing variable names also apply to the names of functions.

11
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036

Types of variables
There are two places where variables are declared: inside a function or outside all functions.
Global variables
Variables declared outside all functions are called global variables and they may be accessed by any
function in your program. Global variables exist the entire time your program is executing.
Local variables
Variables declared inside a function are called local variables. A local variable is known to and may be
accessed by only the function in which it is declared. You need to be aware of two important points about
local variables.
i) The local variables in one function have no relationship to the local variables in another function.
That is, if a variable called count is declared in one function, another variable called count may
also be declared in a second function – the two variables are completely separate from and
unrelated to one another.
ii) Local variables are created when a function is called, and they are destroyed when the function is
exited. Therefore local variables do not maintain their values between function calls.

Basic data types


C supports five basic data types. The table below shows the five types, along with the C keywords that
represent them. Don’t be confused by void. This is a special purpose data type used to explicitly declare
functions that return no value.

Type Meaning Keyword


Character character data char
Integer signed whole number int
Float floating-point numbers float
Double double precision floatingpoint numbers double
Void valueless void

The ‘int’ specifier


It is a type specifier used to declare integer variables which is 4 bytes long (32 bits). For example, to
declare count as an integer you would write: int count;

Integer variables may hold signed whole numbers (numbers with no fractional part).
Typically, an integer variable may hold values in the range –32,768 to 32,767 and are 2 bytes long.

The ‘char’ specifier


A variable of type char is 1 byte long (8 bits) and is mostly used to hold a single character. For example to
declare ch to be a character type, you would write: char ch;

The ‘float’ specifier


It is a type specifier used to declare floating-point variables. These are numbers that have a whole number
part and a fractional or decimal part for example 234.936. To declare f to be of type float, you would write:
float f;
Floating point variables typically occupy 4 bytes (32 bits). Has accuracy up to 7 digits.

The ‘double’ specifier


It is a type specifier used to declare double-precision floating point variables. These are variables that store
float point numbers with a precision twice the size of a normal float value. To declare d to be of type
double you would write: double d;

12
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036

Double-type variables typically occupy 8 bytes (64 bits). Has accuracy up to 15 digits.

Using printf( ) to output values


You can use printf( ) to display values of characters, integers and floating - point values.
For example:
printf(“This prints the number %d ”, 99); displays This prints the number 99 on the screen.
This call to the printf( ) function contains two arguments. The first one is the quoted string and the other is
the constant 99. When there is more than one argument to a function, the arguments are separated from
each other by commas. The first argument is a quoted string that may contain either normal characters or
format specifiers that begin with a percent (%) sign. Normal characters are simply displayed as is on the
screen in the order in which they are encountered in the string (reading left to right).

In order to display the correct values using printf() function conversion specifiers/ format characters/
format specifiers should be used. They are used to instruct the compiler about the type of numbers
appearing in the program, which in turn determines the suitable memory storage locations. In this case, the
%d, means that an integer is to be output in decimal format. The value to be displayed is to be found in the
second argument. This value is then output at the position at which the format specifier is found on the
string. If you want to specify a character value, the format specifier is %c. To specify a floating point value,
use %f. The %f works for both float and double. Keep in mind that the values matched with the format
specifier need not be constants (such as 99 in the printf statement above). They may be variables too.

Examples
i) The program shown below illustrates the above concepts. First, it declares a variable called num.
Second, it assigns this variable the value 100. Finally, it uses printf( ) to display the value is 100
on the screen. Examine it closely.
#include<stdio.h>
main()
{
int num;
num = 100;
printf(“ The value is %d “, num);
return 0;
}
ii) This program creates variables of types char, float, and double assigns each a value and outputs
these values to the screen.
#include<stdio.h>
main()

13
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036

{
char ch;
float f;
double d;
ch = ‘X’;
f = 100.123;
d = 123.009;
printf(“ ch is %c “, ch);
printf(“ f is %f “, f);
printf(“ d is %f “, d);
return 0;
}

Exercise
Enter, compile, and run the two programs above.

Inputting values from the keyboard using scanf( )


There are several ways to input values through the keyboard. One is to use C’s standard library functions
scanf( ). To use scanf( ) to read an integer value from the keyboard, call it using the general form:
scanf(“%d”, &int_var-name);
Where int-var-name is the name of the integer variable you wish to receive the value.
The first argument to scanf( ) is a string that determines how the second argument will be treated. In this
case the %d specifies that the second argument will be receiving an integer value entered in decimal
format. The fragment below, for example, reads an integer entered from the keyboard.
int num;
scanf(“%d”, &num);
The & preceding the variable name means ‘address of’. The values you enter are put into variables using
the variables’ location in memory. When you enter a number at the keyboard, you are simply typing a
string of digits. The scanf( ) function waits until you have pressed <ENTER> before it converts the string
into the internal format used by the computer.
The table below shows format specifiers or codes used in the scanf() function and their meaning.

Code Meaning
%c Read a single character
%d Read a decimal integer
%i Read a decimal integer
%e Read a floating point number
%f Read a floating point number
%lf Read a double
%s Read a string
%u Read an unsigned integer

Examples
i) This program asks you to input an integer and a floating-point number and displays the value.
#include<stdio.h>
main()
{
int num;
float f;
printf(“ \nEnter an integer: “);
scanf( “%d “, &num);

14
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036

printf(“\n Enter a floating point number: “);


scanf( “%f “, &f);
printf( “%d ”, num);
printf( “\n %f ”, f);
return 0;
}
ii) This program computes the area of a rectangle, given its dimensions. It first prompts the user for
the length and width of the rectangle and then displays the area.
#include<stdio.h>
main()
{
int len, width;
printf(“\n Enter length: “);
scanf (“%d “, &len);
printf(“\n Enter width : ” );
scanf( “ %d “, &width);
printf(“\n The area is %d “, len * width);
return 0;
}
Exercise
Enter, compile and run the example programs.

Storage classes
C storage classes determine how a variable is stored. The storage class specifiers are
 auto
 extern
 register
 static

These specifiers precede the type name.

auto
auto is the default storage class for local variables. The example below defines two variables with the same
storage class. auto can only be used within functions, i.e. local variables.
{
int Count;
auto int Month;
}

extern
As the size of a program grows, it takes longer to compile. C allows you to break down your program into
two or more files or functions. You can separately compile these files and then link them together. In
general, global data may only be declared once.
Because global data may need to be accessed by two or more functions that form the program, there must
be a way of informing the compiler about the global data used by the program.
Consider the following;

File 1
#include<stdio.h>
int count;

15
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036

void f1 (void);
main()
{
int i;
f1 ( ); /* Set count’s value */
for( i =0; i <count; i++)
printf(“%d”);
return 0;
}

File 2
#include<stdlib.h>
void f1(void)
{
count = rand ( ); /* Generates a random number */
}
If you try to compile File 2, an error will be reported because count is not defined.
However, you can change File 2 as follows:
#include<stdlib.h>
int count;
void f1(void)
{
count = rand (); /* Generates a random number */
}
But there is still a problem, If you declare count a second time, the linker will report a duplicate-symbol
error, which means that count is defined twice, and the linker doesn’t know which to use. The solution to
this problem is C’s extern specifier. By placing extern in front of count’s declaration in File 2, you are
telling the compiler that count is an integer declared elsewhere. In other words, using extern informs the
compiler about the existence and type of the variable it precedes but does not cause storage for that
variable to be allocated. The correct version for File 2 is:
#include<stdlib.h>
extern int count;
void f1(void)
{
count = rand ( ); /* Generates a random number */
}

Note: stdlib.h is a header file that contains certain standard library functions. These functions include:
rand() – function is one of them and is used to generate a random number between
abort() – to abort a program,
abs() – to get the absolute value ,
malloc() for dynamic memory allocation ,
free() to free memory allocated with malloc(),
qsort()to sort an array,
realloc() to reallocate memory, et al.

register
register is used to define local variables that should be stored in a register instead of Random Access
Memory (RAM). For example: register int Miles; register should only be used for variables that require
quick access - such as counters.

16
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036

It should also be noted that defining 'register' does not mean that the variable will be stored in a register. It
means that it might be stored in a register - depending on hardware and implementation restrictions.

static
The static modifier causes the contents of a local variable to be preserved between function calls. Also,
unlike normal local variables, which are initialized each time a function is entered a static variable is
initialized only once. For example, take a look at the following program:
#include<stdio.h>
void f(void);
main()
{
int i;
for (i =0; i < 10; i ++)
f( );
return 0;
}
void f (void)
{
static int count = 0;
count ++;
printf(“Count is %d \n”, count);
}
which displays the following output.

visibly from above, count retains its value between function calls.

Constants
A constant is a value that does not change during program execution. In other words, constants are fixed
values that may not be altered by the program.

Integer constants are specified as numbers without fractional components. For example –10, 1000.
Floating - point constants require the use of the decimal point followed by the number’s fractional
component. For example, 11.123 is a floating point constant. C allows you to use scientific notation for
floating point numbers. Constants using scientific notation must follow this general form:

number E sign exponent


The number is optional. Although the general form is shown with spaces between the component parts for
clarity, there may be no spaces between parts in an actual number.
For example, to define the value 1234.56 using scientific notation we write 123.456E1
Character constants are usually just the character enclosed in single quotes; 'a', 'b', 'c'.
For example:
ch = ‘z’;
There is nothing in C that prevents you from assigning a character variable a value using a numeric
constant. For example the ASCII Code for ‘A ‘ is 65. Therefore, give the declaration:
char ch; then these two assignments are equivalent.

17
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036

ch = “A’;
ch = 65;

Types of constants
Constants can be used in C expressions as:
 Direct constants
 Symbolic constants

Direct constants
Here the constant value is inserted in the expression, as it should typically be.
For example:
Area = 3.14 * Radius * Radius;
The value 3.14 is used directly to represent the value of PI which never requires changes in the
computation of the area of a circle

Symbolic constant
This involves the use of another C preprocessor, #define.
For example, #define SIZE 10
A symbolic constant is an identifier that is replaced with replacement text by the C preprocessor before the
program is compiled. For example, all occurrences of the symbolic constant SIZE are replaced with the
replacement text 10.
This process is generally referred to as macro substitution. The general form of the
#define statement is;
#define macro-name string
Notice that this line does not end in a semi colon. Each time the macro - name is encountered in the
program, the associated string is substituted for it. For example, consider the following program.
Example: Area of a circle
#include<stdio.h>
#define PI 3.14
main()
{
float radius, area;
printf(“Enter the radius of the circle \n”);
scanf(“%f”, &radius);
area = PI * radius * radius; /* PI is a symbolic constant */
printf(“Area is %.2f cm squared “,area);
return 0;
}
At the time of the substitution, the text such as 3.14 is simply a string of characters composed of 3, ., 1 and
4. The preprocessor does not convert a number into any sort of internal format. This is left to the compiler.
The macro name can be any valid C identifier. Although macro names can appear in either uppercase or
lowercase letters, most programmers have adopted the convention of using uppercase for macro names to
distinguish them from variable names. This makes it easy for anyone reading your program to know when
a macro name is being used.
Macro substitutions are useful in that they make it easier to maintain programs. For example, if you know
that a value, such as array size, is going to be used in several places in your program, it is better to create a
macro for this value. Then, if you ever need to change this value, you simply change the macro definition.
All references will be automatically changed when the program is recompiled.

Revision Exercise
1. Discuss four fundamental data types supported by C, stating how each type is stored in memory.

18
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036

2. Distinguish between a variable and a constant.


3. Suggest, with examples two ways in which constant values can be used in C expression statements.
4. Give the meaning of the following declarations;
char name[20];
int num_emp;
double tax, basicpay;
char response;
5. What is the difference between a local and a global variable?
6. Write a program that computes the number of seconds in a year.
7. The mass of a single molecule of water is about 3.0 x 10-23 grams. A quart of water is about 950
grams. Write a program that requests an amount of water in quarts and displays the number of water
molecules in that amount.
8. Write a program that declares one integer variable called num. Give this variable the 1000 and then,
using one printf ( ) statement, display the value on the screen like this:
1000 is the value of num
9. Write a program that inputs two floating-point numbers (use type float) and then displays their sum.
10. Write a program that computes the volume of a cube. Have the program prompt the user for each
dimension.
11. Write a program that inputs an integer from the keyboard and displays its square
12. Write a program that reads your first name and surname when you enter them. Each part of your
name should not be more than 12 characters. Finally, have the program redisplay your full name.

CHAPTER 3-OPERATORS
Introduction
How does a C programmer tell a program to perform a calculation, compare values and so on. This requires
one to know the symbols associated with these tasks, for example ‘+’ for addition, ‘>’ for checking whether
one value is greater than another value, ‘=’ for assignment of a value to a variable etc.

Operators versus operands


An operator is a component or symbol of any expression that joins individual constants, variables, array
elements and function references.
An operand is a data item that is acted upon by an operator. Some operators act upon two operands (binary
operators) while others act upon only one operand (unary operators).
An operand can be a constant value, a variable name or a symbolic constant.
An expression is a combination of operators and operands.
Examples
(i) x + y ; x, y are operands, + is an addition operator.
(ii) 3 * 5; 3, 5 are constant operands, * is a multiplication operator.
(iii) x % 2.5; x, 2.5 are operands, % is a modulus (remainder) operator.
(iv) sizeof (int); sizeof is an operator (unary), int is an operand.

1. Arithmetic operators
There are five arithmetic operators in C.

Operator Purpose
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo division, remainder after integer division
Note:

19
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036

i. The operands acted upon by arithmetic operators must represent numeric values, that is
operands may be integers, floating point quantities or characters (since character constants
represent integer values).
ii. The % (modulo division operator) requires that both operands be integers.

Thus;
5%3
int x = 8;
int y = 6 ; x % y are valid while;
8.5 % 2.0 and
float p = 6.3, int w = 7 ; 5 %p , p % w are invalid.
iii. Division of one integer quantity by another is known as an integer division. If the quotient
(result of division) has a decimal part, it is truncated.
iv. Dividing a floating point number with another floating point number, or a floating point number
with an integer results to a floating point quotient . If one or both operands represent negative
values, then the addition, subtraction, multiplication, and division operators will result in values
whose signs are determined by their usual rules of algebra. Thus if a b, and c are 11, -3 and -11
respectively, then
a+b=8
a – b = 14
a * b = -33
a / b = -3
a % b = -2
c % b = -2
c/b=3

Examples of floating point arithmetic operators

r1 = -0.66, r2 = 4.50 (operands with different signs)


r1 + r2 = 3.84
r1 - r2 = -5.16
r1 * r2 = -2.97
r1 / r2 = -0.1466667
Note
i. If both operands are floating point types whose precision differ (e.g. a float and a double) the lower
precision operand will be converted to the precision of the other operand, and the result will be
expressed in this higher precision. (Thus if an expression has a float and a double operand, the
result will be a double).
ii. If one operand is a floating-point type (e.g. float, double or long double) and the other is a character
or integer (including short or long integer), the character or integer will be converted to the floating
point type and the result will be expressed as such.
iii. If neither operand is a floating-point type but one is long integer, the other will be converted to long
integer and the result is expressed as such. (Thus between an int and a long int, the long int will be
taken).
iv. If neither operand is a floating type or long int, then both operands will be converted to int (if
necessary) and the result will be int (compare short int and long int)
From the above, evaluate the following expressions given:
i =7, f = 5.5, c = ’w’. State the type of the result.
 i+f
 i+c
 i + c-‘w’

20
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036

 ( i + c) - ( 2 * f / 5)
(‘w” has ASCII decimal value of 119)

Type Conversion
You can mix the types of values in your arithmetic expressions. char types will be treated as int. Otherwise
where types of different size are involved, the result will usually be of the larger size, so a float and a
double would produce a double result.
Where integer and real types meet, the result will be a double.
There is usually no trouble in assigning a value to a variable of different type. The value will be preserved
as expected except where:
 The variable is too small to hold the value. In this case it will be corrupted (this is bad).
 The variable is an integer type and is being assigned a real value. The value is rounded down. This
is often done deliberately by the programmer.
 Values passed as function arguments must be of the correct type. The function has no way of
determining the type passed to it, so automatic conversion cannot take place.
This can lead to corrupt results. The solution is to use a method called casting which temporarily disguises
a value as a different type.

For example, the function sqrt finds the square root of a double.
int i = 256;
int root;
root = sqrt( (double) i);

The cast is made by putting the bracketed name of the required type just before the value, (double) in this
example. The result of sqrt( (double) i) is also a double, but this is automatically converted to an int on
assignment to root.

Operator precedence
The order of executing the various operations makes a significant difference in the result. C assigns each
operator a precedence level. The rules are;
i. Multiplication and division have a higher precedence than addition and subtraction, so they are
performed first.
ii. If operators of equal precedence; (*, /), (+, -) share an operand, they are executed in the order in
which they occur in the statement. For most operators, the order (associativity) is from left to
right with the exception of the assignment ( = ) operator.

Consider the statement:


butter = 25.0 + 60.0 * n / SCALE;
Where n = 6.0 and SCALE = 2.0.
The order of operations is as follows;
First: 60.0 * n = 360.0
(Since * and / are first before + but * and / share the operand n with * first)
Second: 360.0 / SCALE = 180
(Division follows)
Third: 25.0 + 180 = 205.0 (Result)
(+ comes last)

21
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036

Note that it is possible for the programmer to set his or her own order of evaluation by putting, say,
parenthesis. Whatever is enclosed in parenthesis is evaluated first.
What is the result of the above expression written as:
(25+ 60.0 * n) / SCALE?

Example: Use of operators and their precedence


/* Program to demonstrate use of operators and their precedence */
#include<stdio.h >
main()
{
int score,top;
score = 30;
top = score - (2*5) + 6 * (4+3) + (2+3);
printf (“top = %d \ n” , top);
return 0;
}
Try changing the order of evaluation by shifting the parenthesis and note the change in the top score.

Example: Converting seconds to minutes and seconds using the % operator


#include<stdio.h>
#define SEC_PER_MIN 60
main()
{
int sec, min, sec_left;
printf(“=== CONVERTING SECONDS TO MINUTES AND SECONDS === \n\n“) ;
printf(“Enter number of seconds you wish to convert\n“) ;
scanf(“%d”,&sec ) ; /* Read in number of seconds */
min = sec / SEC_PER_MIN ; / * Truncate number of seconds */
sec_left = sec % SEC_PER_MIN ;
printf(“\n%d seconds is % d minutes,% seconds\n“ ,sec,min,sec_left);
return 0;
}
Analyse the sample output below. Run the program with different values.

2. The assignment operator


The Assignment operator ( = ) is a value assigning operator. Assignment expressions take the form;
identifier = expression; where identifier generally represents a variable, constant or a larger expression.

Examples of assignment:
a=3;
x=y;
pi = 3.14;
sum = a + b ;
area_circle = pi * radius * radius;

22
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036

Note
i. You cannot assign a variable to a constant such as 3 = a ;
ii. The assignment operator = and equality operator (= =) are distinctively different. The = operator
assigns a value to an identifier. The equality operator (= =) tests whether two expressions have
the same value.
iii. Multiple assignments are possible e.g. a =b = 5 ; assigns the integer value 5 to both a and b.
iv. Assignment can be combined with +, -, /, *, and %

3. Relational operators
There are four relational operators in C.
 < Less than
 <= Less than or equal to
 > Greater than
 > = Greater than or equal to
Closely associated with the above are two equality operators;
· = = Equal to
· ! = Not equal to
The above six operators form logical expressions.
A logical expression represents conditions that are either true (represented by integer 1) or false
(represented by 0).
Example
Consider a, b, c to be integers with values 1, 2, 3 respectively. Note their results with relational operators
below.

Expression Result
a<b 1 (true)
(a+ b) > = c 1 (true)
(b + c) > (a+5) 0 (false)
c:=3 0 (false)
b==2 1 (true)

4. Logical operators
&& Logical AND
|| Logical OR
! NOT
The three operators act upon operands that are themselves logical expressions to produce more complex
conditions that are either true or false.

Example
Suppose i is an integer whose value is 7, f is a floating point variable whose value is 5.5 and C is a
character that represents the character ‘w’, then;
(i > = = 6 ) && ( C = = ‘w’ ) is 1 (true)
( C’ > = 6 ) || (C = 119 ) is 1 (true)
(f < 11 ) && (i > 100) is 0 (false)
(C! = ‘ p’) || ((i + f) < = 10 ) is 1 (true)

Precedence of relational and logical operators

23
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036

5. The Conditional operator


Conditional tests can be carried out with the conditional operator (?). A conditional expression takes the
form:
expression1 ? expression2 : expression3 and implies;
evaluate expression1. If expression1 evaluates to true ( value is 1 or non zero) then evaluate expression 2,
otherwise (i.e. if expression 1 is false or zero ) , evaluate
expression3.
Consider the statement (i < 0) ? 0 :100
Assuming i is an integer, the expression (i < 0) is evaluated and if it is true, then the result of the entire
conditional expression is zero (0), otherwise, the result will be 100.

6. Unary operators
These are operators that act on a singe operand to produce a value. The operators may precede the operand
or are after an operand.
Examples
(i) Unary minus e.g. - 700 or –x
(ii) Incrementation operator e.g. c++
(iii) Decrementation operator e.g. f - -
(iv) sizeof operator e.g. sizeof( float)

7. The sizeof operator


sizeof returns the size in bytes, of its operand. The operand can be a data type e.g.
sizeof (int), or a specific data object e.g. sizeof n.
If it is a name type such as int, float etc. The operand should be enclosed in parenthesis.

Example : Demonstrating ‘sizeof’ operator


#include <stdio.h>
main()
{
int n;
printf(“n has % d bytes; all ints have % d bytes\n” ,sizeof
n,sizeof(int)) ;
return 0;
}
Run the program and analyse the results. You can later modify program to make the variable n a different
data type and other appropriate changes, then run it.

Revision Exercise
1. Describe with examples, four relational operators.
2. What is ‘operator precedence’? Give the relative precedence of arithmetic operators.
3. Suppose a, b, c are integer variables that have been assigned the values a =8, b = 3 and c = - 5, x, y, z are
floating point variables with values x =8.8, y = 3.5, z = -5.2.

24
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036

Further suppose that c1, c2, c3 are character-type variables assigned the values E, 5 and ? respectively.

Determine the value of each of the following expressions:


(i) a / b
(ii) 2 * b + 3 * (a – c)
(iii) (a * c) % b
(iv) (x / y) + z
(v) x % y
(vi) 2 * x / (3 * y)
(vii) c1 / c3
(viii) (c1 / c2) * c3
4. The roots of a quadratic equation ax2 + bx + c = 0 can be evaluated as:
x1 = (-b + Ö(b2 - 4ac))/2a
x2 = (-b + Ö(b2 - 4ac))/2a

where a, b ,c are double type variables and b2 = b * b , 4ac = 4 * a * c, 2a = 2 * a.


Write a program that calculates the two roots x1 x2 with double precision, and displays
the roots on the screen.
Hint: We use the math function sqrt( ) to get the square root of a value, e.g. if you want
to get the square root of a value x, you write sqrt(x). However, for the function sqrt to
work, you need to have contents of the header file math.h in your source program.
Therefore you will need to have the statement #include<math.h>
5. The total mechanical energy of a particle is given by:
Energy = mgh + ½ mv
Where m = mass
g = acceleration due to gravity.
h = height
v = velocity
Write a program to calculate the energy using the formula above. The data is to
be input from the keyboard.
6. Identify errors in the following programs and write error free programs.
(i)
#include <stdio.h>
#include <math.h>
#define PI = 3.142
VOID main[ ]
{
/* Radius, area and perimeter are declared to be floats /*
Float r, area, perimeter,
printf(\n “Enter the radius of the circle - > \n”);
scanf(“%f”,&r);
area = PI * pow(r, 2)
perimeter = 2 * PI * r;
/* Result is printed after the computation */
printf(“ Area = %f Perimeter = %d /n”, area, perimeter);
}
(ii)
#include <stdio.h>
Main( )
{
cows, legs, integer;

25
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036

printf(“How many cow legs did you count ? \n;


Scanf(“%c”, legs);
cows = legs/4;
printf(“That implies that there are %f cows. \n”, cows)
}

26
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)

You might also like