0% found this document useful (0 votes)
18 views12 pages

Structure of C program and Operators

The document outlines the structure of C programs, detailing components such as preprocessor directives, global variables, the main function, and other functions. It also explains lexical elements like identifiers, constants, reserved keywords, variables, data types, and operators, along with their respective rules and examples. Additionally, it covers input/output functions, operators, and syntax for comments and escape sequences in C programming.

Uploaded by

Bethwel Kipruto
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)
18 views12 pages

Structure of C program and Operators

The document outlines the structure of C programs, detailing components such as preprocessor directives, global variables, the main function, and other functions. It also explains lexical elements like identifiers, constants, reserved keywords, variables, data types, and operators, along with their respective rules and examples. Additionally, it covers input/output functions, operators, and syntax for comments and escape sequences in C programming.

Uploaded by

Bethwel Kipruto
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/ 12

STRUCTURE OF C PROGRAMS

C is a structured programming language made up of procedures (functions) that consist of declarations and
other statements. Generally a C program consists of one or more functions of which main is a special function.
The other functions may be from the C library or user defined. All the statements under the functions should be
present within curly brackets ({}) and each statement should be delimited by a semicolon (;).
C program structure consists of the following parts
i). Preprocessor directives.
ii). Global variables and function declarations
iii). Main function.
iv). Other functions

i). Preprocessor directives


It’s a command to the C preprocessor, which is a program that performs some operations on the source file
before compilation begins. There are three types of preprocessor directives, namely
• Inclusion (# include)
• Macro subsituation (# define)
• Conditional (# if)
E.g. the # include <stdio.h> is a command which informs the preprocessor to include information in the file
stdio.h, which contains the basic input/output. .h indicates that the file is a header file, which is placed at the
beginning of a program.
Note: The preprocessor directives can optionally be present in a program.

ii). Global variable and function declarations.


Outside the main function, variables and function declarations can optionally be declared such variables and
functions are global and hence available to all functions.

iii). Main function


It refers to the main function of any C program. C compilers will start execution from this function and
hence any C program must contain one function bearing the main function.

iv). Other functions.


All other functions called from main or any other function can be present after the statement of main.
N/B – a function is a collection of statements wit a well defined task.

The following is a basic structure of any C program.

Header file declaration


Constant value declaration
Function prototype declaration
Global variable declaration list
void main()
{
local variable declaration list

statement1;
|
|
statement n;
}

Programming Notes ~ Wainaina Page 1 of 12


Function header
{
local data declaration list
statement1;
|
|
statement n;
[return value]; /* optional */
}

LEXICAL ELEMENTS OF A C LANGUAGE

I). Identifier
This is a general name that refers to variable names, constant names, function names etc
It should be made up of a sequence of characters consisting of letters ‘a’ to ‘z’, digits ‘0’ to ‘9’ and the
underscore ‘_’.

II). Constant.
It refers to an identifier that represents values that cannot be changed during the execution of a program. Each
constant has a type that is determined by its form and value. The constants are classified into the following:
i) Numeric constant.
ii) Character constant.
iii) String constant

i) Numeric constant.
Is a constant made up of numeric digits with optional presence of a decimal point. There are two types,
namely
a) Integer – Refers to a sequence of numeric digits without a decimal point (whole numbers).
b) Floating point numeric constant – Refers to sequence of numeric digits with a decimal point
(fractional numbers).

ii) Character constant.


Refers to a single character enclosed in single quotes. Escape sequences are character constants though
they are represented by two characters.

iii) String constant


It refers to sequence of zero or more characters surrounded by double quotes. Generally it’s an array of
character constants whose last character is \0.

III). Reserved/key words


This refers to reserved words that have a special meaning in a language and the compiler recognize them as
a keyword. They cannot be used for any other purpose such as a variable or function name. C key words
must be in lowercase otherwise they won’t be recognized.
The following is a list of some reserved words.

auto double int struct


break else long switch
case enum register typedef
char extern return union

Programming Notes ~ Wainaina Page 2 of 12


const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

IV). Variables
A variable is a location in the computer’s memory where a value can be stored for use by a program.
Or A variable is placeholder in which variables are recalled at will.
Values stored in variables can change during program execution, although the value of the variable may change
the place in memory where it’s stored remains the same. Variables have a name and values.

