0% found this document useful (0 votes)
6 views

CUIITM114 Study Notes

Programming involves creating a sequence of instructions using a programming language to perform specific tasks on a computer. There are various types of software, including off-the-shelf, bespoke, and hybrid software, each with its advantages and disadvantages. Additionally, programming languages are categorized into low-level and high-level languages, with examples including C, Java, and Python, and they serve different purposes in software development.

Uploaded by

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

CUIITM114 Study Notes

Programming involves creating a sequence of instructions using a programming language to perform specific tasks on a computer. There are various types of software, including off-the-shelf, bespoke, and hybrid software, each with its advantages and disadvantages. Additionally, programming languages are categorized into low-level and high-level languages, with examples including C, Java, and Python, and they serve different purposes in software development.

Uploaded by

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

What is programming

A computer program is a sequence of instructions written using a Computer Programming


Language to perform a specified task by the computer. Computer programming is the process
of designing, developing and testing computer programs.

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.

Programmer: A person who specialises in designing, developing and testing computer


programs

Types of Programs

Off the Shelf

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

Advantages of Off-the -shelf

• 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

• May not meet the individual needs of an organisation.


• May not run on the organisation’s hardware.
• May not interface with other software already in use in the organisation.
• Organisations purchasing them have little or no control over their usage
• Organisations purchasing them have no right to modify them.
• The software can be very sophisticated and will usually include large sections
that you will never use (e.g. Excel or Word)
• may be very complex to learn because of the complexity caused through
having unwanted features

Bespoke /Tailor-made/ Custom Made

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

Advantages of Bespoke software

➢ 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

Disadvantages of Bespoke software:

➢ It is very expensive to develop.


➢ They take too long to develop and to implement.
➢ If you pick the wrong developer you could end up with an application that is unstable,
unreliable and full of bugs
➢ very dependent on the suppliers of the software; if they go out of business there will
be little or no support if problems occur
➢ less likely to be as well developed/tested as off-the-shelf software

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

TYPES OF PROGRAMMING LANGUAGES

Low Level Languages (LLL):

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:

(a) Machine Language and


(b) Assembly Language.

Machine code (language)

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.

Disadvantages of Machine language:


▪ They are very difficult to learn.
▪ They are difficult to understand.
▪ Very difficult to use and therefore very few programmers use them these days.
▪ It takes too long to debug and therefore is prone to some errors.
▪ It takes too long to develop working programs.
▪ They are machine dependent (they can only work on type of computer designed for
and not work on other computers)

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,
.

Advantages of Assembly language:

▪ 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.

Disadvantages of Assembly Language

▪ They are very difficult to learn.


▪ They are very difficult to understand.
▪ Takes too long to develop working programs.
▪ They can be machine dependent (machine oriented) unless the machines use the same
processor chip.
High Level Languages (HLL):

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.

Advantages of High Level Languages:


▪ They are easier to understand since they are written in English-like statements which
are more readable.
▪ They are easier to learn.
▪ It is easier to work with, that is to correct errors (debug) and to test programs.
▪ They are problem oriented and therefore can be used on any computer (not machine
dependent)

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.

Types of Computer code

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 programming language is a general-purpose, high-level language that was originally


developed by Dennis M. Ritchie to develop the UNIX operating system in 1972.

The C has now become a widely used professional language for various reasons.

1. Easy to learn

2. Structured language

3. It produces efficient programs.

4. It can handle low-level activities.

5. It can be compiled on a variety of computer platforms

Application of C

C is used to produce efficient programs such as

▪ Operating Systems
▪ Language Compilers
▪ Assemblers
▪ Text Editors
▪ Print Spoolers
▪ Network Drivers
▪ Modern Programs
▪ Databases
▪ Language Interpreters
▪ Utilities
▪ Etc

What you need to write and run a C program

1 A text editor to write source code e.g Notepad,

2 A compiler to convert a source code into an executable code eg GNU C/C++ compiler

