Professional Documents
Culture Documents
Programming Notes
Programming Notes
ALGORITHMS
Most people are familiar with the existing tasks the computer can perform.You will
learn how to command computers to perform those tasks. i.e software-instructions you
write to command computers to perform actions and make decisions that controls
computer hardware.
PROGRAMMING CONCEPTS
PROGRAMMING ERRORS/BUGS
PROGRAM TRANSLATION
NB:Programs don’t always work on first try.Each of preceding phases can fail
due to various errors.
Unstructured Programming
It consists of a set of statements executed from top to bottom (in order)
Structured Programming (Modular programming)
Its used to divide large applications into a set of procedures that can be used to
perform a certain task.A program is subdivided into small programs called
modules that can be solved independently.It was used in large [programming
and also called bottom-up programming.
Procedural programming
This emphasizes on the design of a program using a given procedure. A
procedure is used to solve certain task.
Object oriented programming
The aspect of writing programs using objects and classes.
Event Driven programming
LOW-LEVEL LANGUAGES
These are the basic programming languages, which can easily be understood by the
computer directly, or which require little effort to be translated into computer
understandable form.
They include:
1. Machine languages.
2. Assembly languages.
Features of low-level languages
They are machine hardware-oriented.
They are not portable, i.e., a program written for one computer cannot be installed
and used on another computer of a different family.
They use Mnemonic codes.
They frequently use symbolic addresses.
1.Pseudocode-
This is an artificial and informal language that helps programmers develop
algorithms.It is similar to every day English.
A pseudocode is a method of documenting a program logic in which English-like
statements are used to describe the processing steps.
These are structured English-like phrases that indicate the program steps to be
followed to solve a given problem.
It is convenient and user friendly although its not atual computer programming
language.This helps programmers “thinking out” a program before putting it in actual
coding.
Guidelines for designing a good pseudocode.
1. The statements must be short, clear and readable.
2. The statements must not have more than one meaning (i.e., should not be
ambiguous).
3. The pseudocode lines should be clearly outlined and indented.
4. A pseudocode must have a Begin and an end.
i.e., a pseudocode should show clearly the start and stop of executable statements and
the control structures.
The input, output and processing statements should be clearly stated using keywords
such as PRINT, READ, INPUT
Example 1:
Write a pseudocode that can be used to prompt the user to enter two numbers, calculate
the sum and average of the two numbers and then display the output on the screen.
START
PRINT “Enter two numbers”
INPUT X, Y
Sum = X + Y
Average = Sum/2
PRINT Sum
PRINT Average
STOP
Example 2:
Write a structured algorithm that would prompt the user to enter the Length and Width
of a rectangle, calculate the Area and Perimeter, then display the result.
Solution
Step 1: Draw the rectangle of Length (L) and Width (W).
Step 2: Write down the Pseudocode.
START
PRINT “Enter Length and Width”
READ L, W
Area = L * W
Perimeter = 2 (L + W)
PRINT Area
PRINT Perimeter
STOP
Example 3:
Write a pseudocode that can be used to calculate the Diameter, Circumference and
Area of a circle and then display the output on the screen.
START
Set π to 3.14
Prompt the user for the Radius (R)
Store the radius in a variable (R)
Set Diameter to 2 * Radius
Set Circumference to π * 2 * Radius
Set Area to π * Sqr (Radius)
PRINT Diameter
PRINT Circumference
PRINT Area
STOP
Example 4:
Write a pseudocode for a program that would be used to solve equation: E = MC2.
START
Enter values from M to C
E=M*C*C
Display E
Example 5:
Write a pseudocode for a program that can be used to classify people according to age.
If a person is more than 20 years; output “Adult” else output “Young person”.
START
PRINT “Enter the Age”
INPUT Age
IF Age > 20 THEN
PRINT “Adult”
ELSE
PRINT “Young person”
STOP
Note. Pseudocodes make an algorithm easier to understand. This is because; the
algorithm can be read from top to bottom without the need for jumping backwards or
forwards to follow the logic of the algorithm as in flowcharts.
2.Flowcharts
This is a graphical representation of an algorithm.
They are drawn using special symbols.They are useful for developing and representing
an algorithm. They clearly show how control structures operates.
A Flowchart is a diagrammatic or pictorial representation of a program’s algorithm.
It is a chart that demonstrates the logical sequence of events that must be performed
to solve a problem
Types of Flowcharts.
There are 2 common types of Flowcharts:
1). System flowchart.
A System flowchart is a graphical model that illustrates each basic step of a data
processing system.
It illustrates (in summary) the sequence of events in a system, showing the
department or function responsible for each event.
2). Program flowchart.
This is a diagram that describes, in sequence, all the operations required to process
data in a computer program.
A program flowchart graphically represents the types of instructions contained in a
computer program as well as their sequence & logic.
√ The words Begin & End (or Start & Stop) should be inserted in the Terminal
symbol.
3. Process symbol.
(Rectangle)
- Process symbol is used to indicate that a processing or data transformation is
taking place.
The information placed within the process symbol may be an algebraic formula or a
sentence to describe processing.
NO (Rhombus)
YES
5. Flow lines.
Flow lines with arrowheads are used to indicate the direction of processing of the
program logic, i.e., they show the order in which the instructions are to be executed.
The normal flow of a flowchart is from Top to Bottom, and Left to Right.
Note. Flow lines should never cross each other.
6. Connector symbol.
Sometimes, a flowchart becomes too long to fit in a single page, such that the flow
lines start crisscrossing at many places causing confusion & also making the
flowchart difficult to understand.
The Connector symbol is used as a connecting point for arrows coming from
different directions.
A Connector symbol is represented by a Circle, and a letter or digit is placed within
the circle to indicate the link.
Note. Connectors do not represent any operation. They are used to connect two
parts of a flowchart, indicating that the flow of data is not broken.
General guidelines for drawing a program flowchart.
1. A flowchart should have only one entry/starting point and one exit point (i.e.,
ensure that the flowchart has a logical start and finish).
2. The flowchart should be clear, neat and easy to follow.
3. Use the correct symbol at each stage in the flowchart.
4. The flowchart should not be open to more than one interpretation.
5. Avoid overlapping the lines used to show the flow of logic as this can create
confusion in the flowchart.
6. Make comparison instructions simple, i.e., capable of YES/NO answers.
7. The logical flow should be clearly shown using arrows.
Note. A flowchart should flow from the Top to Bottom of a page, and from the
Left to the Right.
8. Where necessary, use Connectors to reduce the number of flow lines.
Connectors are helpful when a flowchart is several pages long, and where several
loops are needed in the logic of the flowchart.
9. Check to ensure that the flowchart is logically correct & complete.
Star
Example 1: t
Stop
Example 2:
Draw a flowchart for a program that would prompt the user to enter the Length and
Width of a rectangle, calculate the Area and Perimeter, then display the result.
Star
t
L,
W
Area = L x W
Perimeter = 2 (L x W)
Stop
Example 3:
Draw a flowchart for a program that can be used to calculate the Diameter,
Circumference and Area of a circle and then display the output on the screen.
Star
t
SET
π = 3.14
Radius
(R)
Diameter = 2 x Radius
Circumference = π x 2 x Radius
Area = π x Sqr (Radius)
Diameter, Circumference,
Area
Example 4: Stop
Design a flowchart for a program that can be used to classify people according to age.
If a person is more than 20 years; output “Adult” else output “Young person”.
Star
t
Age
No
Age> Young person
20?
Yes
Adul
t
Stop
Example 5:
Draw a flowchart for a program that would be used to classify animals according to
sex. If a letter M is input, the program should display ‘Male’ otherwise it should
display “Female”.
Star
t
Enter Letter
Yes
Letter = Mal
M e
No
Femal
e
Stop
Example 6:
Write a program using a flowchart to convert temperature from 0C to 0F.
Fahrenheit =32 + (9o x C/5).
Star
t
READ Temp.
in oC
Store value in
memory
Calculate Fahrenheit
F = 32 + (9/5 * oC)
PRINT temp.
in oC & oF
Stop
Notes.
A flowchart must have a Start and an end.
A flowchart is useful when the algorithm is short & the flowchart can fit
conveniently on a single page. If the flowchart is too large, it is recommended to
use Pseudocodes for long & complicated programs.
STRUCTURE OF A PROGRAM
#include<stdio.h>//pre-processor directive
Int main()
{
Printf(“My first program\n”);
Return 0;/*program end successfully*/
}
a) Documentation section-it consists of comments giving the title of the
program,the author,the date of creation,the aim or objectives of the program.
b) The compile directive-It provides instructions to the compiler to link the
functions to its system library e.g
#include<stdio.h>,#include<math.h>.#include<stdlib.h>
c) Main function-It indicates the start of execution or the program statement.The
main function is used to call any other program in the body of a program and is
executable in a sequential manner. A function is a small program that carries out
a specific task when called
d) Body of the program-It consists of opening and closing braces.
e) Declaration of variables-All variables must be declared before use.
f) Return 0-This means terminating a function, it puts an end to execution of a
program. It returns the control to the operating system
IDENTIFIERS
In C programming, identifiers are names given to C entities, such as variables,
functions, structures etc.
Identifier are created to give unique name to C entities to identify it during the
execution of program.
It’s a name given to a variable, constant or a function.
Rules for naming identifiers
i. It must should not be a reserved word or keyword
ii. It should always start with an alphabet
iii. It should not contain special characters
iv. It can contain alphabets, numericals i.e alphanumeric
v. Should be upto 256 characters
1. float
2. double
1. FLOAT:
Float data type allows a variable to store decimal values.
Storage size of float data type is 4. This also varies depend upon the processor in the CPU as
“int” data type.
We can use up-to 6 digits after decimal using float data type.
For example, 10.456789 can be stored in a variable using float data type.
2. DOUBLE:
Double data type is also same as float data type which allows up-to 10 digits after decimal.
The range for double datatype is from 1E–37 to 1E+37.
1.3.1. SIZEOF() FUNCTION IN C LANGUAGE:
sizeof() function is used to find the memory space allocated for each C data types.
1 #include <stdio.h>
2 #include <limits.h>
3 int main()
4 {
5 int a;
6 char b;
7 float c;
8 double d;
9 printf("Storage size for int data type:%d \n",sizeof(a));
10 printf("Storage size for char data type:%d \n",sizeof(b));
11 printf("Storage size for float data type:%d \n",sizeof(c));
12 printf("Storage size for double data type:%d\n",sizeof(d));
13 return 0;
14 }
Output:
Storage size for int data type:4
Storage size for char data type:1
Storage size for float data type:4
Storage size for double data type:8
1.3.2. MODIFIERS IN C LANGUAGE:
The amount of memory space to be allocated for a variable is derived by modifiers.
Modifiers are prefixed with basic data types to modify (either increase or decrease) the amount
of storage space allocated to a variable.
For example, storage space for int data type is 4 byte for 32 bit processor. We can increase the
range by using long int which is 8 byte. We can decrease the range by using short int which is 2
byte.
There are 5 modifiers available in C language. They are,
1. short
2. long
3. signed
4. unsigned
5. long long
of each C basic data type in 16 bit processor.
Below table gives the detail about the storage size
Please keep in mind that storage size and range for int and float datatype will vary
depend on the CPU processor (8,16, 32 and 64 bit)
The above enum functionality can also be implemented by “#define” preprocessor directive as
given below. Above enum example is same as given below.
#define Jan 20;
#define Feb 21;
#define Mar 22;
C – ENUM EXAMPLE PROGRAM:
C
1 #include <stdio.h>
2 int main()
3 {
4 enum MONTH { Jan = 0, Feb, Mar };
5 enum MONTH month = Mar;
6 if(month == 0)
7 printf("Value of Jan");
8 else if(month == 1)
9 printf("Month is Feb");
10 if(month == 2)
11 printf("Month is Mar");
12 }
Output:
Month is March
3. DERIVED DATA TYPE IN C LANGUAGE:
Array, pointer, structure and union are called derived data type in C language.
To know more about derived data types, please visit “C – Array” , “C – Pointer” , “C –
Structure” and “C – Union” topics in this tutorial.
4. VOID DATA TYPE IN C LANGUAGE:
Void is an empty data type that has no value.
This can be used in functions and pointers.
Please visit “C – Function” topic to know how to use void data type in function with simple call
by value and call by reference example programs.
VARIABLE DECRALATION
Variable declaration tells the computer to allocate memory for the variables of the
given data type.
Scope of variables
a. Global variables-these are variables which are used in the whole program. They
are declared before the main function
e.g #include<stdio.h>
int marks;//Global variable
int main()
{
}
b. Local variables-the scope is limited to a block of codes enclosed in braces
e.g #include<stdio.h>
int main()
{
Int marks;//local variable
}
Initializing variables
Syntax:
Datatype variable_name=value
Constants
This is a memory location that stores values which are not determined to change
Constants are the terms that can't be changed during the execution of a program.
e.g pie=3.142
Declaration of constants
There are two ways of declaring constants
a. Before the main function-We use the #define followed by the constant name
and the value
i.e #define constant_name value
e.g #include<stdio.h>
#define pie 3.142
Int main()
{
}
b. After the main function
Syntax:
Const datatype constant_name=value
e.g
#include<stdio.h>
Int main()
{
Const double pie=3.14
}
EXPRESSIONS
Operator Description
== Equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
!= Not equal to
c) Logical operators-They are used to test more than one condition and make a
decision. They always perform true or false results.
Operator Meaning
&& AND
|| OR
! NOT
Result
True True True
True False True
False True True
False False False
NOT False=True
NOT True=False
It gives the opposite of the results
Understanding printf()
printf() sends data to the standard output device,which is generally the screen.
Format:
printf(control_string[,one or more values])
printf() always requires a control_string.
NB: You can insert an l (lowercase l) or L before the integer and floating point
conversion characters(such as %ld and %lf)to indicate that a long integer or long
double floating point is to be printed.
Printing strings
printf(“This is stage 2”); is the same as
printf(“%s”,”This is stage 2”);
The %s informs the printf() function that a string follows.
NB:C does not need the %s to print strings,the %s is redundant.
You must use the %c conversion character any time you print single characters.
e.g printf(“%c %c %c”,’A’,’B’,’C’);
Output on screen is:
ABC
When you want to print a numeric constant or variable,you must include the proper
conversion character inside the printf() control string.
Example 1
#include<stdio.h>
main()
{
char first='E';
char middle='W';
char last='C';
int age=32;
int dependents;
float salary=25000.00;
float bonus=575.25;
If you need to print a table of numbers,you can use the \t tab character.
Example 2
#include<stdio.h>
main()
{
printf(“Parrots\tRams\tKings\n”);
printf(“%d\t%d\t%d\n”,3,5,2);
printf( “%d\t%d\t%d\n”,2,5,1) ;
printf( “%d\t%d\t%d\n”,2,6,4) ;
return 0 ;
}
However if you insert a number before the d in the conversion character,you can
control exactly how many positions print.
The following printf() prints the number 456 in five positions(with two leading spaces)
Printf(“%5d”,456);
If you put a minus sign before the width specifier,C left justifies the number inside the
width.
The width specifier is more important when you want to print floating point numbers.
Format:
%width.decimalsf
The floating point conversion character,%6.2f tells C to print a floating point number
within six positions,including the decimal point and the fractional part.It also informs C
to print two decimal places.If C has to round the fractional part,it does so
e.g printf(%6.2f,134.568767);
produces this output:
134.57
Without the format modifier,C would print
134.568767
Using scanf() for input
The scanf() function is one way to get input from the keyboard.
Format:
Scanf(control_string,one or more values);
return 0;
}
output
What is the total amount of the sale? 10.00
The sales tax for 10.00 is 0.70
TYPECASTING
You can override c defaults conversions by specifying your own temporary type
change.This is called typecasting
When you typecast you temporarily change variable data type from its declared data
type to a new one.
e.g
int age;
double age_factor;
int factor;
age_factor=(double)age*factor//temporarily change age from int to double
CONTROL STRUCTURES
Start
Exit
#include<stdio.h>
int main()
{
int grade;
printf("Enter grade\n");
scanf("%d", &grade);
if(grade>=50)
{
printf("Passed\n");
}
return 0;
}
The if……else selection statement
It performs an indicated action only when the condition is true; otherwise the action is
skipped.
Start
Conditio
n
Action Action
End
#include<stdio.h>
int main()
{
int grade;
printf("Enter grade\n");
scanf("%d", &grade);
if(grade>=50)
{
printf("passed\n");
}
else
{
printf("failed\n");
}
return 0;
int main()
{
int marks;
printf("Enter grade\n");
scanf("%d", &marks);
if ((marks>=0) &&(marks<=49))
{
printf("Grade is D\n");
}
else if((marks>=50) &&(marks<=64))
{
printf("Grade is C\n");
}
else if((marks>=65) &&(marks<=79))
{
printf("Grade is B\n");
}
else if((marks>=80) &&(marks<=100))
{
printf("Grade is A\n");
}
else
{
printf("Invalid entry");
}
return 0;
}
Format:
Switch(expression)
{
Case (expression1):
{
One or more C statements;
}
Case (expression2):
{
One or more C statements;
}
Case (expression3):
{
One or more C statements;
}
…
…
…
Default:
{
One or more C statements;
}
}
If the block is only one statement long,you do not need the braces,but they are
recommended.
The default line is optional and it doesn’t have to be the last line of the switch body.
true
Case Case a action(s) break
a
false
true
Case Case a action(s) break
b
false
.
.
false
default
The flowchart makes it clear that each break statement at the end of a case causes
control to immediately exit the switch statement.
#include<stdio.h>
Int main()
{
Int marks;
Char Grade;
printf(“Please enter student marks\n”);
scanf(“%d”, &marks);
switch(marks)
{
case (marks>=0 && marks<=49)
{
Grade=’D’;
Break;
}
case (marks>=50 && marks<=64)
{
Grade=’C’;
Break;
case (marks>=65 && marks<=79)
{
Grade=’B’;
Break;
case (marks>=80 && marks<=100)
{
Grade=’A’;
Break;
}
default:
{
Printf(“You must enter a number between 0 to 100”);
}
return 0;
}
}
Repetition/Looping
A loop is a group of instructions the computer executes repeatedly while some loop-
continuation condition remains true.
Two main types :
i. Counter-controlled repetition-Also called definite repetition because we know
in advance exactly how many times the loop will be executed.e.g for loop
ii. Sentinel-uncontrolled repetition-Also called indefinite repetition because its not
known in advance how many times the loop will be executed.e.g do…while and
while
for loop
format of the for loop:
for(start expression;test expression;count expression)
{
Block of one or more c statements;
}
Start
Initial counter
(start expression)
Exit
Example 1
#include<stdio.h>
int main()
{
int ctr;
for(ctr=1;ctr<=10;ctr++)
{
printf(“%d\n,ctr”);
}
return 0;
}
Example 2
#include<stdio.h>
int main()
{
int total,ctr;
total=0;
for(ctr=100;ctr<=200;ctr++)
{
total+=ctr;
}
printf(“The total is %d\n,total”);
return 0;
}
Example 3
#include<stdio.h>
int main()
{
int ctr;
total=0;
for(ctr=10;ctr!=0;ctr--)
{
printf(“%d\n,ctr”);
}
return 0;
}
When decrementing a loop variable,the initial value should be larger than the end value
being tested.
output
10
9
8
7
6
5
4
3
2
1
output
While
Format:
While(test expression)
{
Block of one or more statements;
} Start
The test expression usually contains relational,and possibly logical operators.
The while loop tests the expression at the top of the loop.
Conditio Execute
n statements
Exit
True
False
#include<stdio.h>
int main()
{
int counter=0;
while(counter<=10)
{
printf(“%d”,counter);
counter++;
}
printf(“%d”,counter);
return 0;
}
Start
do……while
its similar to the while loop except the relational test occurs at the bottom(rather than
top)of the loop.this ensures that the body of the loop executes at least once.
Format:
do Execute statement(s)
{
Block of one or more c statements;
}
while(test expression)
Exit
True
False
#include<stdio.h>
Int main()
{
int ctr=1;
do
{
printf(“%d\n”,ctr);
ctr++;
}
while (ctr<=10);
return 0;
}
Controlling flow
Using break statement
You use a break statement to quit or exit a loop early.
#include<stdio.h>
main()
{
int ctr;
for(ctr=1;ctr<=10;ctr++)
{
printf(“%d”,ctr);
continue;//causes body to end early
printf(“C programming \n”);
}
return 0;
}
output
1 2 3 4 5 6 7 8 9 10
goto statement_label
C FUNCTIONS
Experience has shown that the best way to develop and maintain a large program is to
construct it from smaller pieces or modules each of which is more manageable than the
original program.
Modules in C are called functions
Functions are invoked by a function call,which specifies the function name and
provides information(as arguments)that the called function needs inorder to perform its
designated task.
Functions are normally used in a program by writing the name of the function followed
by a left parenthesis followed by the arguments(or a comma separated list of
argument)of the function followed by a right parenthesis.
e.g a programmer desiring to calculate and print the square root of 900.0 might write.
printf(“%2f”,sqrt(900.0));
Function definitions
Each program we have presented has consisted of a function called main that called
standard library functions to accomplish its tasks.We now consider how programmers
write their own customized function
Format:
return_value_type function_name(parameter_list)
{
definitions
statements
}
The function_name is any valid identifier.
The return_value_type is the data type of the result returned to the caller.
The return_value_type void indicates that a function does not return a value. An
unspecified return_value_type is assumed by the compiler to be int.
N/B However omitting the return type is discouraged.
Together,the return_value_type,function_name and parameter_list are
sometimes referred to as the function header.
The parameter_list is a comma-separated list that specifies the parameters
received by the function when it is called.if a function doesn’t receive any
values,parameter_list is void.
A type must be listed explicitly for each parameter unless the parameter is of
type int.If a type is not listed,int is assumed.
Example
#include<stdio.h>
#define pi 3.142
int main()
{
float radius;
printf(“Please enter radius\n”);
scanf(“%f”, &radius);
circle(radius);
}
float circle(float y)//function definition
{
float Area;
Area=pi*y*y;
printf(“The area is:%f”,Area);
}
This is where a function return a result.You pass data back from a receiving function to
its calling function. When you want to return a value from a function to its calling
function,put the return value after the return statement.
To make the return value clearer, many programmers put parentheses around the return
value, as shown in the following syntax:
return(return value);
Example 1
#include<stdio.h>
int main()
{
int x;
For(x=1;x<=10;x++)
{
printf(“%d”,square(x));
return 0;
}
int square(int y)
{
return y*y;
}
Example 2
/*Calculates the average of three input values*/
#include<stdio.h>
main()
{
int num1,num2,num3;
int avg;
printf(“Please type three numbers\n”);
scanf(“%d,%d,%d”,&num1,&num2,&num3);
avg=calcAv(num1,num2,num3);
printf(“\n\nThe average is %d,avg”);//print the return value
return 0;
}
int calcAv(int num1,int num2,int num3)
{
int localAvg;//Holds the average for three numbers
localAvg=(num1+num2+num3)/3;
return (localAvg);
}
Function prototypes
It tells the compiler the type of data returned by the function ,the number of parameters
the function expects to receive,the types of the parameters,and the order in which these
parameters are expected.
The compiler uses function prototype to validate function calls.
Example 1
#include<stdio.h>
int square(int y)//function prototype
int main()
{
it x;
For(x=1;x<=10;x++)
{
printf(“%d”,square(x));
return 0;
}
int square(int y)//function definition
{
return y*y;
}
Example 2
#include<stdio.h>
void main(void);
float convert(float cType);
void main(void)
{
float cTemp;
float fTemp;
printf(“What is the Celsius temperature to convert?”);
scanf(“%f”,&cTemp);
fTemp=convert(cTemp);
printf(“The Fahrenheit equivalent is %.lf”,fTemp);
return 0;
}
float convert(float cTemp)
{
float fTemp;
fTemp=cTemp*(9.0/5.0)+32;
return(fTemp);
}
NB:You should prototype every function in your program,even main().
Headers
The following program asks users for the weight.It then passes that weight to a function
that calculates the equivalent weight on the moon.
#include<stdio.h>
moon(int weight);
main()
{
int weight;
printf(“How many pounds do you weigh?”);
scanf(“%d”, &weight);
moon(weight);
return 0;
}
moon(int weight)
{
weight/=6;
printf(“You weigh only %d pounds on the moon!”,weight);
return 0;
}
When you pass an argument(local variable) by address,the variables address is sent to-
and is assigned to-the receiving function’s parameter.The caller allows the called
function to modify the original variable’s value.
To pass a non-array by address,you must do the following:
a. Precede the variable in the calling function with an ampersand(&)
b. Precede the variable in the receiving function with an asterisk(*),everywhere the
variable appears.
#include<stdio.h>
main()
{
int amt;
amt=100;
printf(“Amount is %d\n”,amt);
dofun(&amt);
printf(Amount is %d,amt);
return 0;
}
dofun(int*amt)
{
*amt=85;
printf(“Amount is %d”,*amt);
return 0;
}
Output
Amount is 100
Amount is 85
Amount is 85
C Pointers
Pointers enable programs to simulate call-by-reference,and to create and manipulate
dynamic data structures.i.e data structures that can grow and shrink at execution
time,such as linked lists,queues,stacks and trees.
Pointers are variables that contains addresses of other variables,they contain the
location of regular data variables;they in effect point to the data because they hold the
address of the data.
There are two pointer operators in C:
a. & The “address of” operator.
b. * The dereferencing operator
Declaring pointers
Some C programmers prefer to declare such a variable without space after the * as
follows:
int *age;
Example 1
#include<stdio.h>
main()
{
int num=123;
int *pNum;
printf(“num is %d\n”,num);
printf(“The address of num is %ld\n”,&num);
pNum=#
printf(“*pNum is %d\n”,*pNum);
printf(“pNum is %ld\n”,pNum);
return 0;
}
Output
num is 123
The address of num is 65522
*pNum is 123
pNum is 65522
Example 2
#include<stdio.h>
void swapThem(int *num1,int *num2);
void main(void);
void main(void)
{
int i=10,j=20;
printf(“\n\nBefore swap,i is %d and j is %d\n\n”,i,j);
swapThem(&i,&j);
printf(“\n\nAfter swap, i is %d and j is %d\n\n”,i,j);
return 0;
}
void swapThem(int *num1,int *num2)
{
int temp;
temp=*num1;
*num1=*num2;
*num2=temp;
return 0;
}
Recursion
This is a function that calls itself either directly or indirectly through another function.
Example 1
Example 2
/*Recursive Fibonacci function*/
#include<stdio.h>
long fibonacci(long n);
int main()
{
long result;
long number;
printf(“Enter an integer”);
scanf(“%ld”, &number);
result=fibonacci(number);
printf(“Fibonacci(%ld)=%ld\n”,number,result);
return 0;
}
long fibonacci(long n)
{
If(n==0 || n==1)
{
return n;
}
else
{
return fibonacci(n-1)+fibonacci(n-2);
}
}
Output
Enter an integer:10
Fibonacci(10)=55
C ARRAYS
An array is a group of memory locations related by the fact that they all have the same
name and the same type. To refer to a particular location or element in the array, we
specify the name of the array and the position number of the particular element in the
array.
The first element in every array is the zeroth element .Thus, the first element of array is
referred to as e.g marks[0] if the array name is marks.
The position number contained within square brackets is more formally called a
subscript. A subscript must be an integer or an integer expression.
Defining arrays
Syntax:
Array_type Array_name [Array_Size]
#include<stdio.h>
int main()
{
int marks[10];
int i;
printf("Please enter marks\n");
for(i=0;i<10;i++)//assigning values
{
scanf("%d", &marks[i]);
}
for(i=0;i<10;i++)//displaying values
{
printf("%d", marks[i]);
}
return 0;
}
Multiple-Subscripted Arrays
A common use of multiple-subscripted arrays is to represent tables of values consisting
of information arranged in rows and columns.To identify a particular table element,we
must specify two subscripts.The first (by convention)identifies the element’s row and
the second(by convention)identifies the elements column.
Tables or arrays that require two subscripts to identify a particular element are called
double-scripted arrays.
NB:Multiple-subscripted arrays can have more than two subscripts.
An array with m rows and n columns is called an m-by-n array.
Column
0 1 2 3
Row 0 a[0][0] a[0][1] a[0][2] a[0][3]
int b[2][2]={{1,2},{3,4}};
STRUCTURES
struct[structure tag]
{
Member definition;
Member definition;
.
.
Member definition;
}[one or more structure variables];
Example:
struct cdCollection
{
char title[25];
char artist[20];
int numSongs;
float price;
char dateBought[9];
} cd1, cd2, cd3;
Initializing structure data
#include<stdio.h>
#include<string.h>
Main()
{
Struct cdcollection
{
char title[25];
char artist[20];
int numSongs;
float price;
char dateBought[9];
} cd1;
return 0;
}
Output
Here is the CD information:
Title: red moon men
Artist: sam and the sneeds
Songs: 12
Price: 11.95
Date bought: 25/12/2010
Declaring arrays of structures
The following structure definition defines the inventory:
struct inventory
{
long int storage;
int accessTime;
char vendorCode;
double code;
double price ;
}drive[125] ;/*defines 125 occurences of the structure*/
Unions
It’s a derived data type-like a structure-with members that share the same storage space.
For different situations in a program, some variables may not be relevant, but other
variables are-so a union shares the space instead of wasting storage on variables that are
not being used.
The members of a union can be of any data type. The number of bytes used to store a
union must be at least enough to hold the largest member.
Only one member, and thus one data type, can be referenced at a time.
A union is declared with keyword union in the same format as a structure.
Union definition:
union number
{
int x;
double y;
};
Union definition is normally placed in a header and included in all source files that use
the union type.