CUIITM114 Study Notes
CUIITM114 Study Notes
Program: a set of detailed and unambiguous instructions that instructs a computer to perform
a specific task, for example, to add a set of numbers.
Types of Programs
It is a type of software that is ready-made and available for sale to the general public . It is
designed to provide a general set of features that a broad range of customers will find useful.
The most popular and widely used software is usually off-the-shelf, eg web
browsers, apps and games. Microsoft Office is a COTS product that is a packaged software
solution for businesses, schools, university, general users etc
• Cheaper than custom written (tailor made) packages as development costs are spread
over many users.
• the package is available immediately – no need to wait for development period
• Allows large scale sales which bring in considerable revenue which can be used to
enable a lot of development to be done. .
• They are tried and tested and therefore are free from errors.
• Documentation is always provided in form of manuals, user guides and tutorials that
may be in soft or hardcopy.
• Training courses can be available from other end-users.
• Technical support is always available from other users and from the internet. .
• Upgrades are always available every year or two.
Disadvantages
These are programs specifically designed to meet the unique needs of only one organisation,
for example a bank. The organisation would employ or hire an analyst / programmer who will
first asses the needs of the organisation before designing a program that will solve the
problems of the organisation
➢ Much better customer support since they will be in direct contact with the software
designers.
➢ Specifically designed for the application and therefore more efficient and will only
contain the features wanted by the user.
➢ They can be customised to interface with all other software within the company thus
preventing software clashes
➢ They are easier to use since very specific and the writers of the software can also be
involved in the training of staff which will be geared towards their requirements
➢ They can be modified/updated as the company’s requirements change
Hybrid Software
Hybrid software is the combining of bespoke and off-the-shelf software Hybrid software
combine the trust and reliability that comes with an off the shelf software with the
personalisation and individuality that comes with bespoke software. Off the shelf software is
modified with permission from the copyrights holder to add features that are specific in
solving the problems of an organisation or group of users
Programming Languages
Are a vocabulary or set of grammatical rules (syntax) and set of symbols for instructing a
computer to perform specific tasks. .Programming languages are used to create computer
programs.
Examples include
• Pascal
• C
• C++
• Java
• Python
• C#
• PHP etc
These are programming languages used to write programs in machine code (i.e in 1s and 0s)
or in mnemonic codes. Low level languages are machine oriented (machine specific).
Low level language is in two forms:
Machine language is the “natural language” of a computer which it understands and as such
is defined by its hardware design.
Machine languages are machine dependent (i.e., a particular machine language can be used
on only one type of computer)
The language used to write programs in binary form (1s and 0s).
Machine code executes without translation.
Advantages:
▪ Programs run faster since they are already in computer language. There is no need for
conversion as programs are in machine language.
▪ Programs occupy very small disc storage space by storing just 1s and 0s.
Assembly Language:
These are programming languages that use mnemonic codes in writing programs.
Mnemonic codes are abbreviations used to represent instructions when coding assembly
language programs, for example, LDA for Load, ADD for Addition, etc.
Although these codes are clearer to humans, it’s incomprehensible to computers until
translated to machine language.
One assembly language statement is equivalent to one machine code instruction and therefore
programming is lengthy and time consuming.
However, assembly language programs are efficient. Programs also run faster as they are
closer to machine language and therefore are used in designing programs that needs efficient
timing,
.
▪ One assembly language instruction corresponds to one machine code instruction and
therefore translation is easier and faster to code.
▪ Programs run faster since they are close to machine code.
▪ They occupy very small disk storage space hence are economical to use.
▪ Easier for a programmer to use than machine language.
These are programming languages that use English-like statements in writing programs, for
example C, Pascal, C++, Java etc.
There are so many high level languages because of competition from designers who want to
outpace each other.
It can also be due to the fact that we have so many application areas in real life so each high
level language is designed for a specific problem (problem oriented/problem specific) to be
solved in our daily lives, for example BASIC was designed for learning purposes, PHP for
web designing, FORTRAN for scientific purposes, etc.
Programs written in High Level Language are first converted to machine code before
running.
Disadvantages of HLL
▪ Takes long to run since they need to be first converted to machine code.
▪ They occupy a lot of disk storage space as compared to low level languages.
Source code
Source code is the set of instructions and statements written by a programmer using a
computer programming language. This code is later translated into machine language by a
compiler. The translated code is referred to as object code. Source code is the source of a
computer program. It contains declarations, instructions, functions, loops and other
statements, which act as instructions for the program on how to function. Programs may
contain one or more source code text files, which can be stored on a computer's hard disk, in
a database, or be printed in students of code snippets.
Object Code
Object code is produced when an interpreter or a compiler translates source code into
recognizable and executable machine code.
Object code is a set of instruction codes that is understood by a computer at the lowest
hardware level. Object code is usually produced by a compiler that reads some higher level
computer language source instructions and translates them into equivalent machine language
instructions.
A compiler translates source code into object code, which is stored in object files. Object
files contain object code that includes instructions to be executed by the computer. It should
be noted that object files may require some intermediate processing by the operating system
(OS) before the instructions contained in them are actually executed by the hardware.
Executable code
Executable Code is the fully-compiled version of the Software program that can be executed
by a computer and used by an end user without further compilation. It is software in a form
that can be run in the computer. It typically refers to machine language, which is the set of
native instructions the computer carries out in hardware. Executable files in the
DOS/Windows world use .EXE and .COM file extensions
Introduction to C
The C has now become a widely used professional language for various reasons.
1. Easy to learn
2. Structured language
Application of C
▪ Operating Systems
▪ Language Compilers
▪ Assemblers
▪ Text Editors
▪ Print Spoolers
▪ Network Drivers
▪ Modern Programs
▪ Databases
▪ Language Interpreters
▪ Utilities
▪ Etc
2 A compiler to convert a source code into an executable code eg GNU C/C++ compiler
OR
Download DEV C++ IDE for free on the internet and Install on your computer
Step1
Step 2
▪ Click on File
▪ Select New
▪ Click on Project
▪ Select Console Application ,Select C Project and Enter name of Project eg
MyFirstProgram
Then Click OK
Step 3
#include <stdio.h>
int main()
return 0;
Stage 3
Output
Basics of C
Structure of a C pogram
• Preprocessor Commands
• Functions
• Variables
• Comments
Simple C program
return 0;
Preprocessor directives
#include<stdio.h> tells the compiler to include information about the standard input/output
library.It is a directive to the C preprocessor. Lines beginning with # are processed by the
pre-processor before compilation . The stdio.h (standard input output header file) contains
definition & declaration of system defined function such as printf( ), scanf( ), pow( )
etc.Generally printf() function used to display and scanf() function used to read value
Main() function
It is the user defined function and every function has one main() function from where actually
program is started and it is encloses within the pair of curly braces.
The main( ) function can be anywhere in the program but in general practice it is placed in
the first position.
Syntax :
main()
……..
……..
……..
The program execution start with opening braces and end with closing brace. A start brace, {,
begins the body of every function . A corresponding stop brace ends each function . This pair
of braces and the portion of the program between the braces is called a block
Comments
Comments are used for increasing the readability of the program. It is useful in explaining the
program and generally used for documentation. It is enclosed within the decimeters.
Comment line can be single or multiple line but should not be nested. It can be anywhere in
the program except inside string constant & character constant.
//single linecomment
Statements
The statement instructs the computer to perform an action, namely to print on the screen the
string of characters marked by the quotation marks. The semicolon (;), is called a statement
terminator .Every statement in a C program must end with a semicolon
When the preceding printf statement is executed, it prints the message Welcome to the world
of C on the screen. The characters normally print exactly as they appear between the double
quotes in the printf statement
Exercise 1
1) An identifier should only consists of alphabetic letters (both upper and lower case from A-
Z,a-z), digits and underscore (_) sign.
4) C is a case sensitive, the upper case and lower case are different, for example Aecs103,
AECS103, aecs103 etc. are different identifiers
5) Spaces are not allowed in an identifier for example AECS 103 will produce an error
because of the space between AECS and 103 the correct way to write the identifier is
AECS103 or AECS_103(using an underscore)
Variables
Variable is a data name which is used to store some data value or symbolic names for storing
program.A variable is storage area created by a program in the computers memory. Each
variable in C has a specific type, which determines the size and layout of the variable's
memory; the range of values that can be stored within that memory; and the set of operations
that can be applied to the variable.
Syntax
datatype variablename;
The rules of naming variables are the same as the rules of naming an identifier since a
variable is an identifier
Variable declaration
A variable should be declared first before its used in a program .A declaration specifies the
variable name and its data type
eg int number1;
Variable initialisation
When we assign any initial value to variable during the declaration, it is called initialization
of variables. When variable is declared but contain undefined value then it is called garbage
value. The variable is initialized with the assignment operator such as
Or
int number1;
Number1=20;
#include <stdio.h>
main() {
number1 =30;
number2 = 40;
return 0;
Data Types
Variables in C have an associated data type. Each data type requires different amounts of
memory and has some specific operations which can be performed over it. The following are
the different data types used in C
• char: The most basic data type in C. It stores a single character and requires a single
byte of memory in almost all compilers.
• int: As the name suggests, an int variable is used to store an integer.
• float: It is used to store decimal numbers (numbers with floating point value) with
single precision.
• double: It is used to store decimal numbers (numbers with floating point value) with
double precision.
• void: means no valueThis is usually used to specify the type of functions which returns
nothing
Constants
Constant is any value that cannot be changed during program execution. In C, any number,
single character, or character string is known as a constant. A constant is an entity that
doesn’t change whereas a variable is an entity that may change.
For example, the number 50 represents a constant integer value. The character string
"Programming in C is fun.\n" is an example of a constant character string. C constants can be
divided into two major categories:
Primary Constants
Secondary Constants
Numeric constant:
Numeric constant consists of digits. It required minimum size of 2 bytes and max 4 bytes. It
may be positive or negative but by default sign is always positive. No comma or space is
allowed within the numeric constant and it must have at least 1 digit. The allowable range for
integer constants is -32768 to 32767. Truly speaking the range of an Integer constant depends
upon the compiler.
For a 16-bit compiler like Turbo C or Turbo C++ the range is –32768 to 32767.
For a 32-bit compiler the range would be even greater. Mean by a 16-bit or a 32- bit
compiler, what range of an Integer constant has to do with the type of compiler. It is
categorized a integer constant and real constant. An integer constants are whole number
which have no decimal point.
In decimal constant first digit should not be zero unlike octal constant first digit must be zero
(as 076, 0127) and in hexadecimal constant first two digit should be 0x/ 0X (such as 0x24,
0x87A). By default type of integer constant is integer but if the value of integer constant is
exceeds range then value represented by integer type is taken to be unsigned integer or long
integer. It can also be explicitly mention integer and unsigned integer type by suffix l/L and
u/U.
Real constant
It is also called floating point constant. To construct real constant we must follow the rule of
,
426.0
-32.76
for example
3.6*105=3.6e+5. By default type of floating point constant is double, it can also be explicitly
defined it by suffix of f/F.
Character Constant
Character constant represented as a single character enclosed within a single quote. These can
be single digit, single special symbol or white spaces such as‘9’,’c’,’$’, ‘ ’ etc. Every
character constant has a unique integer like value in machine’s character code as if machine
using ASCII (American standard code for information interchange). Some numeric value
associated with each upper and lower case alphabets and decimal integers are as:
String constant
Set of characters are called string and when sequence of characters are enclosed within a
double quote (it may be combination of all kind of symbols) is a string constant. String
constant has zero, one or more than one character and at the end of the string null
character(\0) is automatically placed by compiler. Some examples are “,sarathina” , “908”,
“3”,” ”, “A” etc. In C although same characters are enclosed within single and double quotes
it represents different meaning such as “A” and ‘A’ are different because first one is string
attached with null character at the end but second one is character constant with its
corresponding ASCII value is 65.
Defining Constants
Example Program
#include <stdio.h>
#define WIDTH 5
int main()
int area;
printf("%c", NEWLINE);
return 0;
}
Using Const Keyword
Syntax
Example Program
#include <stdio.h>
int main()
int area;
printf("%c", NEWLINE);
return 0;
Exercise 2
This is a symbol use to perform some operation on variables, operands or with the constant.
▪ Arithmetic Operators
▪ Relational Operators
▪ Logical Operators
▪ Bitwise Operators
▪ Assignment Operators
Arithmetic Operators
These are operators that perform numeric calculations The following are arithmetic operators
which are inbuilt in C and are listed in the their order of precedence
Relational Operators
Following table shows all the relational operators supported by C language. Lets assume
variable A holds 10 and variable B holds 20, then
Operator Operation Example
== Checks if the values of two operands are equal or not, (A == B) is not
if yes then condition becomes true. true.
> Checks if the value of left operand is greater than the (A > B) is not
value of right operand, if yes then condition becomes true.
true.
< Checks if the value of left operand is less than the (A < B) is true.
value of right operand, if yes then condition becomes
true.
>= Checks if the value of left operand is greater than or (A >= B) is not
equal to the value of right operand, if yes then true.
condition becomes true.
<= Checks if the value of left operand is less than or equal (A <= B) is true.
to the value of right operand, if yes then condition
becomes true.
Logical Operators
They are Operators that are used with one or more operand and return either value zero (for
false) or one (for true). The operand may be constant, variables or expressions. And the
expression that combines two or more expressions is termed as logical expression. C has
three logical operators :
The following assignment operators are the operators supported by the C language:
Exercise 3
In every complex creative activity, errors are possible, and programming is no exception. In
programming, the errors are often called “bugs” and the process of finding and removing
them is called “debugging.” Unfortunately, even the smallest program bug can cause a
serious failure.
Types of errors
Syntax error
A syntax error is an error in the source code of a program. Since computer programs must
follow strict syntax to compile correctly, any aspects of the code that do not conform to the
syntax of the programming language will produce a syntax error.The following will generate
a syntax error
▪ Spelling mistakes
▪ Typographic o instead of 0
▪ Spacing for example a space between in a variable name number 1 instead of
number1
▪ Type mismatch assigning REAL to Char
▪ Misuse use of reserved words
▪ Missing out quotes
▪ Missing out brackets
▪ Missing out a semicolon at end of a statement
Semantic Error
A logic error is a “bug” or mistake in a program’s source code that results in incorrect or
unexpected behaviour. It is a type of runtime error that may simply produce the wrong output
or may cause a program to crash while running. They are not found by the compiler, but do
appear during a run. Some examples of these “run-time” errors involve many different types
of programming mistakes . For example,
• assigning a value to the wrong variable may cause a series of unexpected program
errors.
• Multiplying two numbers instead of adding them together may also produce unwanted
results.
• Wrong comparison less than instead of greater than
Example program
A student has written a program to find the average of their test results.
#include <stdio.h>
main() {
double average ;
return 0 ;
This program will produce output but the program will produce wrong results because of a
semantic error caused by a wrong formula i
Instead of the formula average = (test1 + test2 + test3)/3 the wrong formula
These are errors that occur during program execution and can be generated when the
computer tries to read past an end of file marker or by dividing a number
Exercise 5
Using examples outline the difference between a syntax and a semantic error
Console Input and Output
Input means to provide the program with some data to be used in the program and Output
means to display data on screen or write the data to a printer or a file. C programming
language provides many built-in functions to read any given input and to display data on
screen when there is a need to output the result. All these built-in functions are present in C
header files, we will also specify the name of header files in which a particular function is
defined while discussing about it.
The standard input-output header file, named stdio.h contains the definition of the functions
printf() and scanf(), which are used to display output on screen and to take input from user
respectively.
Example program
#include <stdio.h>
int main () {
printf (“Enter your first number %d \n “); // Prints out on the screen using printf
scanf( "%d", &number1 ); // Gets input entered from keyboard using scanf
return 0 ;
The getchar() function reads a character from the terminal and returns it as an integer. This
function reads only single character at a time. You can use this method in a loop in case you
want to read more than one character. The putchar() function displays the character passed to
it on the screen and returns the same character. This function too displays only a single
character at a time. In case you want to display more than one characters, use putchar()
method in a loop.
#include <stdio.h>
void main( )
int c;
printf("Enter a character");
c = getchar();
putchar(c);
The gets() function reads a line from stdin(standard input) into the buffer pointed to by str
pointer, until either a terminating newline or EOF (end of file) occurs. The puts() function
writes the string str and a trailing newline to stdout.
str → This is the pointer to an array of chars where the C string is stored. (Ignore if you are
not able to understand this now.)
#include<stdio.h>
void main()
char str[100];
printf("Enter a string");
gets( str );
puts( str );
getch();
}
When you will compile the above code, it will ask you to enter a string. When you will enter
the string, it will display the value you have entered.
The main difference between these two functions is that scanf() stops reading characters
when it encounters a space, but gets() reads space as character too.
If you enter name as AECS 103 using scanf() it will only read and store AECS and will leave
the part after space. But gets() function will read it completely.
Control Structures
Sequential structure
In this structure statements in a program are executed one after the other in the order in which
they are written. The sequence structure is simple—unless directed otherwise, the computer
executes C statements one after the other in the order in which they are written
Example Program
include <stdio.h>
int main () {
printf (“Enter your first number %d \n “); // Prints out on the screen using printf
scanf( "%d", &number1 ); // Gets input entered from keyboard using scanf
return 0 ;
In this above example program statements are executed one after the other in the order
in which they appear in the program
Decision making structures require that the programmer specify one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be executed if the
condition is determined to be true, and optionally, other statements to be executed if the
condition is determined to be false.
Syntax
if(boolean_expression)
If the boolean expression evaluates to true, then the block of code inside the if statement will
be executed. If boolean expression evaluates to false, then the first set of code after the end of
the if statement (after the closing curly brace) will be executed.
Example Code
The program prompts a student to enter their mark and it evaluates if they passed
PassMark>=50
#include<stdio.h>
int main() {
int ExamMark;
scanf(“%d”, &ExamMark );
printf(“Passed \n”);
} //endif
return 0;
If …..else Statement
When taking a decision, there are always two faces to it i.e. to do or not to do. Similarly,
when programming, there are two faces to a condition, it may evaluate as TRUE or FALSE .
To implement such a decision, C has provided you with the IF-ELSE construct. This
construct carries out a logical test and then takes one of the two possible course of actions,
depending on the outcome of the test
Syntax
if(boolean_expression)
else
Example Program
#include<stdio.h>
int main() {
int ExamMark;
scanf(“%d”, &ExamMark );
else
return 0;
}
If…..elseif……else Statement
In this type of statement there is an if else statement in every else part except the last part. If
condition is false control pass to block where condition is again checked with its if statement
Syntax
if(boolean_expression 1)
else
Example Program
#include<stdio.h>
int main() {
int ExamMark;
else if(ExamMark>=60)
else if(ExamMark>=50)
else if(ExamMark<50)
else
return 0;
if( boolean_expression 1)
if(boolean_expression 2)
Switch Statement
The switch-case statement causes a particular group of statements to be selected from a group
of options. The selection is based upon the current value of the expression which is specified
with the SWITCH statement. Given below is the switch-case syntax
Switch-case syntax
switch(expression)
case label1 :
statements;
break;
case label2 :
statements;
break;
default :
statements;
break;
}
Example program
#include <stdio.h>
int main ()
{
/* local variable definition */
char grade = 'B';
switch(grade)
{
case 'A' :
printf("Excellent!\n" );
break;
case 'B' :
case 'C' :
printf("Well done\n" );
break;
case 'D' :
printf("You passed\n" );
break;
case 'F' :
printf("Better try again\n" );
break;
default :
printf("Invalid grade\n" );
}
printf("Your grade is %c\n", grade );
return 0;
}
A while statement allows you to specify that an action is to be repeated while some condition
remains true. while loop statement in C programming language repeatedly executes a target
statement or statements as long as a given condition is true.
Syntax
while(condition)
statement(s);
Example Program
#include<stdio.h>
int main( )
int count;
count = 0;
count = count + 1;
return 0;
When a loop is constructed using the while statement, the condition is evaluated at the
beginning of the loop body. With the do while the evaluation is done at end of the loop body.
The do while loop like the while loop executes as long as the condition remains true.
Consequently, the body of the loop is always executed at least once.
Syntax of do …..while
do
statement(s);
}while( condition );
Example program
#include<stdio.h>
int main( )
int count;
count = 0;
do
count = count + 1;
return 0;
}
For Loop
A for loop is a repetition control structure that allows you to efficiently write a loop that
needs to execute a specific number of times.
Syntax
Statement(s);
Example program
#include<stdio.h>
int main( )
int count;
for(count=0; count<=10;count++)
return 0;
Example program2
# include <stdio.h>
main()
{
int i,square;
for(i=1;i<=8;i++)
printf(“%d \t %d \n “,i,i*i);
}
Nested Loop
C programming language allows to use one loop inside another loop. Following section
shows few examples to illustrate the concept.
Syntax
statement(s);
statement(s);
The syntax for a nested while loop statement in C programming language is as follows:
while(condition)
while(condition)
statement(s);
statement(s);
}
Example program
The following program uses a nested for loop to find the prime numbers from 2 to 100:
#include <stdio.h>
int main ()
int i, j;
return 0;
Exercise 6
1. Write a program to accept three numbers as input and print out the largest number of
the three
2. Write a program that determines if an integer value entered by a user is an even or an
odd number
3. Write a program that determines a student’s grade. The program will read three test
marks and determine the grade based on the following rules:
An array is a group of contiguous memory locations that all have the same data type. Array
is the collection of similar data types or collection of similar entity stored in contiguous
memory location. Array of character is a string. Each data item of an array is called an
element. And each element is unique and located in separated memory location. Each of
elements of an array share a variable but each element having different index no. known as
subscript.
An array is used to store a collection of data, but it is often more useful to think of an array
as a collection of variables of the same type. Array variable can store more than one value at
a time where other variable can store one value at a time.
Types of arrays
▪ Multidimensional array
Declaration Of An Array
An array is declared in the same manner as ordinary variables, except that each array name
must be accompanied by a size specification. This is necessary because the compiler will
have to know how much memory to reserve for this array.
A single dimensional array is declared as follows :
type array_name[array_size];
where array_name is the name of an array of n elements of the type specified. The size of an
array must be an integer constant. The integer arrray declaration int x[100], creates an array
that is 100 elements along with the first element being 0 and the last being 99.
int i[100];
char text[80];
float n[12];
Initialising Array
An array can be initialized when declared by specifying the values of some or all of its
elements. Arrays can be initialized at the time of declaration when their intial values are
known in advance. The values to initialize an array must be constants never variables or
function calls
int array[5]={4,6,5,7,2};
float x[6]={0,0.25,0,-0.50,0,0};
An element is accessed by indexing the array name. This is done by placing the index of the
element within square brackets after the name of the array. For example:
The above statement will take 8th element from the array and assign the value to rate
variable.
Example Program
#include<stdio.h>
int main()
int arr[5],i;
for(i=0;i<5;i++)
scanf(“%d”,&arr[i]);
for (i=0;i<5;i++)
{
printf(“%d\t”,arr[i]);
return 0;
Example 2
#include<stdio.h>
void main()
int i ;
int sum=o;
}
Multidimensional Arrays
(Two dimensional Arrays)
Declaration Of An Array
C as a language provides for arrays of arbitrary dimensions. A two dimensional array of size
m rows by n columns is declared as follows :
type array_name[m][n];
A two dimensional array, twodim of type int, with 3 rows and 4 columns is declared as
follows :
The array can be declared by passing values of number of rows and number of columns as
subscript values.
Example
int a[3][4];
Initializing Arrays
The values can also be initialized by forming group of initial values enclosed within braces.
The values within an inner pair of braces will be assigned to the element of a row or all the
values can be given in single braces sequentially.
Example
int array[3][4] = {{0, 1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10, 11}};
For processing 2-d array, we use two nested for loops. The outer for loop corresponds to the
row and the inner for loop corresponds to the column.
For example
int a[4][5];
for reading value:-
for(i=0;i<4;i++)
{
for(j=0;j<5;j++)
{
scanf(“%d”,&a[i][j]);
}
}
For displaying value:-
for(i=0;i<4;i++)
{
for(j=0;j<5;j++)
{
printf(“%d”,a[i][j]);
}
}
Example Program
#include<stdio.h>
int main()
int a[4][5];
int i,j;
for(i=0;i<4;i++)
for(j=0;j<5;j++)
scanf("%d",&a[i][j]);
for(i=0;i<4;i++)
for(j=0;j<5;j++)
printf("%d ",a[i][j]);
if (j==4){
printf("\n");
Exercise 7
1. Using an Array write a program that accepts 5 values from a user and it then displays
the average of the 5 values entered
2. Write a program to accept the values into an five integer array.The program then sorts
the array and then print the sorted array.
Functions
A function is a self-contained block of codes or sub programs with a set of statements that
perform some specific task or coherent task when it is called. A function is a self-contained
program segment that carries out some specific, well-defined task. Functions break large
computing tasks into smaller ones. C has been designed to make functions efficient and easy
to use. C programs generally consist of many small functions rather than a few big ones.
Any ‘C’ program contain at least one function i.e main().
Pre-Defined Functions
Pre-defined functions are built in functions that are already defined and stored in header files.
when we use a particular function we should include the header file. It is also called as library
functions.
1.Mathematical Functions.
2. String Functions
3. Character Functions
Mathematical Functions
Mathematical functions are defined in the header file <math.h> before using math functions
we should include the header file
#include<math.h>
abs: -returns the absolute value of a number,a number without its sign.
syntax : abs(argument)
example: abs(-25) Output : 25
There are many Mathematical functions pre-defined in C we can not explore them all in
this guide
These are functions created by a user to solve a particular problem. If a program is divided
into functional parts, then each part may be independently coded and later combined into a
single unit.
1. function declaration
2. function calling
3. function definition
Function Declaration
Every function must be declared before they are defined. If the function is written before the
main() function then declaration is not necessary.
syntax:
Argument-any value passed to the function is called an argument. In the declaration part we
should specify the type of data to be passed into the function.
return value- any value returned from the function is called return value we should mention
the data type of the value returned at the beginning of the function. function can return only
one value.
functionname(argument1,argument2..);
Example
add(10,20); 10,20 are actual arguments to the function add.
Function Definition
A program is a set of definitions of variables and functions. Communication between the
functions is through arguments and values returned by the functions.
{
local function variables;
function executable statements; /* body of the function */
return(return value);
}
The first line of the function definition contains : The type specification of the value returned
by the function. The return value can be char,,int,or float. If the function does not return any
value, the specified return value should be void.
The function name, and (optionally) a set of formal arguments , separated by commas and
enclosed in parenthesis.
The arguments (formal arguments) allow information to be transferred from the calling
portion of the program to the function. The identifiers used as formal arguments are “local “
i.e., they are not recognized outside of the function.
All the formal arguments are declared following the first line.
Each formal argument must be of the same data type as the data type it receives from the
calling portion of the program.
The body of the function defines the action to be taken by the function. The return statement
is the mechanism used for returning a value from the called function to its caller.
return expression;.
The value of expression is returned to the calling portion of the program. The expression will
be converted to the return type of the function if necessary. A function can return only one
value to the calling portion of the program via return. The return statement simply causes
control to revert back to the calling portion. No separate return statement is necessary to send
back the control. When the closing brace (}) of the called function is encountered the control
is returned to the calling function.
Example
# include <stdio.h>
/* To sum two numbers and return the sum to the main program */
main()
{
int addnum(int,int); /* Function Declaration */
int sum,a,b;
scanf(“%d””%d”, &a,&b)
getch();
total=num1+num2;
return(total);
Output :
There are two ways through which we can pass the arguments to the function during a
function call there is call by value and call by reference.
Call by Value
The call by value method of passing arguments to a function copies the actual value of an
argument into the formal parameter of the function. In this case, changes made to the
parameter inside the function have no effect on the argument.
Changes made to the parameter are local to the block of the called function so when the
control is returned back to the calling function the changes made is discarded.
By default, C programming language uses call by value method to pass arguments. In
general, this means that code within a function cannot alter the arguments used to call the
function.
Call by Reference
Instead of passing the value of variable, address or reference is passed and the function
operates on the address of the variable rather than value. Here formal argument is alter to the
actual argument, it means formal arguments calls the actual arguments. The call by reference
method of passing arguments to a function copies the address of an argument into the formal
parameter. Inside the function, the address is used to access the actual argument used in the
call. This means that changes made to the parameter affect the passed argument.
Example:-
#include<stdio.h>
void main()
{
int a,b;
change(int *,int*); //function declaration
printf(“enter two values:\n”);
scanf(“%d%d”,&a,&b);
change(&a,&b); //instead of copy of value an address of the variable is passed to the function
printf(“after changing two value of a=%d and b=%d\n:”a,b);
}
change(int *a, int *b) //function definition
{
int k;
k=*a; /* save the value at address a */
*a=*b;
*b= k;
printf(“value in this function a=%d and b=%d\n”,*a,*b);
}
Exercise 8
A scope in any programming is a region of the program where a defined variable can have its
existence and beyond that variable cannot be accessed. There are three places where variables
can be declared in C programming language:
Local Variables
Variables that are declared inside a function or block are called local variables. The local
variables can be used only in that function or block in which they are declared They can be
used only by statements that are inside that function or block of code. Local variables are not
known to functions outside their own.
#include <stdio.h>
int main ()
{
int a, b; // these are local variables only accessible within the main function only
int c;
a = 10;
b = 20;
c = a + b;
printf ("value of a = %d, b = %d and c = %d\n", a, b, c);
return 0;
}
Global variables
These are variables that are defined outside of any function . All functions in the program can
access and modify global variables. Global variables are automatically initialized at the time
of initialization.
Example
#include <stdio.h>
a = 10;
b = 20;
g = a + b;
printf ("value of a = %d, b = %d and g = %d\n", a, b, g);
return 0;
}
Static variables:
syntax:
A Pointer is a variable which holds the address of another variable. By using this pointer
variable we may call that particular memory location. It is called a pointer because
it points to a particular location in memory by storing address of that location.
Syntax
Eg
#include <stdio.h>
int main ()
{
int number = 300; /* actual variable declaration */
printf("Address stored in ptr variable: %x\n", ptr ); /* address stored in pointer variable */
printf("Value of *ptr variable: %d\n", *ptr ); /* access the value using the pointer */
return 0;
Pointer Arithmetic
In C a pointer is an address, which is a numeric value. Therefore, you can perform arithmetic
operations on a pointer just as you can a numeric value. There are four arithmetic operators
that can be used on pointers: ++(incrementer), -- (decrementer) , +, and –
Let us consider why we need to identify the type of variable that a pointer points to, as in:
int *ptr;
One reason for doing this is so that later, once ptr "points to" something, if we write:
*ptr = 2;
The compiler will know how many bytes to copy into that memory location pointed to by ptr.
If ptr was declared as pointing to an integer, 4 bytes would be copied. Similarly for floats and
doubles the appropriate number will be copied. But, defining the type that the pointer points
to permits a number of other interesting ways a compiler can interpret code. For example,
consider a block in memory consisting of ten integers in a row. That is, 40 bytes of memory
are set aside to hold 10 integers.
Now, let's say we point our integer pointer ptr at the first of these integers. Furthermore let's
say that integer is located at memory location 100 (decimal).
ptr + 1;
Because the compiler knows this is a pointer (i.e. its value is an address) and that it points to
an integer (its current address, 100, is the address of an integer), it adds 4 to ptr instead of 1,
so the pointer "points to" the next integer, at memory location 104. Similarly, were the ptr
declared as a pointer to a short, it would add 2 to it instead of 1. The same goes for other data
types such as floats, doubles, or even user defined data types such as structures. This is
obviously not the same kind of "addition" that we normally think of.
In C it is referred to as addition using "pointer arithmetic".
Similarly, since ++ptr and ptr++ are both equivalent to ptr + 1 (though the point in the
program when ptr is incremented may be different), incrementing a pointer using the unary
++ operator, either pre- or post-, increments the address it stores by the amount sizeof(type)
where "type" is the type of the object pointed to. (i.e. 4 for an integer).
Pointer Comparisons
Pointers may be compared by using relational operators, such as ==, <, and >. If p1 and p2
point to variables that are related to each other, such as elements of the same array, then p1
and p2 can be meaningfully compared.
Example Program
#include<stdio.h>
void main()
{
static int arr[]={20,25,15,27,105,96}
int *p1,*p2;
p1=&arr[4];
p2=&arr[5];
printf(“same”);
else
printf(“not”);
}
This program is comparing the values at position 4 and 5 of an array using pointers
Pointer to Pointer
A Pointer to Pointer is a pointer that is a pointer to another pointer which actually pointing to
a value. When we define a pointer to a pointer, the first pointer contains the address of the
second pointer, which points to the location that contains the actual value.
Syntax
**ptr
Eg
int x=22;
int *p=&x;
int **p1=&p; //p1 is a pointer to pointer p
Example program
#include <stdio.h>
void main() {
int x=22;
int *p=&x;
int **p1=&p;
printf(“value of x=%d\n”,x);
printf(“value of x=%d\n”,*p);
printf(“value of x=%d\n”,*&x);
printf(“value of x=%d\n”,**p1);
printf(“value of p=%u\n”,&p);
printf(“address of p=%u\n”,p1);
printf(“address of x=%u\n”,p);
printf(“address of p1=%u\n”,&p1);
printf(“value of p=%u\n”,p);
}
Exercise 9
A structure is a user defined data type that enables the storing of data that maybe of different
data types. A Structure is a collection of one or more variables ,possibly of different types,
grouped together under a single name for convenient handling such as to represent a record.
The individual structure elements are referred to as members.
Structures help to organize complicated data ,particularly in large programs ,because they
permit a group of related variables to be treated as a unit instead of separate entities.
Structure Definition
Syntax
Struct Struct_name
{
member_type1 member_name1;
member_type2 member_name2;
...........
...........
}
Eg
Struct Student
{
char firstname[25];
char surname[25];
char studentid[10] ;
int age;
};
To access any member of a structure, we use the member access operator (.). The member
access operator is coded as a period between the structure variable name and the structure
member that we wish to access.
Example Program
#include <stdio.h>
Struct Student
{
char firstname[25];
char surname[25];
char studentid[10] ;
int age;
};
main() {
struct student student1; //Declare student1 student
struct student student2;
strcpy( student1.firstname, "Cara"); //Accessing structure members using dot (.) operator
strcpy( student1.surname, "Munda");
strcpy( student1.studentid, "R456787");
student1.age= 29;
Structure Initialisation
For Example
struct Student
{
char Studentname[15];
int age;
};
void main(){
struct Student stud[5];
int i;
for(i = 0; i < 5; i++)
{
printf("\nEnter %dst Student record:\n", i+1);
printf("\nStudent name:\t");
scanf("%s", stud[i].Studentname);
printf("\nEnter the age:\t");
scanf("%d", &stud[i].age);
}
A full program
#include<stdio.h>
struct Student
{
char Studentname[10];
int age;
};
void main(){
struct Student stud[5];
int i;
for(i = 0; i < 5; i++)
{
printf("\nEnter %dst Student record:\n", i+1);
printf("\nStudent name:\t");
scanf("%s", stud[i].Studentname);
printf("\nEnter Age:\t");
scanf("%d", &stud[i].age);
}
printf("\nDisplaying Student record:\n");
for(i = 0; i < 5; i++)
{
printf("\nStudent name is %s", stud[i].Studentname);
printf("\nAge is %d", stud[i].age);
}
A structure can be passed as a function argument just like we pass any other variable or an
array as a function argument.
Exercise 10
1. Create a named structure which is able capture and display the record of employees. The
record should contain EmployeeNumber, Name, Department and Salary
2.Create a structure to specify data on customers in bank. The data to be stored is :
Acc_no, Name, Balance in account.
Assume maximum of 200 customers in the bank.
i) Write a function to print the Acct_no and name of each customer with 1000.
File Handling
A File is a collection of records(data). A file is a place on the disk where a group of related
data is stored.
Opening a file is performed using the fopen() function defined in the stdio.h header file.
Syntax
File *fptr
fptr = fopen("filename","mode");
• *ptr is the FILE pointer (FILE *ptr), which will hold the reference to the opened(or
created) file.
• filename is the name of the file to be opened and mode specifies the purpose of
opening the file.
Closing a file
Syntax :
fclose() function closes the file and returns zero if it is a success, or EOF if there is an error in
closing the file. This EOF is a constant defined in the header file stdio.h
getc() and putc() are the simplest functions which can be used to read and write individual
characters to a file.
#include<stdio.h>
int main()
{
FILE *fp;
char ch;
fp = fopen("one.txt", "w");
printf("Enter data...");
while( (ch = getchar()) != EOF) {
putc(ch, fp);
}
fclose(fp);
fp = fopen("one.txt", "r");
return 0;
}
The below program uses the fprintf() function to write to a text file
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE *fptr;
fptr = fopen("C:\Users\ORACLE\Documents\program.txt","w");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
printf("Enter num: ");
scanf("%d",&num);
fprintf(fptr,"%d",num);
fclose(fptr);
return 0;
}
The below sample program uses fscanf() to read from a text file
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE *fptr;
if ((fptr = fopen(" C:\Users\ORACLE\Documents\program.txt ","r")) == NULL){
printf("Error! opening file");
// Program exits if the file pointer returns NULL.
exit(1);
}
fscanf(fptr,"%d", &num);
printf("Value of n=%d", num);
fclose(fptr);
return 0;
}
Exercise 11
1. Write a program that will prompt for a filename for a read file, prompt for a filename for
write file, and open both plus a file to the printer. Enter a loop that will read a character, and
output it to the file, the printer, and the monitor. Stop at EOF.
2. Prompt for a filename to read. Read the file a line at a time and display it on the monitor
with line numbers.