OR

An Integrated Development Environment(IDE) such as DEV C++ IDE(which I advice we


use for this module), Netbeans IDE for C/C++ etc An IDE contains a Compiler and a text
editor in one package. It is also easier to identify and correct errors in a program when using
an IDE.

Download DEV C++ IDE for free on the internet and Install on your computer

How to write a C Program using Dev C++ IDE

Step1

Open Dev C++ IDE

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

Type(write) your program(source code) in the iDE

Example simple program in C

#include <stdio.h>

int main()

/* Our first program in C */

printf(“Welcome to the world of C \n");

return 0;

Stage 3

Compile the written program

Click on Execute and then click on Compile

Save the program as Name.c eg MyFirstprogram.c

If there are errors correct the errors


Step 4

If there are no errors

Click execute and then click run to run the program

Output
Basics of C

Structure of a C pogram

A C program basically consists of the following parts:

• Preprocessor Commands

• Functions

• Variables

• Statements & Expressions

• Comments

Simple C program

#include <stdio.h> Preprocessor commands

int main() Function

/* Our first program in C */ Comment

printf(“Welcome to the world of C \n”); Statement and Expressions

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

/*…………multiple line comment…………………*/

Statements

printf(“Welcome to the world of C \n”);

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. Write a program to display your name on the monitor.


2. Modify the program to display your address and phone number on separate lines by adding
two additional "printf" statements
Identifiers

In C an identifier is a name used to identify a variable, function, or any other user-defined


item.

Rules of naming Identifiers

1) An identifier should only consists of alphabetic letters (both upper and lower case from A-
Z,a-z), digits and underscore (_) sign.

2) The first character of an identifier should be alphabet or underscore not a digit

3) An identifier should not be a keyword such as int, printf etc

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;

Eg int number1, number2;

char ch, firstname ;

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

Data type variable name=constant;

Example: int number1=20;

Or

int number1;

Number1=20;

Example Program on use of Variables

#include <stdio.h>

main() {

int number1, number2, sum;

number1 =30;

number2 = 40;

sum = number1 + number2;

printf ( “The result of adding the two numbers = %d\n” ,sum);

return 0;

Output of this program

The result of adding the two numbers = 70

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
,

▪ -real constant must have at least one digit.


▪ -It must have a decimal point.
▪ -It could be either positive or negative.
▪ -Default sign is positive.
▪ -No commas or blanks are allowed within a real constant. Ex.: +325.34

426.0

-32.76

To express small/large real constant exponent(scientific) form is used where number is


written in mantissa and exponent form separated by e/E. Exponent can be positive or negative
integer but mantissa can be real/integer type,

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

There are two simple ways in C to define constants:

1. Using #define preprocessor.

2. Using const keyword.

The #define Preprocessor

Following is the form to use #define preprocessor to define a constant:

#define identifier value

Example Program

#include <stdio.h>

#define LENGTH 10 //defining constants

#define WIDTH 5

#define NEWLINE '\n'

int main()

int area;

area = LENGTH * WIDTH;

printf("value of area : %d", area);

printf("%c", NEWLINE);

return 0;

}
Using Const Keyword

Constants can be declared using the const keyword

Syntax

const type variable = value;

eg const float pi = 3.142 ;

Example Program

#include <stdio.h>

int main()

const double PI = 3.142; //declaration and definition of consants

const int RADIUS = 5;

const char NEWLINE = '\n';

int area;

area = PI * RADIUS * RADIUS;

printf("value of area : %d", area);

printf("%c", NEWLINE);

return 0;

Note that it is a good programming practice to define constants in CAPITALS.

Exercise 2

1. Outline the rules of naming identifiers


2. Write lines of code that demonstrates variable declarations and initialisation of an
integer, float and a character.
3. Create a program using C that will accept 3 marks from the user and it will calculate
the total marks and then it will print out the 3 marks entered and the total on the
screen
4. Using a constant PI = 3.1428 . Write a program that will find the area on any circle
Operators

