Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
19 views

Chapter 5-Programming Fundamentals

Computer science

Uploaded by

Anthony
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Chapter 5-Programming Fundamentals

Computer science

Uploaded by

Anthony
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

MAT 224 -INTRODUCTION TO DATA PROCESSING AND COMPUTERS

Chapter three: Fundamentals of programming C. The chapter also aims to familiarize the learners on how to
declare constants and variables in C language. We shall also
3.1 Chapter objectives
Therefore, by the end of this chapter, the learners should be discuss the various data types supported by C programming
able to: Language. Finally, we provide a summary for the chapter and
 Differentiate between identifiers and keywords some self-testing exercise for the learners
 Declare and use variables in C language to store 3.3 Identifiers
They are name given to various program elements such as
information
variables, constants, functions and arrays. Rules for naming
 Understand the different types of variable scopes
identifiers
 Understand different data types supported by C i). Can consists of letters and digits in any order
language
ii). The first character must be a letter or an underscore symbol.
 Understand how and when to use comments in C
iii). Identifier names cannot have space
programming language.
iv). Both upper and lower case letters are permitted
 Understand the different data types supported by C
programming language v). The only special character that can be used in identifier
definition is the underscore (_) and can be included often in
3.2 Introduction
This chapter aims at introducing learners to fundamental the middle of an identifier
concepts of C programming. The chapter will look at concepts
such as variables, constants as well as operators supported by

1|CHAPTER THREE-BASIC CONCEPTS FOR PROGRAMMING


MAT 224 -INTRODUCTION TO DATA PROCESSING AND COMPUTERS