Variable names.
It refers to valid identifiers used to identify storage locations whose values may vary during execution of the
program. In most cases, variables are named with description that transmits the idea of what value it holds.

Rules for naming variables.


1. Variable names consist of letters, digits and underscores. Other special characters and embedded spaces are
not allowed.
2. The first character should be a letter or an underscore, and then it can be followed by letters, digits or
underscores.
3. Upper and lower cases are significant. Though both the cases are allowed, usually C variables are in lower
case.
4. Key words cannot be variable names.
5. Only the first six characters are significant on a standard C compiler though in some C compilers, 31
characters are significant.

V). Data types.


A data type refers to the type of information held in a C variable. C supports the following data types.
• Integer
• Floating point
• Double
• Character

i) Integer: - It refers to whole numbers, both positive and negative. Unsigned integers refer to positive
values only. In addition, there are long and short integers. The keyword used to define integers is int
and it holds two bytes of memory space. The following is an example an integer declaration and
initialization.
int sum;
sum = 20;

ii) Floating point: - These are numbers that contain fractional parts both positive and negative. The
keyword used to define float variables is “float” and it occupies four bytes of memory space. An
example of declaring and initializing a float variable is as follows;
float number;
number = 0.123;

iii) Double: - It refers to exponential numbers, both positive and negative. The key word used to define
double variables is “double” and it occupies 8 bytes of memory space. The following is an example
of declaring and initializing a double variable.

Programming Notes ~ Wainaina Page 3 of 12


double big;
big = 3.12E7;

iv) Character: - It refers to a single character. The key word used to define character variables is “char”
and it holds one byte of memory space. An example of a character variable declaration and
initialization is as follows.
char letter;
letter = ‘A’

Variable declaration Statement


It refers to a statement that ensures appropriate memory space is reserved for the variable depending on the data
type of the variable i.e. amount of storage which a variable is to represent.
Syntax:
data_type variable_list;

Example.
A program illustrating the various data types

#include <stdio.h>
void main ( )
{
int sum;
float number;
double big;
char letter;
sum = 20;
number = 0.123;
big = 3.12e7;
letter =‘A’;
printf ("The value of sum is %d\n", sum);
printf ("The value of number is %f\n", number);
printf ("The value of big is %e\n", big);
printf ("The value of letter is %c\n", letter);
}

VI). Delimiters.
A delimiter is a symbol that has a syntax meaning and significance but doesn’t specify any operation to yield a
value.
The following are delimiters used in C language.

• Hash (#) – preprocessor directives.


• Comma (,) – a variable delimiter in a variable list.
• Semi colon (;) – a statement delimiter.
• Colon (:) – a label delimiter.
• Parenthesis ( ) – a delimiter used in expressions.
• Square brackets [ ] – a delimiter used with arrays.
• Braces { } – a delimiter used to block C statements.

Programming Notes ~ Wainaina Page 4 of 12


VII). Statement:
This is a complete unit of instruction for the computer to process

A statement block is a group of statements surrounded by curly braces. C views a statement block as one
statement. The last statement executed becomes the value of the statement block.
In C statement blocks are enclosed in pairs or curly brackets {....} as shown below:
{
statement_1;
statemrnt_2;
statemrnt_3;
.....
statement_n;
}

Types of Statements
Assignment statement: - It uses the assignment = to give or assign the variables on operators left side a value
to the operators right side or the result of an expression on the right side.

Expression statement: - Is a statement that evaluates to a value. Generally, it’s a combination of operators,
constants, variables and function calls. The expressions are classified as arithmetic, relational and logical

VIII). Escape sequence


They are character combination that start with a backslash symbol and are used to format output and represent
difficult to type characters.
The following is a list of escape sequence characters.

Escape sequence Meaning.


\a alert bell
\b backspace
\f form feed
\n new line
\r carriage return
\v vertical tab
\t horizontal tab
\\ back slash
\o null
\’ single quote.

IX). Labels.
These are identifiers used with a statement so that the statement can be referred to later during execution of a
program. The rules used to name labels are the same as those of variables. Labels are usually the targets of the
goto statements.

Label_identifier:

