SP - 1 C Introduction pg-17-31
SP - 1 C Introduction pg-17-31
SP - 1 C Introduction pg-17-31
3. PROGRAM STRUCTURE
STRUCTURE OF A C PROGRAM
The C programming language was designed by Dennis Ritchie as a systems programming
language for Unix.
Example:
#include <stdio.h>
int main()
{
/* My first program*/
printf("Hello, World! \n");
return 0;
}
Preprocessor Commands
These commands tell the compiler to do preprocessing before doing actual compilation. Like
#include <stdio.h> is a preprocessor command which tells a C compiler to include stdio.h file
before going to actual compilation. The standard input and output header file (stdio.h) allows the
program to interact with the screen, keyboard and file system of the computer.
NB/ Preprocessor directives are not actually part of the C language, but rather instructions from you
to the compiler.
Functions
These are main building blocks of any C Program. Every C Program will have one or more
functions and there is one mandatory function which is called main() function. When this function
is prefixed with keyword int, it means this function returns an integer value when it exits. This
integer value is retuned using return statement.
The C Programming language provides a set of built-in functions. In the above example printf() is a
C built-in function which is used to print anything on the screen.
A function is a group of statements that together perform a task. A C program can be divide up
into separate functions but logically the division usually is so each function performs a specific task.
A function declaration tells the compiler about a function's name, return type, and parameters. A
function definition provides the actual body of the function.
The general form of a function definition in C programming language is as follows:
17
return_type function_name( parameter list )
{
body of the function/Function definition
}
Variable Declarations
In C, all variables must be declared before they are used. Thus, C is a strongly typed programming
language. Variable declaration ensures that appropriate memory space is reserved for the variables.
Variables are used to hold numbers, strings and complex data for manipulation e.g.
Int x;
Int num; int z;
Statements in C are expressions, assignments, function calls, or control flow statements which
make up C programs.
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 an expression on the right.
z = x + y;
Comments
These are non-executable program statements meant to enhance program readability and allow
easier program maintenance- they document the program. They are ignored by the compiler.
These are used to give additional useful information inside a C Program. All the comments will be
put inside /*...*/ or // for single line comments as given in the example above. A comment can span
through multiple lines.
/* Author: Mzee Moja */
or
/*
* Author: Mzee Moja
* Purpose: To show a comment that spans multiple lines.
* Language: C
*/
or
Fruit = apples + oranges; // get the total fruit
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.
They include:
\a Alert/bell
\b Backspace
\n New line
\v Vertical tab
\t Horizontal tab
\\ Back slash
\’ Single quote
18
\” Double quote
\0 Null
Keywords
The following list shows the reserved words in C. These reserved words may not be used as
constants or variables or any other identifier names.
19
case extern return union
char float short unsigned
const for signed void
continue goto sizeof volatile
default if static while
do int struct _packed
double
Linking is the process where the object code, the start up code and the code for library routines
used in the program (all in machine language) are combined into a single file- the executable file.
If the compiled program can run on a computer whose CPU or operating system is
different from the one on which the compiler runs, the compiler is known as a cross-
compiler.
A program that translates from a low level language to a higher level one is a
decompiler.
Library Functions
There is a minimal set of library functions that should 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() which is a general purpose
output function. The quoted string between the parenthesis of the printf() function is called an
argument.
Printf(“This is a C program\n”)
The \n at the end of the text is an escape sequence tells the program to print a new line as part of
the output.
20
C DATA TYPES
In the C programming language, data types refer to a system used for declaring variables or
functions of different types. A data type is, therefore, a data storage format that can contain a
specific type or range of values. The type of a variable determines how much space it occupies in
storage and how the bit pattern stored is interpreted.
Long
Sometimes while coding a program, we need to increase the Storage Capacity of a variable
so that it can store values higher than its maximum limit which is there as default.
This can be applied to both int and double. When applied to int, it doubles its length, in
bits, of the base type that it modifies. For example, an integer is usually 16 bits long.
Therefore a long int is 32 bits in length. When long is applied to a double, it roughly
doubles the precision.
Short
A “short” type modifier does just the opposite of “long”. If one is not expecting to see high
range values in a program.
For example, if we need to store the “age” of a student in a variable, we will make use of
this type qualifier as we are aware that this value is not going to be very high
The type modifier precedes the type name. For example this declares a long integer.
21
Integer Types
Following table gives you details about standard integer types with its storage sizes and value
ranges:
Type Storage size Value range
Char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
Int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to
2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
Short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
Long 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295
Floating-Point Types
Following table gives you details about standard floating-point types with storage sizes and value
ranges and their precision:
Type Storage size Value range Precision
float 4 byte 1.2E-38 to 3.4E+38 6 decimal places
double 8 byte 2.3E-308 to 1.7E+308 15 decimal places
long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places
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.
Variable Declaration
Declaring a variable tells the compiler to reserve space in memory for that particular variable. A
variable definition specifies a data type and the variable name and contains a list of one or more
variables of that type .Variables can be declared at the start of any block of code. A declaration
begins with the type, followed by the name of one or more variables. For example,
Int high, low;
int i, j, k;
char c, ch;
float f, salary;
22
Variables can be initialized when they are declared. This is done by adding an equals sign and the
required value after the declaration.
TYPES OF VARIABLES
The Programming language C has two main variable types
• Local Variables
• Global Variables
Local Variables
A local variable is a variable that is declared inside a function.
• Local variables scope is confined within the block or function where it is defined. Local
variables must always be defined at the top of a block.
• When execution of the block starts the variable is available, and when the block ends the
variable 'dies'.
Global Variables
Global variable is defined at the top of the program file and it can be visible and modified by any
function that may reference it. Global variables are declared outside all functions.
Sample Program.
#include <stdio.h>
int area; //global variable
int main ()
{
int a, b; //local variable
/* actual initialization */
a = 10;
b = 20;
area = a*b;
printf("\t The area of your rectangle is : %d \n", area);
return 0;
}
23
Variable Names
Every variable has a name and a value. The name identifies the variable and the value stores data.
Every variable name in C must start with a letter; the rest of the name can consist of letters,
numbers and underscore characters. C is case sensitive i.e. it recognizes upper and lower case
characters as being different. You cannot use any of C’s keywords like main, while, switch etc as
variable names,
It is conventional in C not to use capital letters in variable names. These are used for names of
constants.
Declaration vs Definition
A declaration provides basic attributes of a symbol: its type and its name. A definition provides all
of the details of that symbol--if it's a function, what it does; if it's a class, what fields and methods it
has; if it's a variable, where that variable is stored. Often, the compiler only needs to have a
declaration for something in order to compile a file into an object file, expecting that the linker can
find the definition from another file. If no source file ever defines a symbol, but it is declared, you
will get errors at link time complaining about undefined symbols. In the following short code, the
definition of variable x means that the storage for the variable is that it is a global variable.
int x;
int main()
{
x = 3;
}
The %d is a format specifier which tells the compiler that the second argument will be receiving an
integer value.
The & preceding the variable name means “address of”. The function allows the function to place a
value into one of its arguments.
The table below shows format specifiers or codes used in the scanf() function and their meaning.
24
When used in a printf() function, a type specifier informs the function that a different type item is
being displayed.
int main ()
{
int a, b; //local variables
/* actual initialization */
printf("Enter the value of side a: ");
scanf("%d", &a);
area = a*b;
printf("\t The area of your rectangle is : %d \n", area);
return 0;
}
CONSTANTS
C allows you to declare constants. When you declare a constant it is a bit like a variable declaration
except the value cannot be changed during program execution.
The const keyword is used to declare a constant, as shown below:
int const A = 1;
const int A =2;
TYPE CASTING
Type casting is a way to convert a variable from one data type to another. For example, if you want
to store a long value into a simple integer then you can type cast long to int. You can convert values
from one type to another explicitly using the cast operator as follows:
(type_name) expression
Consider the following example where the cast operator causes the division of one integer variable
by another to be performed as a floating-point operation:
25
#include <stdio.h>
main()
{
int sum = 17, count = 5;
double mean;
When the above code is compiled and executed, it produces the following result:
It should be noted here that the cast operator has precedence over division, so the value of sum is
first converted to type double and finally it gets divided by count yielding a double value.
Type conversions can be implicit which is performed by the compiler automatically, or it can be
specified explicitly through the use of the cast operator. It is considered good programming
practice to use the cast operator whenever type conversions are necessary.
C PROGRAMMING OPERATORS
Operator is the symbol which operates on a value or a variable (operand). For example: + is an
operator to perform addition.
C programming language has a wide range of operators to perform various operations. For better
understanding of operators, these operators can be classified as:
OPERATORS IN C PROGRAMMING
1. Arithmetic Operators
2. Increment and Decrement Operators
3. Assignment Operators
4. Relational Operators
5. Logical Operators
6. Conditional Operators
7. Bitwise Operators
8. Special Operators
ARITHMETIC OPERATORS
Assume variable A holds 10 and variable B holds 20 then
Operator Description Example
+ Adds two operands A + B will give 30
- Subtracts second operand from the first A - B will give -10
* Multiplies both operands A * B will give 200
/ Divides numerator by de-numerator B / A will give 2
% Modulus Operator - remainder of after an B % A will give 0
integer division
26
Note: % operator can only be used with integers.
Let a=5
a++; //a becomes 6
a--; //a becomes 5
++a; //a becomes 6
--a; //a becomes 5
#include <stdio.h>
int main(){
int c=2;
printf("%d\n",c++); /*this statement displays 2 then,
only c incremented by 1 to 3.*/
printf("%d",++c); /*this statement increments 1 to
c then, only c is displayed.*/
return 0;
}
Output
2
4
27
Operator Example Same as
/= a/=b a=a/b
%= a%=b a=a%b
NB/ += means Add and Assign etc.
a>b
Here, > is a relational operator. If a is greater than b, a>b returns 1 if not then, it returns 0.
Meaning of
Operator Example
Operator
If c=5 and d=2 then,((c= =5) && (d>5))
&& Logical AND
returns false.
If c=5 and d=2 then, ((c= =5) || (d>5))
|| Logical OR
returns true.
! Logical NOT If c=5 then, !(c= =5) returns false.
The following table shows the result of operator && evaluating the expression a&&b:
28
The operator || corresponds to the Boolean logical operation OR, which yields true if either of its
operands is true, thus being false only when both operands are false. Here are the possible results
of a || b:
|| OPERATOR (or)
a b a || b
true true true
true false true
false true true
false false false
Explanation
For expression, ((c==5) && (d>5)) to be true, both c==5 and d>5 should be true but, (d>5) is false
in the given example. So, the expression is false. For expression ((c==5) || (d>5)) to be true,
either the expression should be true.
Since, (c==5) is true. So, the expression is true. Since, expression (c==5) is true, !(c==5) is false.
c=(c>0)?10:-10;
If c is greater than 0, value of c will be 10 but, if c is less than 0, value of c will be -10.
BITWISE OPERATORS
Bitwise operators work on bits and performs bit-by-bit operation.
29
PRECEDENCE OF OPERATORS
If more than one operator is involved in an expression then, C language has a predefined rule of
priority of operators. This rule of priority of operators is called operator precedence.
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
ASSOCIATIVITY OF OPERATORS
Associativity indicates in which order two operators of same precedence (priority) executes. Let us
suppose an expression:
a= =b!=c
30
Here, operators == and != have the same precedence. The associativity of both == and != is left to
right, i.e., the expression in left is executed first and execution take pale towards right. Thus,
a==b!=c equivalent to :
(a= =b)!=c
Operators may be left-associative (meaning the operations are grouped from the left), right-
associative (meaning the operations are grouped from the right)
31