3.4 Key words program pretty easily. All characters available inside any
These are words that have a standard predefined meaning in C comment are ignored by C compiler. C multiple comments
programming language. E.g. main is a word that has a
start with /* and end with */. e.g.
predefined meaning in C language so no identifier can have
/* This is a comment */
such name
/* C comments can also span multiple lines */
3.5 Statements in C
A statement is meant to cause the computer to carry out some
For single comment, we use the double fowardslash (//). All
action. In C, all statements are usually terminated with a
statements preceded by the backslash shall be ignored by the
semicolon except for comments and control structure
compiler. e.g.
statements.
void main ()
3.6 Include <headerfile.h>
C has some predefined header files. Any program can include {
those files. The general format for include declaration is as
printf<< "welcome"; // prints welcome return 0;
follows
#include <headerfile.h> or #include “headerfile.h” }

3.8 Data types


3.7 Comments in C
Before storing values in C programming, we need to declare
C supports single line and multi-line comments. Comments
variable (s) to hold their values. Variables will have different
help in improving programming readability as well as serve as
data type depending on the kind of data they will store. While
documentation for others so that they can understand the

2|CHAPTER THREE-BASIC CONCEPTS FOR PROGRAMMING


MAT 224 -INTRODUCTION TO DATA PROCESSING AND COMPUTERS

declaring Identifiers, the programmer must specify a data type Void


to help to reserve memory. Char

As a programming language, C offers the programmer a rich


We can modify several of the basic types using one or more
collection of built-in as well as user defined data types.
of these type modifiers signed (1), unsigned (2), short (3) and
Following table lists down seven basic (primitive) data types
long (4) as depicted in the table that follows
Data type Keyword Typical bit Typical range Data type Typical bit Typical range
width width
Boolean bool I byte- 8 bits unsigned 1byte 0 to 255
char
Character Char 1 byte-8 bits -127 to 127 or 0
signed 1byte -127 to 127
to
char
Integer Int 4 bytes-32 bits 2147483648 to
unsigned 4bytes 0 to 4294967295
2147483647
int
Floating Float 4 bytes-32 bits +/- 3.4e +/- 38
signed int 4bytes -2147483648 to
point (~7 digits)
2147483647
Double Double 8 bytes-64 bits +/- 1.7e +/- 308 short int 2bytes -32768 to 32767
float point (~15 digits)

3|CHAPTER THREE-BASIC CONCEPTS FOR PROGRAMMING


MAT 224 -INTRODUCTION TO DATA PROCESSING AND COMPUTERS

unsigned Range 0 to 65,535 3.9 Variables


While programming using any programming language, we may
short int
need to use various variables to store various information.
signed Range -32768 to 32767
Variables are simply reserved memory locations to store
short int
values. They are identifiers whose value is allowed to change
long int 4bytes -2,147,483,647 to
during run time.
2,147,483,647
Before using a variable, we must declare it first. By declaring
signed 4bytes same as long int
a variable, we are simply requesting the operating system for
long int
a piece of memory. This piece of memory you give a name and
unsigned 4bytes 0 to 4,294,967,295 you can store something in that piece of memory.
long int
long 8bytes +/- 1.7e +/- 308 (~15 digits) You may like to store information of various data types like
double character, wide character, integer, floating point, double floating

wchar_t 2 or 4 bytes 1 wide character point, Boolean etc. Based on the data type of a variable, the
operating system allocates memory and decides what can be
stored in the reserved memory.
The sizes of variables might be different from those shown in
the above table, depending on the compiler and the computer 3.9.1 Variable Definition in C

you are using. When we declare a variable, we are telling the compiler where
and how much to create the storage for the variable. A variable

4|CHAPTER THREE-BASIC CONCEPTS FOR PROGRAMMING


MAT 224 -INTRODUCTION TO DATA PROCESSING AND COMPUTERS

definition specifies a data type, and contains a list of one or 3.9.2.1 Local Variables
more variables of that type as shown in the following syntax: They are variables declared inside a function or block. They can
Data_type identifier [=value], [identifier=value]… [Identifiern=valuen]; be used only by statements that are inside that function or block
Here, data_type must be a valid C data type (char, wchar_t, int, of code. Local variables are not known to functions outside their
float, double, bool or any user-defined object like structure, etc., own. The following is the example uses local variables:
and identifier can be one or more identifier names separated by void main ()
commas.
{
Identifiers can be initialized (assigned an initial value) in their // Local variable declaration
declaration. The assignment operator (=) is always followed by
int a, b,sum;
a constant expression as follows:
// actual initialization
Data_type identifier_name = value;
a = 10; b = 20;
Some examples are:
sum = a + b;
E.g. float sum=0.0;
printf(“the sum is %d” ,sum);
3.9.2 Variable scope }
A variable scope means the extent to which a variable is 3.9.2.2 Global Variables
available in a program. There are three variable scopes namely:

5|CHAPTER THREE-BASIC CONCEPTS FOR PROGRAMMING


MAT 224 -INTRODUCTION TO DATA PROCESSING AND COMPUTERS

They are variables defined on top of the program. The global A program can have same name for local and global variables
variables will hold their value throughout the life-time of your but value of local variable inside a function will take preference.
program. They can be accessed by any function i.e. it can be An example is presented below
available for use throughout your entire program after its int sum = 20;
declaration. A good example is presented below:
void main ()
Int sum;
{
void main ()
// Local variable declaration
{
int sum = 15;
// Local variable declaration:
printf(“the sum is%d”,sum);
int a, b;
return 0;
// actual initialization
}
a = 10; b = 20;
Program output: 15
sum = a + b;
3.9.2.3 Formal parameters
printf(“the sum is%d”,sum);
These are defined in a function
} Initializing Local and Global Variables

6|CHAPTER THREE-BASIC CONCEPTS FOR PROGRAMMING


MAT 224 -INTRODUCTION TO DATA PROCESSING AND COMPUTERS

Anytime a local variable is defined, it is not automatically Constants can be treated just like regular variables only that
initialized by the system, you must initialize it yourself. However their values cannot be modified after their definition. There are
for global variables, they are initialized automatically by the different categories of constants
system when you define them as follows: 3.10.1 Integer literals/constants
Data type Initialize Integer constants are constant data elements that have no
Int 0 fractional parts or exponents. They always begin with a digit.
Char „\0‟ You can specify integer constants in decimal, octal, or
Float 0 hexadecimal form. They can specify signed or unsigned types

Double 0 and long or short types.


3.10.2 Floating-point literals
Pointer Null
As a programmer though, it’s a good practice to initialize They are constants that have an integer part, a decimal point, a
variables properly, otherwise sometimes program would fractional part, and an exponent part. You can represent floating
produce unexpected result. point literals either in decimal form or exponential form.
3.10.3 Boolean literals
3.10 Constants
Constants refer to fixed values that the program may not alter They are constants that can hold either a true or a false value.
and they are called literals. They are programmer’s memory
location for holding values that do not change during program
execution. Constants can be of any of the basic data types.

7|CHAPTER THREE-BASIC CONCEPTS FOR PROGRAMMING


MAT 224 -INTRODUCTION TO DATA PROCESSING AND COMPUTERS

3.10.4 Character literals This format has the following general syntax

They are usually enclosed in single quotes. A character literal #define identifier value

can be a plain character (e.g., 'y'), an escape sequence (e.g.,


The same example above is presented below
'\n'), or a universal character (e.g., '\u02C0').
3.10.5 String literals Note that it is a good programming practice to define constants
They are constants enclosed in double quotes. A string in CAPITALS.
contains characters that are similar to character literals: plain 3.12 Escape sequence
In C, certain non-printing characters are used as in-built
characters, escape sequences, and universal characters. A
commands. Escape sequence are usually preceded by back
typical example is presented below
slash sign (\). Here, you have a list of some of such escape
"Hello, welcome to C programming"
sequence codes:
3.11 Declaring constants
 Using the const Keyword Escape sequence Description
The const keyword can be used to define constants as \\ \ character
shown in the following syntax \' ' character
Const type ConstName = value; \" " character
\? ? character
An example of the same is presented below
\a Alert or bell
 Using the #define pre-processor

8|CHAPTER THREE-BASIC CONCEPTS FOR PROGRAMMING


MAT 224 -INTRODUCTION TO DATA PROCESSING AND COMPUTERS

\b Backspace iii). Logical Operators


\f Form feed iv). Bitwise Operators

\n Newline v). Assignment Operators