X). Comments
These are non-executable program statements meant to enhance program readability and allow easier program
maintenance. Comments are usually optional in the program. The need for use of too many comments can be
avoided by good programming practices, such as use of sensible variable names, indenting program statements
and good logic design.

Programming Notes ~ Wainaina Page 5 of 12


Syntax
1. One line comment
/* Comment */

2. Multiple line comment.


/* Multi lines comment that
span move that one line */

XI). Conversion Specification Characters


These are characters used to provide type and size of the data. The following are the various types of
conversion specification characters

Modifier Meaning
d Decimal integer
f Floating point number

c Single character

s A sequence of characters
h Short integer
l Long integer
e Double floating point numbers
u Unsigned integer
o Octal numbers
x Hexadecimal numbers

Programming Notes ~ Wainaina Page 6 of 12


INPUT AND OUTPUT IN C

C language has no input/output facilities but relies on libraries of input/output functions.

Input Functions
These are inbuilt C functions used to read data to the computer. Input data can be users’ data entry through the
keyboard, or a file stored in a secondary device such as a disk, tape e.t.c

The following is an example of input functions.


i) scanf ()
ii) getch ()

scanf: This is an inbuilt C function, which is used to perform formatted input and reads all types of values.
The function has atleast two arguments
Syntax
scanf (control string, variable list);

Control string: – it refers to the conversion specification characters and determines the number or arguments
that will follow it. It should be given within double quotes (“”).
Variable list: – It refers to variable names. An ampersand (&) symbol should precede each numeric and
character type variable by which the address of the variable is denoted.

Output Functions.
These are inbuilt C functions used to obtain (write) information from a program. The user can get the result or
data on the monitor or data can be written to another file in a secondary storage device, such as a disk or a tape.
The following are examples of output functions.
i) printf ()
ii) putch ()

printf: This is an inbuilt C functions that is used to perform formatted output and used to write all type of
values.
Syntax
printf (control string, variable list);

Control string: – It contains the conversion specification characters along with string constants. The number of
conversion specification characters determines the number of variables that follow it. It should be given within
double quotes (“”)
Variable list: – It refers to the variable names or expressions that can optionally be present in printf function.

Note:
To format input or output is to control how data is read or written, to convert input to the desired type (int, char,
float, etc) and to write output in the desired manner.

Programming Notes ~ Wainaina Page 7 of 12


OPERATORS
An operator is a symbol that specifies an operation to be performed on an operand to yield a value. An operand
is an entity on which an operator acts.
Generally operators can be categorized as follows: -
i) Unary operators – requires one operand
ii) Binary operators – requires two operands.
iii) Ternary operators – requires three operands.

The following are the different types of C language operators: -


1. Arithmetic
2. Relational
3. Logical
4. Assignment

1) Arithmetic operators
It refers to operators used for mathematical calculations. Arithmetic expressions consist of constants,
variables, function calls and arithmetic operators.

The following is a list of binary arithmetic operators.

Operator Operation Comment Value of Value of


sum sum after
before
* Multiply Sum = sum*2 4 8
/ Divide Sum = sum/2 4 2
+ Addition Sum = sum+2 4 6
- Subtraction Sum = sum-2 4 2
% Modulus Sum = sum%2 4 0

N/B: A modulus operator assigns the remainder left over after division of two integer numbers. Modulus
operator cannot be applied with floats or doubles.

Hierarchy of operations
The following is the hierarchy of operations followed by C compilers when executing the arithmetic
expressions
• * / % Evaluated from left to right
• + - Evaluated from left to right
However the sub expressions within parenthesis are evaluated first.

Example
Evaluate the following expression
(i + j) /k * n % m – 5 * 6
Where
i = 2, j = 1, k = 7, n = 4, m = 6

Programming Notes ~ Wainaina Page 8 of 12


2) Relational Operators.
These operators used to test relation between two operands to return zero when the relation is false and non-
zero when the relation is true.

Operator Meaning
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal to
!= Not equal to.
Relational operators are binary operators and hence they require two operands.

Hierarchy of operations
There’s no hierarchy for these operators. The expressions are evaluated first and then the relation is tested.

Note: - Arithmetic operators have higher precedence than relational operators

3) Logical / Boolean Operators.


