0% found this document useful (0 votes)
16 views

1 C Basic

Uploaded by

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

1 C Basic

Uploaded by

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

1 BASIC @ FRED 2023

Chapter One: Introduction to Programming


Expected Learning Outcomes
• Define programming
• Explain what a programming language is
• Describe the structured programming approach
• Identify the steps of developing a program
• Explain the characteristics of C language.
• Discuss the components of a C program
• Identify various types of program errors
• Create and compile a program

Definition: Programming
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.
Definition: Programming language
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.

Definition: Structured Programming


It is a programming approach based on the following principles:
• Stepwise refinement – Solution consists of small logical steps
• Control structures – Statements that control program flow:
- Sequence
- Selection
- Iteration
• Use of modules (Modularity)– Building a program in blocks /units
which perform specialised tasks.

Steps in program development


1. Specify program requirements
This stage setting program objectives and specifying what it will do in an
unambiguous way so that the users can verify those requirements and the
programmer can easily understand the program. The requirements of the all
the program’s phases (Input, Processing, Output) need to be well spelt out.

2. Design program
This stage is about specifying how the program will meet the requirements
identified i.e. how it will be implemented. Program areas considered are the
user interface, program flow (algorithm) , data types and names.

3. Develop the program


This is the actual writing of the program – using words and symbols that are
understandable to human beings. You type the program directly into a
window on the screen and save the resulting text as a separate file. This is
1
2 BASIC @ FRED 2023

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 language

4. Compiling
This is the translation of the source file must be translated into machine
understandable form - binary numbers. An intermediate file called the object
code - with the extension .obj is produced.

5. Linking
This is the integration of library file information with the intermediate
code of your program to produce the final program file that you
execute or run. The final file is called the executable file - .exe file.
Library files are used by a programmer to enable his/her program
perform some special task for which a function has been written by a
manufacturer.

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

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

7. Maintain the program


This involves modifying a program as need may arise. This is easily made
possible if you document the program clearly and follow good program design
practices.

What is C?
• C is a compiled language. This means that once you write your C
program, you must run it through a C compiler to turn your program
into an executable that the computer can run (execute).
• 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 structured programming
• C is a middle level language. This refers to the fact that C can be
used to write low level programs as well as high level programs.

Factors that make C popular

2
3 BASIC @ FRED 2023

• Support for structured programming- It allows programmers to


break down their programs into functions as well as use of control
structures.
• 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.
• Portability- C programs written for one system can be run with little or
no modification on other systems.

• Adaptability/ and flexibility - C has been used to develop to


develop complex software such as 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, et al.

In addition C has (and still is) been used to solve problems in areas such
as physics and engineering.

A simple C program.
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. You will
find it at the beginning of almost every C program.
• main() declares the start of the function, while the two curly
brackets show the start and finish of the function. Curly
brackets in C 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.

C is case sensitive, that is, it recognises a lower case letter


and it's upper case equivalent as being different.
C Program Components
A typical C program is made of the following components:
• Keywords
• Preprocessor directives
• Functions
• Declaration statements
• Comments

3
4 BASIC @ FRED 2023

