Structured Programming
Structured Programming
Pre-requisite: None
Moses Wainaina
0707691430
Purpose
TOPICS
Learning Outcomes: Upon successful completion of this course, the student should be able to:
Reference TextBooks
1. H.M. Deitel and P.J. Deitel, C: How to Program, 2nd ed Prentice Hall, ISBN 3417600455
2. Bjarne Stroustrup (2008) Programming: Principles and Practice Using C++ Prentice Hall
ISBN 341-6780027
3. B.Kernighan's .D.M. Ritchie's, C Programming Language (2nd Edition) ISBN 345895840
Course Journals
Reference Journals
This is a complete set of step-by-step instructions that control and direct the computer hardware in
carrying out a given task. Tasks may vary from very simple e.g. computing surface area to
complex ones like statistical analysis.
Programming Language
This is a set of symbols and the rules that govern their rules that are employed in the construction
of a computer program.
Syntax
These are the rules of a language that govern the ways in which words, symbols, expressions and
statements may be formed and combined in that language.
Semantics
These are the rules of language that govern meaning of statements in any language.
Programmer
This is a person who is trained and/or specializes in the technique of creating, maintaining and
modifying computer programs.
Programming Languages
A programming language is a tool for developing executable models for a class of problem
domains.
Programming languages provide the basic building block for all software. They are the means by
which people can tell the computer how to carry out a task.
Digital computers represent and process data and instructions as binary numbers. This
representation of instructions and data is called machine language. Program instructions were
written as a series of binary digits (0’s and 1’s). When the program was entered into the computer
execution was direct since machine language needs no translation. The binary combination
allowed the program to have full access to and control the computer’s internal circuitry and
memory addresses.
Advantages
Disadvantages
Advantages
Disadvantages
These languages are user friendly and problem oriented compared to the low level languages.
Programs written in high level languages are shorter than the machine language programs.
They have an extensive vocabulary of words and symbols therefore program instructions are
written using familiar English-like statements and mathematical statements.
A single high-level language program is translated into multiple machine code instructions.
Advantages
i. They are portable i.e. they can be used on more than one type of machine.
ii. Creating program and error correction takes less time.
iii. Are relatively easy to learn and use.
iv. The programmer does not have to be an expert on the internal workings of the machine.
They require the programmer to specify step-by-step how the computer will accomplish a specific
task. Program execution follows the exact sequence laid down by the programmer during coding.
Examples include FORTRAN, PASCAL, BASIC,
They allow the programmer to specify the desired result without having to specify the detailed
procedure needed to achieve the result.
They are more users’ oriented and allow programmers to develop programs with fewer commands
compared with 3rd generation languages. They are called non procedural because programmers
can write programs that need only tell the computer what they want done, not all the procedures
of doing it.
Report Generators: also called report writers. This is a program for end users that is used to
produce reports.
Query Language: This is an easy to use language for retrieving data from a database management
system.
In essence, the programming language is used to denote the properties, or logic, of a solution,
rather than how it is reached. Most constraint-based and logic programming languages are 5GLs.
A common misconception about 5GLs pertains to the practice of some 4GL vendors to denote
their products as 5GLs, when in essence the products are evolved and enhanced 4GL tools.
PROGRAMMING PARADIGMS.
Programming paradigms are a way to classify programming languages according to the style of
computer programming.
Features of various programming languages determine which programming paradigms they belong
to; as a result, some languages fall into only one paradigm, while others fall into multiple
paradigms.
1) Un structured programming.
2) Structured programming
A technique for organizing and coding computer programs in which a hierarchy of modules is
used, each having a single entry and a single exit point, and in which control is passed downward
through the structure without unconditional branches to higher levels of the structure. Three types
of control flow are used: sequential, test, and iteration.
Object Oriented Programming (OOP) is a paradigm in which real-world objects are each viewed
as seperate entities having their own state which is modified only by built in procedures, called
methods. Because objects operate independently, they are encapsulated into modules which
contain both local environments and methods. Communication with an object is done by message
passing.
4) Visual Programming.
In computing, a visual programming language (VPL) is any programming language that lets users
create programs by manipulating program elements graphically rather than by specifying them
textually. A VPL allows programming with visual expressions, spatial arrangements of text and
graphic symbols used either as elements of syntax or secondary notation.
Web programming refers to the writing, markup and coding involved in Web development, which
includes Web content, Web client and server scripting and network security. The most common
languages used for Web programming are XML, HTML, JavaScript, Perl 5 and PHP. Web
programming is different from just programming, which requires interdisciplinary knowledge on
the application area, client and server scripting, and database technology.
HTML5 and CSS3 support most of the client-side functionality provided by other application
frameworks.
Software development is the process of computer programming, documenting, testing, and bug
fixing involved in creating and maintaining applications and frameworks resulting in a software
product. Software development is a process of writing and maintaining the source code, but in a
broader sense, it includes all that is involved between the conception of the desired software
through to the final manifestation of the software, sometimes in a planned and structured process.
It involves forming a clear idea in terms of the information you want to include in the program,
computations needed and the output. At this stage, the programmer should think in general terms,
not in terms of some specific computer language.
2. Design program
The programmer decides how the program will go about its implementation, what should the user
interface be like, how should the program be organized, how to represent the data and what
methods to use during processing.
It is the design Implementation by writing the code i.e. translating your program design into
language instructions.
The compiler also checks errors in your program and reports the error to you for correction. The
object code can never be produced if the source code contains syntax errors.
This is the actual execution of the final code. Once the executable code is complete it can be
invoked in future by typing its name in a ‘run’ command.
This involves checking whether the system does what it is supposed to do. Programs may have
bugs (errors). Debugging involves the finding and fixing of program mistakes.
Occasionally, changes become necessary to make to a given program. You may think of a better
way to do something in a program, a clever feature or you may want to adapt the program to run
in a different machine. These tasks are simplified greatly if you document the program clearly and
follow good program design practices.
Algorithm
An algorithm is a sequence of steps which results to a plan or strategy on how to go about
solving a problem.
Algorithms
In programming, algorithm is a set of well defined instructions in sequence to solve the problem.
Step 1: Start
factorial←1
i←1
5.1: factorial←factorial*i
5.2: i←i+1
Step 7: Stop
Algorithm
START
Step 1 → Take integer variable A
Step 2 → Assign value to the variable
Step 3 → Perform A modulo 2 and check result if output is 0
Step 4 → If true print A is even
Step 5 → If false print A is odd
STOP
Step 1: Start
Step 4: Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 6: Stop
1) Start.
6) End
Step 1: Start
Else
Step 4: Exit
Pseudo code
Pseudocode is the statement in plain English which may be translated later into a programming
language (program).
This is a case where an algorithm is expressed in English like statements (descriptions). For
example the following pseudocode calculates the pay amount for five employees.
BEGIN
OUTPUT("Input number1:")
INPUT s1
OUTPUT("Input number2:")
INPUT s2
sum=s1+s2
OUTPUT sum
END
1. START
3. READ number
ELSE
END IF
5. STOP
Area of a triangle
begin
numeric nBase, nHigh, nArea
display "ENTER THE BASE OF TRIANGLE : "
accept nBase
display "ENTER THE HEIGHT OF TRIANGLE : "
accept nHigh
nArea=nBase*nHigh
display "AREA OF TRIANGLE : " nArea
end
begin
numeric nSide,nPeri
display "ENTER THE SIDE OF SQUARE : "
accept nSide
nPeri=nSide*nSide
display "AREA OF SQUARE : " nPeri
end
begin
numeric nRad, nAre
display "ENTER THE RADIUS OF CIRCLE : "
accept nRad
nAre = nRad*nRad*22/7
display "AREA OF CIRCLE : " nAre
end
begin
numeric nRad,nCir
display "ENTER THE RADIUS OF CIRCLE : "
accept nRad
nCir=2*nRad*22/7
display "CIRCUMFERENCE OF CIRCLE : " nCir
end
begin
numeric nLen,nBrd,nAre
display "ENTER THE LENGTH OF RECGTANGLE : "
accept nLen
display "ENTER THE BREADTH OF RECTANGLE : "
accept nBrd
nAre=2*(nLen+nBrd)
display "PERIMETER OF RECTANGLE : " nAre
end
Flow Chart
Draw flowchart to find the largest among three different numbers entered by user.
2) Constant
3) Instruction
4) Programme
1. CHARACTER SET
, Comma * Asterisk
“ Quotation marks
$ Dollar sign
4) White spaces
WHITE SPACES
i. Horizontal Tab \t
Constant is an entity that do not change e.g pie while variable is an entity that keeps on
We don’t work directly with values so values are stored in the computer memory
Constant name is a memory location that hold a value that don’t change
Variable name is a memory location that holds a value that keeps on changing
2) Secondary type use primary data type to form user defined include the arrays and
Structures
Type Keyword
Meaning
Character Character data Char
1. Void
Description:
Format: (void).
Description:
A character denotes any alphabet, digit or special symbol used to represent in formation and it is
used to store a single character.
Format: %c
Description:
Format: %d
4. Float
Description:
It is used to store real number, with single precision floating point number (precision of 6 digits
after decimal points.)
5. Double
Description:
It stores real numbers with double precision. The use of double doesn’t guarantee to double the
number of significant digits in our result, but it improves the accuracy of the arithmetic and
reduces the accumulation of rounding errors.
Format: %ld
1. Array:
2. Pointer:
3. Structure:
e.g.
Struct employees
int Age;
int Salary;
4. Union:
int m;
float x;
char c;
};
This data types gives us an opportunity to invent your own data type and define what values the
variable of this data type can take.
};
a) The first part declare the data type and specifies its possible values.
foreground=red;
background=blue;
2) Every variable or constant name should start with either underscore or alphabet
4) No special character are allowed within either constant or variable name except underscore
5) In case a variable or a constant name is made up of more than one word, the words can either
be fully joined or joined by use of underscore
3. INSTRUCTIONS
Instructions are of three types:
1) Declarative instruction
2) Arithmetic instruction
3) Control instruction
It is made to introduce the value to be used when solving a problem. It’s done by use of variable
and constant names associated with respective data types e.g. integer, constant number.
NB: Identifiers name of user defined names such as variables, array and function
2) ARITHEMETIC INSTRUCTION
They are for performing computational instruction. There are different operators in C
a) Arithmetic operator
b) Relational operator
c) Logical operator
A) ARITHEMETIC OPERATOR
They include
B) RELATIONAL OPERATOR
C) LOGICAL OPERATOR
Operator Meaning
|| Logical OR
! Logical NOT
3) CONTROL INSTRUCTION
They are the instruction that affect the flow of execution. They are of three types
A) Sequence flow
a) SEQUENCE FLOW
B) SELECTIVE INSTRUCTION
They are statement that allow set of instruction to executed repeatedly until a certain condition is
met
STRUCTURE OF A C PROGRAM
Structure of C program is made of four component:
1) Header file
2) Main()
3) Body
i.e.
# include <stdio.h>
Instruction; Body
}
Header files –these are collection of function which perform a predefined task. Every header file
has extension .h e.g. <stdio.h>- this is a header file that contains input and output function
(functions that manage input and output). <conio.h > this is a header file that hold function that
manage the console.
The main () indicates the beginning of the executable code. The body begins with opening curly
brackets and ends with closing curly brackets. This entails the source code. The general syntax is
as follows:
#include<stdio.h>
#include<conio.h>
main()
{
RULE OF C PROGRAM
1) Each instruction in c program is written as separate statement
N/B first statement should be declarative instruction where needed
2) Statement in a program must appear in systematic order in which one wishes them to be
executed
3) Blank spaces may be inserted between words to improve readability of statement
4) All statement are entered in lower case
5) Ever C statement must be terminated with semicolon
b) scanf()
This function allows an end user input values to work within the program in the respective
variable names and constant names. They should have already been declared.
E.g. int a;
scanf (“%d”, &a);
Thus &a means address location of a
int a, b, c;
scanf (“%d %d”, &a, &b);
c: =a+ b
NB: the format specifiers should be as many as the variable or constant names whose values are
being captured.
2. MANAGING OF OUTPUT
This is to display outputs. This can be with the help of printf (). It can take the following forms:
a) To display values.
In this case the values are represented by their respective variable or constant names.
For example:
int a;
a =5;
print f(“%d”, a);
b) To display a statement
# include <stdio.h>
#include<conio.h>
main ( )
Example:
#include <stdio.h>
int main() {
// C program to demo
// Single Line comment
#include <stdio.h>
int main(void)
{
Output
Enter Fast Number number: 4
Enter Second Number:5
Sum is : 9
int main() {
float per; // we a using float data type because percentage must have decimal number / fraction
scanf("%d",&Eng);
scanf("%d",&Kisw);
scanf("%d",&Math);
scanf("%d",&Sci);
scanf("%d",&ss);
return 0;
}Output:
45 67 89 23 90
Sum : 314
Percentage : 62.000000
#include<stdio.h>
int main() {
scanf("%d", &amount);
scanf("%d", &rate);
scanf("%d", &time);
return();
Output:
The term flow control details the direction the program takes (which way program control
"flows"). Hence it is the basic decision-making process in computing; flow control determines
how a computer will respond when given certain conditions and parameters.
i. Sequence
ii. Selection or decision structure
iii. Iteration or looping structure
This is the simplest control structure. It dictates the order of execution from one statement to the
next within the program. In the absence of repetition or branching, the program instructions will
be executed in the order in which they were coded.
Basically, program statements are executed in the sequence in which they appear in the program.
The sequence control structure is the default or overriding structure.
The structure is used for decision making within a program. It allows alternative actions to be
taken according to conditions that exist at particular stages within a program.
The structure uses a test condition statement, which upon evaluation by the computer gives rise
to certain conditions which may evaluate to a Boolean true or false. Based on the outcome of the
test condition, the computer may execute one or more statements.
a) The if statement
b) The if – Else statement
c) Nested If
d) Switch-case statement
a) The If statement
Syntax
If (Condition)
#include <stdio.h>
int main()
{
int x, y;
printf("enter the value of x:");
scanf("%d", &x);
printf("enter the value of y:");
scanf("%d", &y);
if (x>y)
{
printf("x is greater than y\n");
}
return 0;
}
#include <stdio.h>
int main()
{
int x, y;
printf("enter the value of x:");
scanf("%d", &x);
printf("enter the value of y:");
Output
x is equal to y
b) If – else statement
The if else statement lets the programmer choose between two statements as opposed to the
simple if statement which gives you the choice of executing a statement or skipping it.
if(Condition)
{
(Statement (s)) ; /* statement(s) will execute if the condition is true */
}
else
{
Examples
To check which number is greater between two numbers entered by the user
#include<stdio.h>
main()
{
int a, b;
printf("Please enter the value for a:");
scanf("%d", &a);
printf("\nPlease the value for b:");
scanf("%d", &b);
if(a>b){
printf("\n a is greater");
} else {
printf("\n b is greater");
}
Example 2
To get the greatest number between three number entered by the user
#include<stdio.h>
int main()
{
int num1,num2,num3;
//Ask user to input any three integer numbers
printf("\nEnter value of num1:");
//Store input values in variables for comparsion
scanf("%d ",&num1);
printf("\nEnter value of num2:");
//Store input values in variables for comparsion
scanf("%d ", num2);
if((num1>num2)&&(num1>num3))
printf("\n Number1 is greatest");
else if((num2>num3)&&(num2>num1))
printf("\n Number2 is greatest");
else
printf("\n Number3 is greatest");
return 0;
}
Output
Number2 is greatest
c) Nested if statement
Writing an if statement inside another if statement is called nested if statement. The general
syntax of the nested if statement is as follows
The nested if statement can be defined using any combination of simple if & if-else statements
#include <stdio.h>
int main(){
int n ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;
if ( n < 100 )
{
printf("Given number is below 100\n") ;
if( n%2 == 0)
printf("And it is EVEN") ;
else
printf("And it is ODD") ;
}
The switch statement contains one or more number of cases and each case has a value associated
with it. At first switch statement compares the first case value with the switchValue, if it gets
matched the execution starts from the first case. If it doesn't match the switch statement compares
the second case value with the switchValue and if it is matched the execution starts from the second
case. This process continues until it finds a match. If no case value matches with the switchValue
specified in the switch statement, then a special case called default is executed.
When a case value matches with the switchValue, the execution starts from that particular case.
This execution flow continues with next case statements also. To avoid this, we use "break"
statement at the end of each case. That means the break statement is used to terminate the switch
statement. However it is optional.
#include <stdio.h>
int main()
{
int week;
/* Input week number from user */
printf("Enter week number(1-7): ");
scanf("%d", &week);
switch(week)
{
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
Output
Monday
#include <stdio.h>
int main()
{
int month;
printf("Input Month No 1-12 : ");
scanf("%d",&month);
switch(month)
{
case 1:
printf("January\n");
break;
case 2:
printf("February\n");
break;
case 3:
printf("March\n");
break;
case 4:
Output:
April
Consider a situation in which we execute a single statement or block of statements repeatedly for
required number of times. Such kind of problems can be solved using looping statements in C. For
example, assume a situation where we print a message for 100 times. If we want to perform that
task without using looping statements, we have to either write 100 printf statements or we have to
write the same message for 100 times in a single printf statement. Both are complex methods. The
same task can be performed very easily using looping statements.
The looping statements are used to execute a single statement or block of statements repeatedly
until the given condition is FALSE.
a) while statement
b) do-while statement
c) for statement
a) While statement
The while statement is used to execute a single statement or block of statements repeatedly as long
as the given condition is TRUE. The while statement is also known as Entry control looping
statement
Syntax
50 | P a g e Moses Wainaina 0707691430
The syntax of a while loop in C programming language is:
while(condition)
{
statement(s);
}
Flowchart
#include<conio.h>
int main(){
int n = 0;
printf("Even numbers up to 10\n");
while( n <= 10 )
{
if( n%2 == 0) //This is to check if the number is divisible by 2
printf("%d", n) ;
n++ ; //this is increment operator
}
return 0;
}
Output
Even numbers up to 10
0 2 4 6 8 10
Output
11
22
33
44
#include<stdio.h>
int main()
{
int Number, i = 1, Sum = 0;
Output
Please enter the number of integer value 10
Sum of Natural Numbers = 55
b) Do –while loop
In this structure the test condition is placed after the block of code that is to be repeatedly
executed. The computer first executes the block of code then evaluates the test condition
statement.
Syntax
The syntax of a do...while loop in C programming language is:
do
{
statement(s);
}while( condition );
Flowchart
do
{
Sum = Sum + i;
i++;
} while(i <= Number);
Output
Please enter the number of integer value 10
Sum of Natural Numbers = 55
#include<stdio.h>
int main(){
int n = 0;
printf("Even numbers up to 10\n");
do
while( n <= 10 );
return 0;
}
Output
Even numbers up to 10
0 2 4 6 8 10
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);
The init step is executed first, and only once. This step allows you to declare and initialize any
loop control variables. You are not required to put a statement here, as long as a semicolon appears.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the
body of the loop does not execute and the flow of control jumps to the next statement just after the
'for' loop.
After the body of the 'for' loop executes, the flow of control jumps back up to the increment
statement. This statement allows you to update any loop control variables. This statement can be
left blank, as long as a semicolon appears after the condition.
The condition is now evaluated again. If it is true, the loop executes and the process repeats itself
(body of loop, then increment step, and then again condition). After the condition becomes false,
the 'for' loop terminates.
#include <stdio.h>
int main () {
int a;
return 0;
}
Example 2: To display 10 9 8 7 6 5 4 3 2 1
#include<stdio.h>
int main()
{
int n;
for(n=10;n>=1;n--)
{
printf(" %d",n);
}
return 0;
}
Example 3:
#include<stdio.h>
int main()
{
int n, m; Output
for(n=0;n<5;n++){
for (m=0;m<=n;m++){
printf("*");
}
printf("\n");
}
return 0;
}
for(n=1;n<5;n++){
for (m=5;m>=n;m--){
printf("*");
}
printf("\n");
}
return 0;
}
Example 5 :
#include <stdio.h>
int main() {
Output
int i,j,k;
for (i=1; i<=5; i++) {
for (j=5; j>=i; j--) {
printf(" ");
}
for (k=1; k<=i; k++) {
printf("*");
}
printf("\n");
}
}
Example 6:
#include<stdio.h>
int main() Output
{
int n;
for(n=10;n>=1;n--)
{
printf(" %d",n);
}
return 0;
}
A pointer is a secondary data type (also known as derived data type) in C. It is built from one of
the primary data types available in C language. Basically pointer contains memory address of
other variable or function as their value. As pointer deals with memory address, it can be used to
access and manipulate data stored in memory.
Pointer is one of the most exciting features of C language and it has added power and flexibility
to the language. Pointer is in C language because it offers following benefits to the programmers:
3. Pointer helps to return multiple values from a function through function argument.
5. Pointer is an efficient tool for manipulating structures, linked lists, queues stacks etc. We can
achieve these and much more benefits from pointer only if we can use it properly.
Pointer Declaration
type *var_name;
Here, type is the base type of the pointer. The base type specifies the type of the object that the
pointer can point to. Notice that an asterisk precedes the variable name. This tells the computer
that a pointer variable is being created. For example, the following statement creates a pointer to
an integer.
int *p;
Pointer Operators
C contains two special pointer operators: * and &. The operator returns the address of the
variable it precedes. The * operator returns the value stored at the address that it precedes. The *
pointer operator has no relationship to the multiplication operator, which uses the same symbol).
For example, examine this short program.
Explanation
First, the line int *p, q; defines two variables: p, which is declared as an integer pointer, and q,
which is an integer. Next, q is assigned the value 100.
In the next line, p is assigned the address of q. You can verbalize the & operator as “address of.“
Therefore, this line can be read as: assign p the address of q. Finally, the value is displayed
using the * operator applied to p. The * operator can be verbalized as “at address”.
Therefore the printf( ) statement can be read as “print the value at address q,” which is 100.
When a variable value is referenced through a pointer, the process is called indirection. It is
possible to use the * operator on the left side of an assignment statement in order to assign a
variable a new value using a pointer to it.
Example 1:
Program that uses a for loop that counts from 0 to 9. It puts in the numbers using a pointer.
#include<stdio.h>
main()
{
int i,*p;
p = &i;
for ( i =0; i <10; i++)
printf (“ %d ”, *p);
return 0;
}
Types of Arrays:
1. One dimension array (Also known as 1D array).
2. Two dimension array (Also known as 2D array).
3. Multidimensional array.
This means that i [0] will have the value 1 and i [4] will have the value 25.
You can initialize character arrays in two ways. First, if the array is not holding a null -
terminated string, you simply specify each character using a comma separated list. For example,
this initialize a with the letters ‘A’, ‘B’, and ‘C’.
If the character array is going to hold a string, you can initialize the array using a quoted string,
as shown here.
Notice that no curly braces surround the string. They are not used in this form of initialization.
Because strings in C must end with a null, you must make sure that the array you declare is long
enough to include the null. This is why name is 6 characters long, even though “Peter” is only 5
characters. When a string constant is used, the compiler automatically supplies the null
terminator
Example 1
Output
The output will be 9 7 8 0 4
Example 2
#include<stdio.h>
main()
{
char str1[80],str2[80];
printf( " Enter your name: \n");
gets(str1);
printf( " Enter your home county: \n");
gets(str2);
printf("Your name is %s\n",str1);
printf("Your home county is %s\n",str2);
return 0;
}
Output
Syntax:
data_type array_name[row_size][column_size];
Example:1
int arr[3][3];
So the above example declares a 2D array of integer type. This integer array has been named
Example 2
#include<stdio.h>
int main()
{
int i, j;
int arr[3][3]={{12,45,63},{89,34,73},{19,76,49}};
printf(" 2D Array Elements \n\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",arr[i][j]);
}
printf("\n");
}
Return 0;
}
Output
3. Multidimensional arrays
Multidimensional arrays are initialised the same way as one-dimensional ones.
For example, here the array sqr is initialised with the values 1 though 9, using row order.
This initialization causes sqr[0][0] to have the value 1, sqr[0][1] to contain 2, sqr[0][2] to
contain 3, and so forth.
If you are initializing a one-dimensional array, you need not specify the size of the array; simply
put nothing inside the square brackets. If you don’t specify the size, the compiler simply counts
the number of initialization constants and uses that that value as the size of the array.
Arrays that don’t have their dimensions explicitly specified are called unsized arrays. An unsized
array is useful because it is easier for you to change the size of the initialization list without
having to count it and then change the array dimension. This helps avoid counting errors on long
lists, which is especially important when initializing strings.
STRUCTURE
Suppose you want to write a program that keeps tracks of students [Name, Marks] i.e. a variety
of information to be stored about each student. This requires;
• An array of strings (for the Names).
• Marks in an array of integers
A structure is an aggregate data type that is composed of two or more related elements. If we are
using C structure then we are combining different related data types in one group so that we can
use and manage those variables easily
Setting up A Structure
In our example, we can have the following template;
struct student
{
char name[SIZE];
int marks;
};
The above describes a structure made up of a character array name, and int variable marks.
Explanation
• The keyword struct announces to the computer that what follows is a structure data type
template.
• The tag follows: which is a shorthand label that can be used later to refer to this structure. In the
above example, the tag name is student.
• A list of structure members enclosed in a pair of braces. Each member is described by its own
declaration. For example; the name portion is a character array of SIZE elements.
main()
{
struct student mystudent; /* declare mystudent as a student type */
printf("Please enter the name of the student \n");
scanf("%s", mystudent.name);
printf("Enter the marks obtained \n");
scanf("%d", &mystudent.marks);
printf("%s: got %d ", mystudent.name, mystudent.marks );
printf("\n");
system("pause");
return 0;
}
Output
Use of Structures
The immediate application that comes to mind is database management. For example, to
maintain data about employees in an organization, books in a library, items in a store, financial
transactions in a company. Their use however, stretches beyond database management. They can
be used for a variety of applications like:
• Checking the memory size of the computer.
• Hiding a file from a directory
• Displaying the directory of a disk.
• Interacting with the mouse
• Formatting a floppy
• Drawing any graphics shape on the screen.
FUNCTION IN C
A function is a set of instruction that performs a specific task.
Inbuilt function are declared and defined within the compiler. For example:
User defined
These are the functions which are declared and defined by the programmer.
Properties of functions
Whether user defined or inbuilt functions can exhibit the following properties:
3) Every function may or may not return a value to the calling function
Benefits of function:
3) It reduces the aspect of rewriting the source code of statement again and again within the same
programme
5) It reduces developing time of any application since a function can be reused in different
application
Syntax:
Return_Type Function_Name ( ) // Function Definition
{
// body of Statement;
}
*/
#include<stdio.h>
//Function Declaration
void add();
int main()
{
//Function Calling
add();
return 0;
}
//Function Definition
void add()
{
int a,b,c;
printf("\nEnter The Value of A & B :");
scanf("%d%d",&a,&b);
c=a+b;
printf("\nTotal : %d",c);
}
Output
34
When a function has arguments, it receive any data from the calling function but it returns no
values.
Syntax :
Return_Type Function_Name ( Parameters ) // Function Definition
{
// body of Statement ;
}
Example :
void add ( int x , int y )
{
// body of Statement ;
}
Source Code
//Function Declaration
void add(int,int);
int main()
{
int a,b;
printf("\nEnter The Value of A & B : ")l
scanf("%d%d",&a,&b);
//Function Calling
add(a,b); // Actual Parameters
return 0;
}
//Function Definition
void add(int a,int b) //Formal Parameters
{
int c;
c=a+b;
Output
34
Total : 57
There could be occasions where we may need to design functions that may not take any
arguments but returns a value to the calling function. A example for this is getchar function it has
no parameters but it returns an integer an integer type data that represents a character.
Syntax :
Return_Type Function_Name ( ) // Function Definition
{
// body of Statement ;
}
Example :
int add ( )
{
// body of Statement ;
}
Source Code
int add();
int main()
{
int a;
a=add();
printf("\nTotal : %d",a);
return 0;
70 | P a g e Moses Wainaina 0707691430
}
int add()
{
int a,b;
printf("\nEnter The Value of A & B : ");
scanf("%d%d",&a,&b);
return a+b;
}
Output
45
Total : 51
Here this function is taking any input argument, and also returns value.
Syntax :
Return_Type Function_Name ( Parameters ) // Function Definition
{
// body of Statement ;
}
Example :
int add ( int x , int y )
{
// body of Statement ;
}
Source Code
Output
Total : 11
inprotected.com