\r Carriage return vi). Misc Operators
\t Horizontal tab
This module shall examine the arithmetic, relational, logical &
assignment operators into detail.
A good use of escape sequence is presented below
Void main( ) 3.12.1 Arithmetic Operators
{ C as a programming language supports the following arithmetic
printf( "Hello\t welcome\t to C programming\n"); return 0; operators. Assume we have two variables; x holds 15 and y
} holds 10, then;
Output: Hello welcome to C programming Operator Description Example
3.13 Operators in C + Adds two operands X+y will yield 25
An operator is a symbol that tells the compiler to perform
- Subtracts second operand from x-y will yield 5
specific mathematical or logical manipulations. C programming
the first
has a rich in built-in operators and provides the following types
* Multiplies two operands X*y will yield 150
of operators:
i). Arithmetic Operators / Divides two operands x/y will yield 1

ii). Relational Operators

9|CHAPTER THREE-BASIC CONCEPTS FOR PROGRAMMING


MAT 224 -INTRODUCTION TO DATA PROCESSING AND COMPUTERS

% Modulus Operator and X% y will yield > Checks if the value of left (X>Y) is true
remainder of after an integer operand is greater than the
division value of right operand, if yes
++ Increment operator, increases X++ will yield 16 then condition becomes true.
integer value by one < Checks if the value of left (X<Y) is not true
-- Decrement operator, decreases Y++ will yield 9 operand is less than the value
integer value by one of right operand, if yes then
3.12.2 Relational/comparison Operators condition becomes true.
C programming language supports the following relational >= Checks if the value of left (X>=Y) is true
operators. Assume we have two variables; x holds 15 and y operand is greater than or equal
holds 10, then; to the value of right operand, if
Operator Description Example yes then condition becomes

== Checks if the values of two (X==Y) is not true true.

operands are equal or not, if yes >= Checks if the value of left (X>=Y) is true

!= Checks if the values of two (X!=Y) is true operand is greater than or equal

operands are equal or not, if to the value of right operand, if

values are not equal then yes then condition becomes

condition becomes true. true.

10 | C H A P T E R T H R E E - B A S I C C O N C E P T S F O R P R O G R A M M I N G
MAT 224 -INTRODUCTION TO DATA PROCESSING AND COMPUTERS

<= Checks if the value of left (X<=Y) is not Operator Description Example

operand is less than or equal to true && Called Logical AND operator. If (X&&Y) is false
the value of right operand, if yes both the operands are non zero
then condition becomes true. i.e. then the condition becomes

3.12.3 Logical Operators true.

There are following logical operators supported by C language. || Called Logical OR Operator. If (X||Y) is true
The result of logical operators can only be a Boolean value; true any of the two operands is
or false. Assume variable x holds 1 and variable y holds 0, then: nonzero, then condition
becomes true.
! Called Logical NOT Operator. !(X||Y) is false
Used to reverses the logical
state of its operand. If a condition
is true, then Logical NOT
operator will make false.