• Expressions
• Input and output statements
The following program demonstrates the C program components.
#include<stdio.h>
main()
{
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.

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 C language keywords:


break, case, else, int, void, default, do, double,
if, sizeof, long, float, for, return, union, continue,
struct, switch,while, char

Functions
A function is a set of related statements that perform a specific task in a
program. A statement specifies an action to be performed by the program.
Note that all C statements must end with a semicolon.

A C program consists of one or more functions, and one of them must be


called main, in order for the program to execute.

The main( ) function is the point at which execution of your program begins.
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.

Library functions are also part of C programs. These are ready-to- run
programs written by the C language producer (such as Borland). The
functions perform tasks such as program data Input/output, string
manipulations, mathematics, and much more.

4
5 BASIC @ FRED 2023

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

The printf( ) outputs the characters that are contained between the beginning
and ending double quotes.
For example, printf(“ This is a C program “);
• 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 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. 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.

Tip
• 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. We shall
adopt the former hence forth.

Preprocessor Directives
A preprocessor directive is a statement that performs various manipulations on your source
file before it is actually compiled.

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

Header files contain details of functions 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, < >.

Comments
Comments are non – executable program statements meant to enhance
program readability and allow easier program maintenance, i.e. they
document the program.

5
6 BASIC @ FRED 2023

Declaration Statements
In C, all variables must be declared before they are used (discussed later).
Line 4 is a declaration for an integer variable called num.

Assignment and expression statements


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. The program below displays the following output on the screen.

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

Below is a summary of C escape sequences:


Escape sequence Meaning
\a alert/bell
\b backspace
\n new line
\v vertical tab
\t horizontal tab
\\ back slash
\’ Single quote (‘)
\” Double quote (“”)
\0 null

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;
• Missing semi colon at the end of a statement
• 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

6
7 BASIC @ FRED 2023

Logic Errors
These occur from the incorrect use of control structures, incorrect calculation,
or omission of a procedure. Examples include: An infinite 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 requires, division by zero, etc.

Chapter Two: Data Handling

Expected Learning outcomes

▪ Explain C’s basic data types


▪ Define a variable
▪ Declare variables
▪ Use scanf() and printf() functions to perform input and output of
variables
▪ Describe various types of variables
▪ Define a constant
▪ Describe various types of constants.
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;

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; /* MinimumTemperature */

7
8 BASIC @ FRED 2023

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.

Basic Data Types


C supports five basic data types. The table below shows the five types, along
with the C keywords that represent them. Do not 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 int
number
Float floating-point float
numbers
Double double precision double
floating-point
numbers
Void Valueless void

The ‘int’ specifier


It is a type specifier used to declare integer variables. 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.
The ‘char’ specifier

A variable of type char is 1 byte long and is mostly used to hold a single
character.

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.

8
9 BASIC @ FRED 2023

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.
Using printf( ) to output values
You can use printf( ) to display values of characters, integers and floating - point values. To do
so, however, requires that you know more about the printf( ) function.
For example:

printf(“This prints the number %d ”, 99);

displays This prints the number 99 on the screen.


The printf( ) function contains two arguments. The first one is the quoted string and the other is
the constant 99. Notice that the arguments are separated from each other by a comma.
In general, 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). A format specifier, on the other hand informs
printf( ) that a different type item is being displayed. 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.

The main output code used with print() and the format they represent are listed below.
Code Format
%c Character
%d or %i Integer
%f Floating point numbers (float, double)
%s String of characters

Inputting values from the keyboard using scanf( )


There are several ways to input values through the keyboard. One of the easiest is to use
another of C’s standard library functions called scanf( ).

To use scanf( ) to read an integer value from the keyboard, use 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.

9
10 BASIC @ FRED 2023

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 codes and formats used with scanf() for basic types.

Code Format
%c Read a single character
%d or %i Read an integer
%lf Read a double
%s Read a string
Example
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>
void 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);
}
Enter, compile and run the program

Variable Types
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.
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 are integer constants.

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.

Character constants are usually just the character enclosed in single quotes; 'a', 'b',
'c'. For example:
10
11 BASIC @ FRED 2023

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 constants
This involves the use of another C preprocessor, #define.
For example, #define PI 3.14

A symbolic constant is an name (e.g. PI) that is replaced with replacement


text (a value, e.g. 3.14) before the program is compiled.

For example, all occurrences of the symbolic constant PI are replaced with
the replacement text 3.14.

For example, consider the following program.

#include<stdio.h>
#define PI 3.14
void main()
{
float radius, area;
printf(“Enter the radius of the circle \n”);
scanf(“%f”, &radius);
area = PI * radius * radius;
printf(“Area is %.2f cm squared “,area);
}

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.

11

You might also like