This is a symbol use to perform some operation on variables, operands or with the constant.

An operator instructs the compiler to perform specific mathematical or logical manipulations.


C language is rich in built-in operators and provides the following types of operators:

▪ 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

Lets assume the variables A = 20 and B = 40

Operator Operation Example


() Parenthesis Operands in parenthesis are evaluated
first
-- decrement variable by 1 --A = 19
++ increment variable by 1 ++A=20
* multiplication A*B =800
/ division B/A= 2
% modulus gives the remainder B%A= 0
after division
+ addition A+B= 60

- subtarction A-B = -20

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 values of two operands are equal or not, (A != B) is true.


if values are not equal then condition becomes 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 :

Operator Operation Example


&& Called Logical AND operator. If both the operands are (A && B) is
non-zero, then condition becomes true. false
|| Called Logical OR Operator. If any of the two (A || B) is true.
operands is non-zero, then condition becomes true.
! Called Logical NOT Operator. Use to reverses the . !(A && B) is
logical state of its operand. If a condition is true, then true.
Logical NOT operator will make false
Assignment Operators

The following assignment operators are the operators supported by the C language:

Exercise 3

1. Write a C program to calculate the area and circumference of a circle


2. Write a program that accept input of distance (in KM) to convert and print this
distance in meters, inches and centimeters
Errors in Programming

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() {

int test1, test2, test3;

double average ;

printf (“Enter your mark for test1 %d \n “);

scanf( "%d", &test1 );

printf (“Enter your mark for test2 %d \n “);

scanf( "%d", &test2 );

printf (“Enter your mark for test3 %d \n “);

scanf( "%d", &test3 );

average = test1 + test2 + test3/3

printf (“Your average mark is %lf \n “ ,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

average = test1 + test2 + test3/3 was used

Runtime (execution) error:

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.

scanf() and printf() functions

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 () {

int number1, number2, sum;

printf (“Enter your first number %d \n “); // Prints out on the screen using printf

scanf( "%d", &number1 ); // Gets input entered from keyboard using scanf

printf (“Enter your mark for test2 %d \n “);

scanf( "%d", &number2 );

sum = number1 + number2

printf (“Your average mark is %d \n “ , sum);

return 0 ;

getchar() & putchar() functions

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");

/* Take a character as input and store it in variable c */

c = getchar();

/*display the character stored in variable c */

putchar(c);

gets() & puts() functions

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()

/* character array of length 100 */

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.

Difference between scanf() and gets()

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 () {

int number1, number2, sum;

printf (“Enter your first number %d \n “); // Prints out on the screen using printf

scanf( "%d", &number1 ); // Gets input entered from keyboard using scanf

printf (“Enter your mark for test2 %d \n “);

scanf( "%d", &number2 );

sum = number1 + number2

printf (“Your average mark is %d \n “ , sum);

return 0 ;

In this above example program statements are executed one after the other in the order
in which they appear in the program

Selection structure/ Decision Making structure

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.

C supports the following decision making structures:


i. if or simple if statements.
ii. if else statements.
iii. else if ladder statements.
iv. Nested if statements.
If Statement

The if statement allows the programmer to execute a statement or series of statements


conditionally. If the condition supplied to the statement is logically true, the statement that
follows it is executed. Else, it simply transfers control to the next statement

Syntax

if(boolean_expression)

{ /* statement(s) will execute if the boolean expression is true */ }

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;

printf(“Enter your exam mark %d|n”);

scanf(“%d”, &ExamMark );

if (ExamMark>=50) { // Use of Decision Making If statement structure

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)

/* statement(s) will execute if the boolean expression is true */

else

/* statement(s) will execute if the boolean expression is false */

Example Program

#include<stdio.h>

int main() {

int ExamMark;

printf(“Enter your exam mark %d|n”);

scanf(“%d”, &ExamMark );

if (ExamMark>=50) // Use of Decision Making If else statement structure

printf(“Passed \n”); //printed on screen if condition is true

else

printf(“Failed \n”); //printed on screen if condition is false

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)

/* Executes when the boolean expression 1 is true */

else if( boolean_expression 2)

/* Executes when the boolean expression 2 is true */

else if( boolean_expression 3)

/* Executes when the boolean expression 3 is true */

else

/* executes when the none of the above condition is true */

Example Program

#include<stdio.h>

int main() {

int ExamMark;

printf(“Enter your exam mark %d|n”);


scanf(“%d”, &ExamMark );

if (ExamMark>=70) // Use of Decision Making If else statement structure

printf(“The grade is A \n”);

else if(ExamMark>=60)

printf(“The grade is B \n”);

else if(ExamMark>=50)

printf(“The grade is C \n”);

else if(ExamMark<50)

printf(“You failed the exam \n”);

else

printf(“Enter a valid exam mark \n”); //printed on screen if condition is false

return 0;

Nested if……else Statement

This is an If or if….else statement nested inside another if or if….else statement


Syntax

if( boolean_expression 1)

/* Executes when the boolean expression 1 is true */

if(boolean_expression 2)

/* Executes when the boolean expression 2 is true */

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;
}

Looping Statements/Repetitive Statements

Used to execute a group of statements repeatedly until the condition is satisfied.

C supports the following looping statements:

1. while statement (Entry controlled loop).


2. do while statement. (Exit controlled loop)
3. for statement
While statement

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

The syntax of a while loop in C programming language is:

while(condition)

statement(s);

Example Program

/* This is an example of a "while" loop */

#include<stdio.h>

int main( )

int count;

count = 0;

while (count <= 10) {

printf("The value of count is %d\n",count);

count = count + 1;

return 0;

Output of this program is shown below

The value of count is 0

The value of count is 1


.
.
.
The value of count is 10

The Do-While Loop Statement

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

printf("The value of count is %d\n",count);

count = count + 1;

}while (count <=10);

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

The syntax of a for loop in C programming language is:

for ( initial value ; condition ; increment )

Statement(s);

Example program

#include<stdio.h>

int main( )

int count;

for(count=0; count<=10;count++)

printf("The value of count is %d\n",count);

return 0;

Example program2

# include <stdio.h>
main()
{
int i,square;

/* To print the square of first 8 integers */


printf(“x \t square(x)\n\n “);

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

The syntax for a nested for loop statement in C is as follows:

for ( init; condition; increment )

for ( init; condition; increment )

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 ()

/* local variable definition */

int i, j;

for(i=2; i<100; i++) {

for(j=2; j <= (i/j); j++)

if(!(i%j)) break; // if factor found, not prime

if(j > (i/j)) printf("%d is prime\n", i);

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:

-if the average mark >= 70 and <=100 grade=A


-if the average mark >= 60% and <70% grade=B
-if the average mark>=50% and <60% grade=C
-if the average mark<50% grade=F

4. Outline the differences between a while loop and a do while loop


5. Using a For Loop .Write a program that enables a user to enter 10 numbers and the
program will calculate the sum and average of those numbers

6. Write a program to generate fibonacci series up to N terms.

7. Write a program to print the following outputs using for loops.


a) 1 b) * * * * *
22 ****
333 ***
4444 **
55555 *
Arrays

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

▪ Single dimensional array

▪ Multidimensional array

Single dimensional 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.

Example of array declarations are :

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

Examples of Array initialisation

int array[5]={4,6,5,7,2};

int array[] = {4,6,5,7,2};

float x[6]={0,0.25,0,-0.50,0,0};

Accessing Array Elements

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:

double rate = array[7];

The above statement will take 8th element from the array and assign the value to rate
variable.

Example Program

/*Write a program to input values into an array and display them*/

#include<stdio.h>

int main()

int arr[5],i;

for(i=0;i<5;i++)

printf(“enter a value for arr[%d] \n”,i);

scanf(“%d”,&arr[i]);

printf(“the array elements are: \n”);

for (i=0;i<5;i++)

{
printf(“%d\t”,arr[i]);

return 0;

Example 2

/* Write a program to add 10 array elements */

#include<stdio.h>

void main()

int i ;

int arr [10];

int sum=o;

for (i=0; i<=9; i++)

printf (“enter the %d element \n”, i+1);

scanf (“%d”, &arr[i]);

for (i=0; i<=9; i++)

sum = sum + a[i];

printf (“the sum of 10 array elements is %d”, sum);

}
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}};

Accessing a 2 Dimensional Array

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++)

printf ("Enter the values a[%d][%d]",i,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().

There are basically two types of function those are

1. Library function/Predefined Functions


2. User defined function

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.

Pre-defined functions are divided into

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

sqrt:- returns the square root of a number.


syntax : sqrt(argument)
Example : sqrt(49) Output : 7

sin: -returns the sin value of an angle.


Syntax : sin(argument)
Example : sin(90) Output : 1
NB The same format is applicable to find tan, cos values.

log:returns the logarithmic value of a number.


syntax : log(argument)
Example : log(10) Output :1

pow: - returns the number raised to a power value.


syntax : pow(argu1,argu2)
argument 1 must be a number and argument 2 must be a power value.
Example : pow(5,3) Output : 125

There are many Mathematical functions pre-defined in C we can not explore them all in
this guide

User Defined Functions

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.

Steps in writing User defined Functions

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:

returndatatype functionname(argument datatype,argument datatype...);

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.

Example of function declaration


int add(int,int);
The above example for function declaration shows that the function add receives two integer
values and return an integer value

Calling the function


A function can be accessed by specifying its function name ,followed by a list of arguments
enclosed in parenthesis and separated by commas. If the function call doesn't require any
arguments , an empty pair of parenthesis must follow the function's name. The arguments
present in the function call is called as actual arguments.
syntax:

functionname(argument1,argument2..);

argument may be constants ,variables .

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.

A function definition has three principal components :


• The first line,
• The argument declarations and
• The body of the function.

Functions are defined as follows :

return_type function_name(argument list) /* first line */

definition_of_ argument_list_members /* argument declarations */

{
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;

printf(“ \n Enter two numbers to be added %d\n);

scanf(“%d””%d”, &a,&b)

sum = addnum(a,b); /* Function Call */

printf(“\n The sum of %d and % d is %d “,a,b,sum);

getch();

int addnum(int num1,int num2) /* Function Definition */


{
int total;

total=num1+num2;

return(total);

Output :

Enter two numbers to be summed :12,13


The sum of 12 and 13 is 25

The above program consists of two functions,

• The required main() function


• The programmer user-defined function addnum, which sums the two values
The function main reads in two integer values, and assigns them to a and b. Then, main()
function calls the function addnum, transferring the integer values a and b receiving their
sum. The sum is then displayed and the program terminates. The integer values are
transferred via the arguments num1 and num2, and their sum total is returned to the calling
portion of the program via the return statement.
Function Call by Value and Call by Reference

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);

/* calling a function to change the values.


* &a indicates pointer to a ie. address of variable a and
* &b indicates pointer to b ie. address of variable 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

1 Using functions write a program that calculates the area of a rectangle

2 Distinguish between call by value and call by reference in functions


Scope –Global, local and Static Variables

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:

▪ Inside a function or a block which is called local variables,


▪ Outside of all functions which is called global variables.
▪ In the definition of function parameters which is called formal parameters.

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>

int g; // Global variable declaration


int main ()
{

int a, b; //local variable declaration

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:

Static variables are declared by writing the key word static.

syntax:

static data type variable name;


eg static int a;
The static variable is initialized only once and it retain between the function call. If its
variable is not initialized, then it is automatically initialized to zero.
Pointers

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

Data type *pointer name;

Eg

int *p1; //pointer to integer type

float *p2; //pointer to float type

char *p3; //pointer to character type

Example of Program using pointers

#include <stdio.h>
int main ()
{
int number = 300; /* actual variable declaration */

int *ptr; /* pointer variable declaration */

ptr = &number; /* store address of number in pointer variable*/

printf("Address of var variable: %x\n", &number );

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];

if(p1==p2) // Pointer comparison of pointer p1 and pointer p2

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

Given two floating - point numbers a and b initialized as follows


a=122.5;
b=10.7;
and two pointer variables c and d initialized as follows
c=&a;
d=&b;

a) Print the values of a,b,c and d


b) Swap the values of a and b and print a,b,c,d.
c) Swap the values of c and d and print a,b,c,d
d) Use the expressions *c and *d to swap the values of a and b. And print a,b,c,d
Structures

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