3.12.4 Assignment Operators


C supports the following assignment operators. Assume x hold
15 and y holds 10, then;

11 | C H A P T E R T H R E E - B A S I C C O N C E P T S F O R P R O G R A M M I N G
MAT 224 -INTRODUCTION TO DATA PROCESSING AND COMPUTERS

3.12.5 Misc Operators


= assignment operator, It equivalent to x = x
multiplies right operand with the *y Operator Operator description
left operand and assign the * Pointer operator * is pointer to a variable. For
result example *studname; will pointer to a variable
to left operand name studname.
/= Its known as Divide AND /= y is equivalent Pointer operator & returns the address of a
assignment operator, It divides to x = x /y & variable. For example &studname will return
left operand with the right the actual address of the variable studname.
operand and assign the result to Casting operators which are used to convert
left operand one data type to another. For example,
Cast
%= Its known as Modulus AND %= y is equivalent Float sum=2.200;
assignment operator. It takes to x = x
(Int) sum returns 2 instead of 2.200.
modulus using two operands %y
Known as sizeof operator returns the size of a
and assign the result to left
sizeof variable. For example, sizeof (x), where x is
operand
integer or float will return 4.
Condition? X : Conditional operator. If Condition is true? then it
Y returns value X : or else value Y

12 | C H A P T E R T H R E E - B A S I C C O N C E P T S F O R P R O G R A M M I N G
MAT 224 -INTRODUCTION TO DATA PROCESSING AND COMPUTERS

3.14 Assignment in C++ The general format is as follows


Every variable in a program must be assigned (allocated) a
Variable=expression;
value explicitly before any attempt is made to use it. It is also
Where expression is the value we are assigning to the variable.
important that the value assigned is of the correct type. This one
A good example is presented below whereby the programs
is achieved using the assignment operator to this (=).
takes the values of a and b, sums them together and assigns
Assignment is always done from left to right. Though the
the result to a variable known as total i.e. total = a + b;
assignment operator looks like the mathematical equality
Anytime a variable appears in an expression, it represents the
operator, in programming, it’s a meaning is different. The
value currently stored in that memory location. When an
symbol simply indicates that the value on the right hand side of
assignment statement is executed, a new value is dropped into
the assignment operator (=) symbol must be stored (assigned)
the memory location overwriting it with the new one
to the variable named on the left hand side.
3.15 Output in C
To print a value on the console, we always use the function
Ideally, the operator should be read as “becomes equal to” and
printf which is defined in the standard library stdio.h in c. An
means that the variable on the left hand side has its value
example of a printf( ) statement is as follows
changed to the value of the expression on the right hand side.
For the assignment to work successfully, the type of the variable Printf (“the area of the circle is %d\n”, area);

on the left hand side should be the same as the type returned “The area of the circle is %d\n”, is referred as control string
by the expression. while area is the variable to be outputted

13 | C H A P T E R T H R E E - B A S I C C O N C E P T S F O R P R O G R A M M I N G
MAT 224 -INTRODUCTION TO DATA PROCESSING AND COMPUTERS

%d is a conversion specifier indicating that the type of the e Floating point number Pointer to float
corresponding variable to be printed is integer f Floating point number Pointer to float

3.16 Input in c g Floating point number Pointer to float


scanf ( ) is used to read values from the keyboard then assign
s String Pointer to char
them to specified variable(s). E.g. scanf("%d", &x); read a
p Address format, depends Pointer to void
decimal integer from the keyboard and store the value in the
on system
memory address of the variable x
3.17 scanf( ) Control String Conversion Characters
scanf( ) uses the same format specifier as the printf statement. 3.18 Character I/O — getchar ( ) & putchar ( )
They are used to for the input and output of single characters
Arguments of scanf must be pointers to memory address hence
respectively. getchar() returns an int which is either EOF or the
the use of the ampersand sign (&)
next character in the standard input stream. putchar(c) puts the
Character Form of output Expected argument
character c on the standard output stream.
c Character Pointer to char
void main()
d Decimal integer Pointer to int
{
x Hexadecimal integer Pointer to int int a; a = getchar(); /* read a character and assign to c */
o Octal integer Pointer to int putchar(c); /* print c on the screen */
u Unsigned integer Pointer to int }

i Integer Pointer to int

14 | C H A P T E R T H R E E - B A S I C C O N C E P T S F O R P R O G R A M M I N G

You might also like