It refers to operators that are used to test the condition of one or more expressions to return the logical status
(true/false) as a net result.
The logical operators are unary or binary operators. The operands maybe constants, variables or other
expressions.
The following is a list of logical operators.
i). AND (&&) - It returns true when both of its operands are true and returns false otherwise.
ii). OR (||) – It returns true when either of its operands are true and returns false otherwise.
iii). NOT (!) – It returns true when its operand result is false and false otherwise.
iv). EOR (^) – It returns true if either condition is true and false otherwise.

The truth table for logical operators.

X Y X&&Y X || Y !X X^Y
T T T T F F
F T F T T T
T F F T T
F F F F F

Assignment operators
It refers to operators used to store a value in a variable for future reference. The following are different types
of assignments.

i). General assignment: – It is used to assign a variable with the result of an expression or value.
Syntax:
Variable = expression;
E.g. area = length * width;

Programming Notes ~ Wainaina Page 9 of 12


ii). Declaration assignment: – This is initialization of variables at the time of declaration.
Syntax
datatype variable = value;
E.g. int count = 1;

iii). Multiple assignment: – This occurs when more than one variable is assigned with single value or
expression. This is a distinct feature of C language.
Syntax
Variable1 = Variable2 = Variable3… =value/expression.
E.g. k = m = n = 1;

iv). Updation assignment statements:


Consider the statement below,
x = x + 3;
In this given case ‘x’ is repeated on the right hand side of the assignment operator. This can be reduced
as shown below.
x + = 3.
This type of updating a variable with most of the arithmetic operators +, -, /, *, % is called updation
assignment and is a distinct feature of C language.
Syntax.
Variable operator = expression/ value

Example
a) int count = 2;
count * = 2;

b) int count = 2;
count % = 2;

c) int a=4, b=2, d=2


d*= (a+b)/2;

Increment and Decrement Operators.


i). Increment operator (++): -
It refers to a unary operator used to add one to the value of the variable.
Example.
cout count = 4;
count ++;

ii). Decrement operator (--): -


It refers to a unary operator used to subtract one from the value of the variable
Example.
int count = 4;
count --;

Prefix Notation and Postfix Notation.


Prefix means that you do the operation first followed by any assignment operation. Postfix means that you
do the operation after any assignment operation.
Note: It makes no difference if the operator is not used in as part of the larger assignment expression.

Programming Notes ~ Wainaina Page 10 of 12


Examples
Find the computed value after the following statements are executed

a) int count = 0,answer; /* Prefix notation */


answer = ++ count;

b) int count = 0,answer; /* Postfix notation */


answer = count ++;

c) int i=5,j;
j = ++ i + 5

d) int i=5,j;
j = i -- + 5

Conditional Expression Operator


This operator takes three operands. The symbols used for these operands are? :
Syntax
Condition? Expression1: Expression2

If the results of the condition are true, Expression1 is evaluated and the result of the evaluation becomes the
result of the operation. If the condition is false, Expression2 is evaluated and its result becomes the result of
the operation.

Example
i) Given the following declaration and assignment statement:
int s, x= -2;
Evaluate the value of s after the following line of code is executed
s = (x>0)? –1: x*x;
Solution
s=4

ii) The following is the same C programs written using if…else control statements and conditional
expression operator

# include <stdio.h>
void main ( )
{
int number;
printf ("Enter an integer number\n");
scanf ("%d", &number);
if (number <0)
printf ("NEGATIVE\n");
else if ( number >0)
printf ("POSITIVE\n");
else
printf ("ZERO\n");
}

Programming Notes ~ Wainaina Page 11 of 12


# include <stdio.h>
void main ( )
{
int number;
printf ("Enter an integer number\n");
scanf ("%d", &number);
(number<0)? printf ("NEGATIVE\n"):
(number>0)? printf ("POSITIVE\n"):
printf (“ZERO\n”);
}

Exercise
(1). Given the following declaration and assignment states
int x=9,y=5,z=4;
float v=5.0;
Evaluate the value of x after each of the following lines of code is executed
(NB: The lines of code are independent of one another)
i) x=++x+5;
ii) x+=z--+5;
iii) x+=y%2;
iv) x=z%v;
v) x%=y+z*z%y;

(2). Write the following mathematical expression as a C statement.

x= - b √ (b2 + 4ac);

Programming Notes ~ Wainaina Page 12 of 12

You might also like