A structure is defined using the keyword struct as follows

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;
};

Accessing Structure members

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;

strcpy( student2.firstname, "John");


strcpy( student1.surname, "Danda");
strcpy( student1.studentid, "R201890");
student1.age= 35;

/* print Student1 info */

printf( "Student 1 firstname : %s\n", Student1.firstname);


printf( "Student 1 surname : %s\n", Student1.surname);
printf( "Student 1 studentid : %s\n", Student1.studentid);
printf( "Student 1 age : %d\n", Student1.age);

/* print Student2 info */


printf( "Student 2 firstname : %s\n", Student2.firstname);
printf( "Student 2 surname : %s\n", Student2.surname);
printf( "Student 2 studentid : %s\n", Student2.studentid);
printf( "Student 2 age : %d\n", Student2.age);
return 0;

Structure Initialisation

For Example

Structure variable can also be initialized at compile time.


struct Patient
{
float height;
int weight;
int age;
};
struct Patient p1 = { 180.75 , 73, 23 }
Or
struct Patient p1;
p1.height = 180.75; //initialization of each member separately
p1.weight = 73;
p1.age = 23;
Array with a structure

Assignment of a records values entered by user can be done using an array


For example a program snippet that assigns values entered by a user to a structure using an
array is demonstrated below

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);
}

