You are on page 1of 17

CMT 110: PROGRAMMING METHODOLOGY

Chapter three: Fundamentals of C programming such as variables, constants as well as operators supported by

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

Email: Kioko@cuea.edu Mobile:-+254-725-695-782

© By Edward Kioko. All rights reserved for this module. No part of this module may be reproduced or transmitted in any form or by any means,
electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the author
CMT 110: PROGRAMMING METHODOLOGY

v). The only special character that can be used in identifier 3.7 Comments in C++
definition is the underscore (_) and can be included C supports single line and multi-line comments. Comments

often in the middle of an identifier help in improving programming readability as well as serve as
documentation for others so that they can understand the
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
predefined meaning in C language so no identifier can have start with /* and end with */. e.g.

such name /* This is a comment */

3.5 Statements in C++ /* C++ comments can also span multiple lines */
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.
#include <stdio.h>
3.6 Include <headerfile.h>
C has some predefined header files. Any program can include Int main ()

those files. The general format for include declaration is as {

follows Cout<< "welcome"; // prints welcome return 0;

#include <headerfile.h> or #include “headerfile.h” }

Email: Kioko@cuea.edu Mobile:-+254-725-695-782

© By Edward Kioko. All rights reserved for this module. No part of this module may be reproduced or transmitted in any form or by any means,
electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the author
CMT 110: PROGRAMMING METHODOLOGY

3.8 Data types Floating Float 4 bytes-32 bits +/- 3.4e +/- 38
Before storing values in C programming, we need to declare point (~7 digits)
variable (s) to hold their values. Variables will have different Double Double 8 bytes-64 bits +/- 1.7e +/- 308
data type depending on the kind of data they will store. While (~15 digits)
float point
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
collection of built-in as well as user defined data types. We can modify several of the basic types using one or more

Following table lists down seven basic (primitive) data types of these type modifiers signed (1), unsigned (2), short (3) and
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
Character Char 1 byte-8 bits -127 to 127 or 0 char
to signed 1byte -127 to 127
Integer Int 4 bytes-32 bits 2147483648 to char

2147483647 unsigned 4bytes 0 to 4294967295


int

Email: Kioko@cuea.edu Mobile:-+254-725-695-782

© By Edward Kioko. All rights reserved for this module. No part of this module may be reproduced or transmitted in any form or by any means,
electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the author
CMT 110: PROGRAMMING METHODOLOGY

signed int 4bytes -2147483648 to The sizes of variables might be different from those shown in
2147483647 the above table, depending on the compiler and the computer
short int 2bytes -32768 to 32767 you are using.
unsigned Range 0 to 65,535 3.9 Variables
short int While programming using any programming language, we may

signed Range -32768 to 32767 need to use various variables to store various information.

short int Variables are simply reserved memory locations to store

long int 4bytes -2,147,483,647 to values. They are identifiers whose value is allowed to change

2,147,483,647 during run time.

signed 4bytes same as long int Before using a variable, we must declare it first. By declaring

long int a variable, we are simply requesting the operating system for

unsigned 4bytes 0 to 4,294,967,295 a piece of memory. This piece of memory you give a name and

long int you can store something in that piece of memory.

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
wchar_t 2 or 4 bytes 1 wide character
floating 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.

Email: Kioko@cuea.edu Mobile:-+254-725-695-782

© By Edward Kioko. All rights reserved for this module. No part of this module may be reproduced or transmitted in any form or by any means,
electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the author
CMT 110: PROGRAMMING METHODOLOGY

3.9.1 Variable Definition in C Some examples are:

When we declare a variable, we are telling the compiler where E.g. float sum=0.0;
and how much to create the storage for the variable. A variable
3.9.2 Variable scope
definition specifies a data type, and contains a list of one or
more variables of that type as shown in the following syntax: A variable scope means the extent to which a variable is
available in a program. There are three variable scopes namely:

Data_type identifier [=value], [identifier=value]… [Identifiern=valuen];  Local Variables


They are variables declared inside a function or block.
They can be used only by statements that are inside that
Here, data_type must be a valid C data type (char, wchar_t, int, function or block of code. Local variables are not known
float, double, bool or any user-defined object like structure, etc., to functions outside their own. The following is the
and identifier can be one or more identifier names separated by example uses local variables:
commas.
#include <stdio.h>

Identifiers can be initialized (assigned an initial value) in their int main ()

declaration. The assignment operator (=) is always followed by {


a constant expression as follows: // Local variable declaration
int a, b,sum;
Data_type identifier_name = value; // actual initialization a = 10; b = 20; sum = a + b;

Email: Kioko@cuea.edu Mobile:-+254-725-695-782

© By Edward Kioko. All rights reserved for this module. No part of this module may be reproduced or transmitted in any form or by any means,
electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the author
CMT 110: PROGRAMMING METHODOLOGY

printf(“the sum is%d”,sum); return 0;


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

Email: Kioko@cuea.edu Mobile:-+254-725-695-782

© By Edward Kioko. All rights reserved for this module. No part of this module may be reproduced or transmitted in any form or by any means,
electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the author
CMT 110: PROGRAMMING METHODOLOGY

 Formal parameters 3.10 Constants


Constants refer to fixed values that the program may not alter
These are defined in a function
and they are called literals. They are programmer’s memory
Initializing Local and Global Variables
location for holding values that do not change during program
Anytime a local variable is defined, it is not automatically
execution. Constants can be of any of the basic data types.
initialized by the system, you must initialize it yourself. However
Constants can be treated just like regular variables only that
for global variables, they are initialized automatically by the
their values cannot be modified after their definition.
system when you define them as follows:
3.10.1 Types of constants
Data type Initialize
We can divide constants/literals as follows
Int 0
 Integer literals/constants
Char „\0‟
Float 0 Integer constants are constant data elements that have no

Double 0 fractional parts or exponents. They always begin with a


digit. You can specify integer constants in decimal, octal, or
Pointer Null
hexadecimal form. They can specify signed or unsigned
As a programmer though, it’s a good practice to initialize
types and long or short types.
variables properly, otherwise sometimes program would
 Floating-point literals
produce unexpected result.
They are constants that have an integer part, a decimal
point, a fractional part, and an exponent part. You can

Email: Kioko@cuea.edu Mobile:-+254-725-695-782

© By Edward Kioko. All rights reserved for this module. No part of this module may be reproduced or transmitted in any form or by any means,
electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the author
CMT 110: PROGRAMMING METHODOLOGY

represent floating point literals either in decimal form or  String literals


exponential form.
They are constants enclosed in double quotes. A string
contains characters that are similar to character literals:
 Boolean literals
plain characters, escape sequences, and universal
They are constants that can hold either a true or a false
characters. A typical example is presented below
value.
"Hello, welcome to C programming"
 Character literals
3.10.2 Declaring variables
They are usually enclosed in single quotes. If the literal
 Using the const Keyword
begins with L (uppercase only), it is a wide character literal
The const keyword can be used to define constants as
(e.g., „Y‟') and should be stored in wchar_t type of variable.
shown in the following syntax
Otherwise, it is a narrow character literal (e.g., 'y') and can
Const type ConstName = value;
be stored in a simple variable of char type.

An example of the same is presented below


A character literal can be a plain character (e.g., 'y'), an
escape sequence (e.g., '\n'), or a universal character (e.g.,
 Using the #define pre-processor
'\u02C0').
This format has the following general syntax
#define identifier value

Email: Kioko@cuea.edu Mobile:-+254-725-695-782

© By Edward Kioko. All rights reserved for this module. No part of this module may be reproduced or transmitted in any form or by any means,
electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the author
CMT 110: PROGRAMMING METHODOLOGY

The same example above is presented below \r Carriage return


\t Horizontal tab
Note that it is a good programming practice to define constants
in CAPITALS. A good use of escape sequence is presented below
3.11 Escape sequence #include<stdio.h>
In C, certain non-printing characters are used as in-built Void main( )
commands. Escape sequence are usually preceded by back {
slash sign (\). Here, you have a list of some of such escape printf( "Hello\t welcome\t to C programming\n"); return 0;
sequence codes: }

Escape sequence Description Output: Hello welcome to oop

\\ \ character 3.12 Operators in C


An operator is a symbol that tells the compiler to perform
\' ' character
specific mathematical or logical manipulations. C programming
\" " character
has a rich in built-in operators and provides the following types
\? ? character
of operators:
\a Alert or bell  Arithmetic Operators
\b Backspace  Relational Operators
\f Form feed  Logical Operators
\n Newline  Bitwise Operators

Email: Kioko@cuea.edu Mobile:-+254-725-695-782

© By Edward Kioko. All rights reserved for this module. No part of this module may be reproduced or transmitted in any form or by any means,
electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the author
CMT 110: PROGRAMMING METHODOLOGY

 Assignment Operators ++ Increment operator, increases X++ will yield 16


 Misc Operators integer value by one
-- Decrement operator, decreases Y++ will yield 9
This module shall examine the arithmetic, relational, logical &
integer value by one
assignment operators into detail.
3.12.2 Relational/comparison Operators
3.12.1 Arithmetic Operators
C programming language supports the following relational
C as a programming language supports the following arithmetic
operators. Assume we have two variables; x holds 15 and y
operators. Assume we have two variables; x holds 15 and y
holds 10, then;
holds 10, then;
Operator Description Example
Operator Description Example
== Checks if the values of two (X==Y) is not true
+ Adds two operands X+y will yield 25
operands are equal or not, if yes
- Subtracts second operand from x-y will yield 5
!= Checks if the values of two (X!=Y) is true
the first
operands are equal or not, if
* Multiplies two operands X*y will yield 150
values are not equal then
/ Divides two operands x/y will yield 1
condition becomes true.
% 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

Email: Kioko@cuea.edu Mobile:-+254-725-695-782

© By Edward Kioko. All rights reserved for this module. No part of this module may be reproduced or transmitted in any form or by any means,
electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the author
CMT 110: PROGRAMMING METHODOLOGY

value of right operand, if yes the value of right operand, if yes true
then condition becomes true. then condition becomes true.
< Checks if the value of left (X<Y) is not true 3.12.3 Logical Operators
operand is less than the value There are following logical operators supported by C language.
of right operand, if yes then The result of logical operators can only be a Boolean value; true
condition becomes true. or false. Assume variable x holds 1 and variable y holds 0, then:
>= Checks if the value of left (X>=Y) is true
operand is greater than or equal
to the value of right operand, if
yes then condition becomes
true.
>= Checks if the value of left (X>=Y) is true
operand is greater than or equal
to the value of right operand, if
yes then condition becomes
true.
<= Checks if the value of left (X<=Y) is not
operand is less than or equal to

Email: Kioko@cuea.edu Mobile:-+254-725-695-782

© By Edward Kioko. All rights reserved for this module. No part of this module may be reproduced or transmitted in any form or by any means,
electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the author
CMT 110: PROGRAMMING METHODOLOGY

Operator Description Example = assignment operator, It equivalent to x = x


&& Called Logical AND operator. If (X&&Y) is false multiplies right operand with the *y
both the operands are non zero left operand and assign the
i.e. then the condition becomes result
true. to left operand
|| Called Logical OR Operator. If (X||Y) is true /= Its known as Divide AND /= y is equivalent
any of the two operands is assignment operator, It divides to x = x /y
nonzero, then condition left operand with the right
becomes true. operand and assign the result to
! Called Logical NOT Operator. !(X||Y) is false left operand
Used to reverses the logical
%= Its known as Modulus AND %= y is equivalent
state of its operand. If a condition
assignment operator. It takes to x = x
is true, then Logical NOT
modulus using two operands %y
operator will make false.
and assign the result to left
operand
3.12.4 Assignment Operators
C supports the following assignment operators. Assume x hold
15 and y holds 10, then;

Email: Kioko@cuea.edu Mobile:-+254-725-695-782

© By Edward Kioko. All rights reserved for this module. No part of this module may be reproduced or transmitted in any form or by any means,
electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the author
CMT 110: PROGRAMMING METHODOLOGY

3.12.5 Misc Operators 3.13 Precedence and nesting parentheses


The use of parentheses (brackets) is advisable to resolve
Operator Operator description
ambiguity. The order of execution of mathematical operations
* Pointer operator * is pointer to a variable. For
is governed by rules of precedence. Certain operators have
example *studname; will pointer to a variable
higher precedence than others. Parentheses are always
name studname.
evaluated first, followed by multiplication, division and modulus
Pointer operator & returns the address of a operations. Addition and subtraction are last. For example
& variable. For example &studname will return
4 + 2 * 3 equals 10
the actual address of the variable studname.
(4+2) * 3 equal 18
Casting operators which are used to convert
one data type to another. For example,
Cast For example x =10 + 8/ 4; here, x is assigned 12 since operator
Float sum=2.200;
*/ has higher precedence than +, so we first divide 8 by 4 to get
(Int) sum returns 2 instead of 2.200. 2 then add that two to 10 to get 12
Known as sizeof operator returns the size of a 3.14 Operators Precedence in C
sizeof variable. For example, sizeof (x), where x is Here, operators with the highest precedence appear at the top

integer or float will return 4. of the table, those with the lowest appear at the bottom.
Operator precedence determines the grouping of terms in an
Condition? X : Conditional operator. If Condition is true? then it
expression, higher precedence operators will be evaluated first.
Y returns value X : or else value Y
expression. This affects how an expression is evaluated.

Email: Kioko@cuea.edu Mobile:-+254-725-695-782

© By Edward Kioko. All rights reserved for this module. No part of this module may be reproduced or transmitted in any form or by any means,
electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the author
CMT 110: PROGRAMMING METHODOLOGY

Category Operator Associativity Comma ,


Postfix () [] -> . ++ - Left to right
- 3.15 Assignment in C++
Unary + - ! ~ ++ - - Right to left Every variable in a program must be assigned (allocated) a
(type)*
value explicitly before any attempt is made to use it. It is also
&sizeof
Multiplicative */% Left to right important that the value assigned is of the correct type. This one
Additive +- Left to right is achieved using the assignment operator to this (=).
Shift <<>> Left to right Assignment is always done from left to right. Though the
Relational <<= Left to right
assignment operator looks like the mathematical equality
>>=
Equality == != Left to right operator, in programming, it’s a meaning is different. The
Bitwise AND & Left to right symbol simply indicates that the value on the right hand side of
Bitwise XOR ^ Left to right the assignment operator (=) symbol must be stored (assigned)
Bitwise OR | Left to right
to the variable named on the left hand side.
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left Ideally, the operator should be read as “becomes equal to” and
Assignment = += -= *= Right to left means that the variable on the left hand side has its value
/= %=>>=
<<= &= ^= changed to the value of the expression on the right hand side.
|=
Left to right

Email: Kioko@cuea.edu Mobile:-+254-725-695-782

© By Edward Kioko. All rights reserved for this module. No part of this module may be reproduced or transmitted in any form or by any means,
electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the author
CMT 110: PROGRAMMING METHODOLOGY

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
%d is a conversion specifier indicating that the type of the
The general format is as follows corresponding variable to be printed is integer
Variable=expression;
3.17 Input in c
Where expression is the value we are assigning to the variable. scanf ( ) is used to read values from the keyboard then assign
A good example is presented below whereby the programs them to specified variable(s). E.g. scan("%d", &x); read a
takes the values of a and b, sums them together and assigns decimal integer from the keyboard and store the value in the
the result to a variable known as total i.e. total = a + b; memory address of the variable x
Anytime a variable appears in an expression, it represents the 3.18 scanf( ) Control String Conversion Characters
scanf( ) uses the same format specifier as the printf statement.
value currently stored in that memory location. When an
Arguments of scanf must be pointers to memory address hence
assignment statement is executed, a new value is dropped into
the use of the ampersand sign (&)
the memory location overwriting it with the new one
Character Form of output Expected argument
3.16 Output in C
c Character Pointer to char
To print a value on the console, we always use the function
printf which is defined in the standard library stdio.h in c. An d Decimal integer Pointer to int

example of a printf( ) statement is as follows x Hexadecimal integer Pointer to int

Email: Kioko@cuea.edu Mobile:-+254-725-695-782

© By Edward Kioko. All rights reserved for this module. No part of this module may be reproduced or transmitted in any form or by any means,
electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the author
CMT 110: PROGRAMMING METHODOLOGY

o Octal integer Pointer to int The d, x,o,u or i conversion characters should be preceded by
u Unsigned integer Pointer to int l if the argument is a pointer to a long rather than an a pointer

i Integer Pointer to int to an int , or by h of the argument is a pointer to short int .

e Floating point number Pointer to float


The e, f, or g conversion characters should be preceded by l if
f Floating point number Pointer to float
the argument is pointer to double rather than pointer to float,
g Floating point number Pointer to float
or L for pointer to long double.
s String Pointer to char
Maximum field widths can be specified between the % and the
p Address format, depends Pointer to void
conversion character. For example, the following call to scanf
on system
will read no more than 40 characters into the string variable
string str;
The conversion characters e, f and g have exactly the same
scanf ("%40s", str);
effect. They read a floating point number which can be written
A*between the % and the conversion character indicates that
with or without an exponent.
the field should be skipped.
When reading integers using the i conversion character, the
data entered may be preceded by 0 or 0x to indicate that the
Other characters that appear in the format string must be
data is in octal (base 8) or hexadecimal (base16).
matched exactly in the input.

Email: Kioko@cuea.edu Mobile:-+254-725-695-782

© By Edward Kioko. All rights reserved for this module. No part of this module may be reproduced or transmitted in any form or by any means,
electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the author
CMT 110: PROGRAMMING METHODOLOGY

3.19 Character I/O — getchar ( )& putchar ( )


They are used to for the input and output of single characters
respectively. getchar() returns an int which is either EOF or the
next character in the standard input stream. putchar(c) puts the
character c on the standard output stream.

void main()
{
int a; a = getchar(); /* read a character and assign to c */
putchar(c); /* print c on the screen */
}

3.12.6

Email: Kioko@cuea.edu Mobile:-+254-725-695-782

© By Edward Kioko. All rights reserved for this module. No part of this module may be reproduced or transmitted in any form or by any means,
electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the author

You might also like