Structure as a Function Argument

A structure can be passed as a function argument just like we pass any other variable or an
array as a function argument.

An example program of a Structure as a Function argument is demonstrated below


#include<stdio.h>
struct Student
{
char Studentname[10];
int age;
};
void show(struct Student st);
void main()
{
struct Student std;
printf("\nEnter Student record:\n");
printf("\nStudent name:\t");
scanf("%s", std.Studentname);
printf("\nEnter Student age.:\t");
scanf("%d", &std.age);
show(std);
}
void show(struct Student st)
{
printf("\nstudent name is %s", st.Studentname);
printf("\nroll is %d", st.age);
}
The above program shows a function void show(struct Studentst) using a structure
Student as a function argument meaning structure values are passed to the fuction when a
function call is executed in the main program

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.

C supports the following basic file operations


• Opening a file.
• Writing data into a file.
• Reading data from a file.
• Closing a file.

Opening and Creating a file

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

The fclose() function is used to close an already opened file.

Syntax :

int fclose( FILE *fptr);

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

Reading and Writing to a File

Using getc() and putc()

getc() and putc() are the simplest functions which can be used to read and write individual
characters to a file.

getc() is used to read a single character to a file

putc() is used to write(enter) a single character to a file


A sample program using getc() and putc() function

#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");

while( (ch = getc(fp)! = EOF)


printf("%c",ch);

// closing the file pointer


fclose(fp);

return 0;
}

Using fscanf() and fprintf()

The fprintf() function is used for writing to a text file.

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;
}

fscanf() function is used for reading from a text file

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.

You might also like