Anda di halaman 1dari 163

Introduction To

Computer Programming

Programming
The act of a programmer writing code
or instructions (program) in a
programming language that instructs
a computer or other electronic device
how to operate or function.
Programming
is a term used to describe the process
of a programmer developing a
program.

Computer programming (often


shortened to programming or
coding)

is the process of designing, writing,


testing, debugging / troubleshooting,
and maintaining the source code of
computer programs. This source
code is written in a programming
language.

Computer programming
(often shortened to
programming or coding)
cntd

The purpose of programming is to


create a program that exhibits a certain
desired behavior (customization). The
process of writing source code often
requires expertise in many different
subjects, including knowledge of the
application domain, specialized
algorithms and formal logic.

Programming language
A programming language is a
computer language programmers
use to develop applications, scripts,
or other set of instructions for a
computer to execute.

Program
A program is a set of instructions for
performing a particular task.
Many program files on IBM
compatible computers commonly
end with a file extension of .BAT,
.EXE, .COM, or .PIF. Executing these
files will commonly open the
program.

Program cntd
A software application, or software
program, is the most commonly
found and run files on a computer. An
example of a software application is
Microsoft Word, which is a word
processor allowing users to create
and write documents. Without
programs, a user may have an
operating computer, but would not be
able to do much with it.

Programmer
An individual who enjoys or writes code,
or develops software for a living. Many
programmers who program for a
profession have a college degree in
computer science. While each job differs,
most programmers are responsible for
creating the software program or parts of
a program, debugging problems, and/or
adding onto a program.

Generation languages
The first generation languages, or 1GL
are low-level languages that are
machine language.
The second generation languages, or
2GL are also low-level languages that
generally consist of assembly
languages.
The third generation languages, or 3GL
are high-level languages such as C.

Generation languages
cntd
The fourth generation languages, or 4GL
are languages that consist of statements
similar to statements in a human language.
Fourth generation languages are commonly
used in database programming and scripts.
The fifth generation languages, or 5GL are
programming languages that contain visual
tools to help develop a program. A good
example of a fifth generation language is
Visual Basic.

Low-level language
Programming language that is more
arcane and difficult to understand.
Some good examples of low-level
languages are assembly and
machine languages

High-level language
A type of advanced computer
programming language that isn't
limited by the type of computer or
for one specific job and is more easily
understood. Today, there are dozens
of high-level languages; some
commonly used high-level languages
are BASIC, C, FORTAN and Pascal.

Machine language
Sometimes referred to as machine
code or object code, machine
language is a collection of binary
digits or bits that the computer
reads and interprets. Machine
language is the only language a
computer is capable of
understanding

Assembly language
Sometimes referred to as assembly or
ASL.
An assembly language is the low-level
programming language designed for a
specific processor.
Assembly language uses structured
commands as substitutions for
numbers allowing humans to read the
code more easily than looking at
binary.

Assembly language cntd


Although easier to read than binary,
the assembly language is still a
difficult language and often
substituted for a higher language
such as C.
mov
int

ax,4C00h
21h

Special purpose language


A programming language that was
designed for a specific function. For
example, LISP is an example of a
special purpose programming
language designed to create artificial
intelligence.

C
is general purpose programming
language.
C language was developed by
Dennis Ritchie at Bell
Laboratories in 1972.
It is an offspring of the Basic
combined programming
language called B developed in
1960 at Cambridge University.

C cntd
C runs under a number of operating
systems including MS.DOS. C programs are
efficient, fast and highly portable i.e C
programs written on one computer can be
run on another with little or no modification.
C language is a middle level computer
language.
C is not troublesome like assembly level
language. It combines the features of both
high level language and functionality like
assembly language. It reduces the gap
between high and low level languages.

ANSI C
A standard C version created by ANSI
(American National Standard Institute)
in 1990.
The purpose of this standard is to
enhance the portability and efficient
execution of C language programs on
different computers.
To Date most C compilers have been
designed following ANSI C standard.

Overview of Compilers and


Interpreters
A program can be written in
assembly language as well as high
level language. The written program
is called a source program. The
source program is to be converted
to machine language, which is
called an object program. Either an
Interpreter or Compiler will do this
activity.

Interpreters
An Interpreter reads only one line of
a source program at a time and
converts it into object codes. If an
error occurs, it will instantly be
indicated. The disadvantage of
interpreters is that it consumes
more time for converting a source
program to an object program.

Compilers
A compiler reads the entire program
and converts it to object code. It
provides errors not of one line but of
the entire program. Only error free
programs are executed. It consumes
little time for converting a source
program to object program. Compilers
are preferred when the program
length of an application is large.

Structure of a C Program
Every C program contains a number
of several building blocks known as
functions. Each function performs a
task independently. A function is a
subroutine that may consist of one or
more statements. A C program is
comprised of the following sections:

Structure of a C Program cntd


Include header file section
Global Declaration Section
/* Comments */
main() // Function name
{
/* comments */
Declaration part
Executable part
}
User-defined functions
{
}

Include header file


section
A header file is a file that contains
the declaration of functions and data
constants.
A C program depends upon some
header files for functions that are
used in a program.
Each header file by default is
extended with .h. The file should be
included using #include directive :

Include header file


section cntd
E.g #include<stdio.h> or #include
stdio.h
In this example <stdio.h> file is
included i.e all the definitions and
prototypes of functions defined in
this file are available in the current
program.
This file is also compiled with the
original program.

Global Declaration
This section declares variables that
are used in more than one function.
These variables are known as global
variables. These variables must be
declared outside of all the functions.

Function main()
Every program written in C language
must contain main() function. The empty
parenthesis after main are necessary.
The function main() is the starting point
of every C program. The execution of
the program always begins with the
function main(). Program execution starts
with the opening brace { and ends with
the closing brace }.

Declaration part
The declaration part declares the
entire variables that are used in the
executable part.
The initializations of variables are
also done in this section.
Initialization means providing an
initial value to the variables.

Executable part
This part contains the statements
following the declaration of variables.
This part can contain a set of
statements or a single statement.
These statements are enclosed
between braces.

User defined function


These are functions defined by the
user. These functions are generally
defined after the main() function.
Though they can also be defined
before the main function.

Comments
Comments are statements that help
programmers understand the flow of
programs. Comments are useful for
documentation. /* comments are
statements placed between
delimiters */
/* the compiler does not execute
comments. */

Introduction To C
Programming language
A Programming language should be able to
support certain kind of data, such as numbers,
characters, strings etc. to get useful output
known as information.
A program is a set of statements for a specific
task, which will be executed in a sequential
form.
These statements or instructions are formed
using certain words and symbols according to
the rules known as syntax rules or grammar
of the language.
Every program must follow accurately the
syntax rules supported by the language.

The C Character Set


Characters in C are classified in
the
following Categories:
1. Letters
2. Digits
3. White spaces
4. Special characters

Letters
Capital A to Z
Small a to z

Digits
All decimal digits 0 to 9

White Spaces
Blank spaces
New line

Special Characters
C/outline)

(See

Delimiters
Are special kind of symbols:
: Colon
Useful for label
; Semi colon
Terminates statements
( ) Parenthesis
used in expressions and
functions
[ ] Square brackets
for array declaration
{}
Curly Brace
Scope of statement
# HashPreprocessor Directive
, Comma Variable separator

The C Keywords
(c/outline)
The C keywords are reserved words
by the compiler.
All C keywords are assigned a fixed
meaning.
The keywords cannot be used as
variable names because they have
fixed jobs.

Identifiers
Are names of variables, functions,
and arrays.
They are user-defined names,
consisting of sequences of letters and
digits, with the letter as the first
character.
Constants: are identifiers whose
value does not change during program
execution.

Variable
Is a data name used for storing a data
value. or
Is defined as a location in the
computer memory which stores a data
type according to the declaration.
Also named an Identifier.
A variable is just a named area of
storage that can hold a single value
(numeric or character).

Variable cntd
A variable is a data object that may
change in value.
A variable can be assigned different values
at different times during the execution of a
program.
It is given a name by means of a definition
and declaration which allocates the
storage space for the data and associates
the storage location with the variable
name.

C demands that you declare the name


of each variable/identifier that you are
going to use and its type, or class,
before you actually try to do anything
with it. (Declaration first before use.)
Declaring a variable tells the compiler
the type and the name of the
variable.
A variable name may be declared
based on the meaning of the
operation. Examples of meaningful
names:
Height, average, sum etc.

There are five basic data types:


int: integer, whole Number.
Range: -32,768 to 32,767
float: floating point value, I.e. No with
fractional part.
Range: 3.4e -38 to 3.4e +38
double: a double-precision floating point
No. (No with a larger fractional part)
Range: 1.7e -308 to 1.7e +308
Char: a single character enclosed within a
pair of single qoute marks. E.g. a, 8,
, &
Range: -128 to 127
void: valueless special purpose type.

Syntax for Variable


Declaration

Data_Type Variable_Name;
int mark1;
float sum, ave;
double answer;
char yr_initial;
State its type and give it a name.
Int = =2 bytes,
float = =4 bytes,
double = =8 bytes,
char = =1
byte.

Rules for Variable


Formulation
1. No variable must be the same as one
of the keywords.
2. Identifiers or variable names must
start with a letter or the underscore,
without spaces.
3. Variable names can be alphanumeric.
Identifiers are case sensitive such
that A and a are viewed differently in
C.

Rules for Variable


Formulation cntd
4. The variable name should not start
with a digit.
5. A variable name can be 8
characters excluding the extension,
however the ANSI standard
recognizes the maximum length of
a variable up to 31 characters long.

Constatnts
Constants: are identifiers whose
value does not change during
program execution.

Constatnts cntd
C constants

Numeric Constants

Integer Constants
Real Constants

Character Constants

Single Character constants


String Constants

Integer Constants
These are the sequence of numbers
from 0 to 9 without decimal points or
fractional part or any other symbols.
Requires a min of 2 bytes and a max
of 4 bytes.
Integer Constants can either be
positive or negative.
E.g. 10, 20, +30, -15

Real Constants
Real constants are often known as
floating point constants.
E.g. 2.5, 5.521, 3.14
Real constants can be written in
exponential notation, which contains a
fraction part and an exponential part.
E.g. 2456.123 can be written as
2.4561Xe+3

Real Constants cntd


The general format of the real number
contains mantissa and an exponent.
The mantissa is either a real number
represented in decimal or an integer.
The exponent is an integer number
which may be positive or negative.
The letter e separating the mantissa
and exponent can be written in lower
or upper case.

Single Character
Constants
A character constant is a single
character.
Represented with a single digit or a
single special symbol or white space
enclosed within a pair of single quote
marks.
E.g. a, 7, , $,

String Constants
Are sequences of characters
enclosed within a double quote
marks.
The string may be a combination of
all kinds of symbols.
E.g. Hello, India, 444, a

Declaring Constants
By adding the keyword const before
the declaration. E.g. const int m=10;
The compiler protects the value of
m from modification. The user
cannot assign any value to m.
#define N 10
#define a 15
Where N and a are user-defined
identifiers.

Assignment Statement
Once declared a variable has to be
defined.
An assignment statement stores
values ( of expressions, or other
variables) into variables.
C uses the = assignment
operator for assignment. (storing
values into variables)

Initialising Variables
Providing an initial value into a variable.
Variables declared can be assigned or
initialised using an = assignment
operator.
The declaration and initialisation can
also be done in the same line.
Syntax:
variable_name=constant;
Or data_type Variable_name=constant;

Initialising Variables cntd


You initialise a variable by using the
assignment statement: int a, b;
a=0; b=2;
a takes the initial value of zero and b
takes the initial value of two.

Statements and
Expressions
Having defined variables of different
types as part of your program, one
will need to combine the variables to
make them useful in Expressions.
A simple Statement is an expression
Terminated by a semi-colon (;).
E.g. a=3;
(complete
statement)

Statements and
Expressions cntd
One can assign an expression to a
variable:
E.g.
Sum = a+b;

Arithmetic Expressions
C Operators- Arithmetic
Ther are two types: Binary and Unary
1. Binary Operators
+
a+b addition
- a-b subtraction
* a*b multiplication
/ a/b division
%
a%bmodular remainder division

C Operators- Arithmetic
2.

Unary Operators
Minus
++
increment
-Decrement
&
Address Operator
Size of
Gives the size of a variable
Minus (-): Unary minus is used to indicate
or change the algebraic sign of a value.

Increment and
Decrement Operators
++
- E.g.

Increases a value by One


Decreases a value by One
num++;
num--;

Equivalent to:

num = num+1;
num = num-1;

Increment and Decrement


Operators cntd
Both these operators may either follow
or precede the operand. E.g. ++x; or
x++;
If ++ or - - are used as a suffix to the
variables name then the post
increased/ decreased operations take
place.
E.g. x=20; y=10;
then
z=x*y++; results in 200.

Increment and Decrement


Operators cntd
If ++ or - - are used as a preffix to
the variables name then the pre
increased/ decrement operations
take place.
E.g. x=20; y=10;
then
z=x*++y;
results in 220.

Arithmetic Ordering:
a=10.0 + (2.0 * 5.0) - (6.0 / 2.0)
a=(10.0 + 2.0) * (5.0 - 6.0) / 2.0

Sizeof()
The sizeof() operator gives the bytes
occupied by a variable. The number
of bytes occupied varies from
variable to variable depending on its
data types.
E.g. int x=2; float y=2;
printf(%d : %d,sizeof(x), sizeof(y));
Ans:
2 : 4

& Address of
The & address of operator prints
address of the variable in the memory.
E.g. int x=2; float y=2;
printf(%d : %d,sizeof(x), sizeof(y));
printf(%u : %u, &x, &y);
Ans:2 : 4

4066

: 25096

Relational Operators

> greater than


>= greater than or equal to
< less than
<=
less than or equal to
==
equal to
!= not equal to

Relational Operators cntd


These Operators are used to
distinguish between two values
depending on their relations.
If the relation is true then it returns
a value 1 otherwise 0 for false
relation.

Logical Operators

&&

AND
T AND T = T
T AND F = F

||

OR

NOT

T OR T = T and
T OR F = T,
F OR F = F

Input and Output (I/O)


A C program uses standard Input and
Output to read its input from the
keyboard and to write its output to
the screen.
Such input and output consists of
streams which are simply sequences
of characters that either come from
or go to an input or output device.

The data type for an input stream is


stdi, while that of an output stream
is stdo.
These are all supplied by the library
called stdio.
A C program gains access to this
library and other libraries by
including them as header files.
A header file is a file that contains
the declaration of functions and
data constants.

printf() and scanf()


Functions
These functions use the standard
input and output to read input from
the keyboard and to write output to
the screen.

Input and Output Functions


Input and Output Functions
1.input functions, called scanf ()

2.output functions, called printf ()


printf("The value stored in a is %d",a );
The printf (and scanf) functions do differ
from the sort of functions that you will
create for yourself in that they can take a
variable number of parameters. In the case
of printf the first parameter is always a
string (c.f. "Hello World") but after that
you can include as many parameters of any
type that you want to. That is, the printf
function is usually of the form

Format Specifiers

FS
Type
display
%c
charsingle character
%d
[%i] int signed integer
%e[%E]
float/double exponential
formt
%f float/double
%s
array of characters
sequence
(a string)

flag
flag width.precision
The flag can be any of:
flag
meaning

left justify

+
always display sign

space
display space if there is no sign

0
pad with leading zeros

#
use alternate form of specifier

control codes

Finally there are the control codes:


\b
backspace
\f
formfeed
\n
new line
\r
carriage return
\t
horizontal tab
\'
single quote
\0
null

Scanf()
scanf(control
string,variable,variable,...)
scanf("%d %d",&i,&j);
In this case the control string specifies
how strings of characters, usually typed
on the keyboard, should be converted
into values and stored in the listed
variables. However there are a number
of important differences as well as
similarities between scanf and printf.

Syntax
When referring to a programming
language or command, syntax is a set of
rules that are associated with the
language or command.
When referring to an error, a syntax error
is an error that is encountered when the
programmer or individual who wrote the
code has not followed the rules of the
language, causing the program to fail.

write a program that adds two


numbers together and prints the
result.
#include <stdio.h>
main()
{
int a,b,c;
printf("\nEnter the first number :");
scanf("%d",&a);
printf(\nEnter second number :");
scanf("%d",&b);
c=a+b;
printf("The answer is %d \n",c);
}

Execute
A term used to describe the process
of running a computer software
program or command. For example,
each time you open your Internet
browser you're executing the
program

Executable file
An executable file is a file that is used to
perform various functions or operations
on a computer. Unlike a data file, an
executable file cannot generally be read
because it has been compiled. On an IBM
compatible computer, common
executable files are .BAT, .COM, .EXE, and
.BIN. Depending on the operating system
and its setup, there can also be several
other types of executable files

Compile
The process of creating an
executable program from code
written in a compiled programming
language that allows the computer to
run the program without the need of
the programming software used to
create it. es.

Compile
When a program is compiled it is
often compiled for a specific platform
such as an IBM platform, which would
work with any IBM compatible
computers but not other platforms
such as the Apple Macintosh platform.
Below are some examples of
compiled programming language:
C, C++, C#, D, Pascal

Control Loops
Objectives:
Having read this section you should
have an idea about C's:
1.Conditional, or Logical, Expressions
as used
in program control
2.the do while loop
3.the while loop
4.the for loop

Conditions or Logical
Expressions:
The only detail we need to clear up is what

the condition (or Logical Expression) can be.


How, for example, do we display 100 or
10,000 "Hello World!" messages? The
condition can be any test of one value
against another. For example:
a>0
is true if a contains a value greater than
zero;
b<0
is true if b contains a value less than zero.

Conditions or Logical
Expressions
The only complication is that the test
for 'something equals something
else' uses the character sequence
== and not =. That's right: a test for
equality uses two equal-signs, as in
a==0, while
an assignment, as in a=0, uses one.

if
The if statement evaluates an
expression. If that expression is true,
then a statement is executed. If an
else clause is given and if the
expression is false, then the else's
statement is executed.

if
Syntax:
if( expression ) statement1;
or
if( expression ) statement1;
else statement2 ;

Examples:
if(loop<3) counter++;
if(x==y) x++;
else y++;
if(z>x) {z=5; x=3; }
else { z=3; x=5; }

switch
A switch statement allows a single
variable to be compared with several
possible constants. If the variable
matches one of the constants, then a
execution jump is made to that point.
A constant can not appear more than
once, and there can only be one
default expression.

Syntax:
switch ( variable )
{
case const:
statements...;
default:
statements...;
}

Examples:
switch(betty)
{
case 1: printf("betty=1\n");
case 2: printf("betty=2\n"); break;
case 3: printf("betty=3\n"); break;
default: printf("Not sure.\n");
}

Examples:
If betty is 1, then two lines are
printed: betty==1 and betty==2. If
betty is 2, then only one line is
printed: betty==2. If betty==3, then
only one line is printed: betty==3. If
betty does not equal 1, 2, or 3, then
"Not sure." is printed.

while
The while statement provides an
iterative loop.
Syntax:
while( expression ) statement...
statement is executed repeatedly as
long as expression is true. The test
on expression takes place before
each execution of statement.

The expression/condition is just a test


to control how long you want the
compound statement to carry on
repeating.
In the case of the while loop before the
compound statement is carried out the
condition is checked, and if it is true
the statement is obeyed one more
time. If the condition turns out to be
false, the looping isn't obeyed and the
program moves on to the next statement.
So you can see that the instruction really
means while something or other is true
keep on doing the statement.

Examples:
while(*pointer!='j') pointer++;
while(counter<5)
{
printf("counter=%i",counter);
counter++;
}

while
Each line of a C program up to the
semicolon is called a statement. The
semicolon is the statement's
terminator. The braces { and }
which have appeared at the beginning
and end of our program unit can also
be used to group together related
declarations and statements into a
compound statement or a block.

while Examples:
#include <stdio.h>
main()
{

while (1 == 1) printf("Hello
World!\n");
}

dowhile
The do...while construct provides an
iterative loop.
Syntax:
do statement... while( expression );
statement is executed repeatedly as
long as expression is true. The test
on expression takes place after each
execution of statement.

dowhile
In the case of the do while loop it will
always execute the code within the
loop at least once, since the condition
controlling the loop is tested at the
bottom of the loop.
The do while loop repeats the instruction
while the condition is true. If the
condition turns out to be false, the looping
isn't obeyed and the program moves on to
the next statement.

Examples:
do {
betty++;
printf("%i",betty);
} while (betty<100);

#include <stdio.h>
main()
{
do
{
printf("Hello World!\n");
}while (1 == 1);
}

for
This sort of loop - runs from a
starting value to a finishing value
going up by one each time.
The for statement allows for a
controlled loop.
The counter does not have to be
incremented or (deremented) by 1;
we can use any value.

Syntax:
for( expression1 ; expression2 ;
expression3 ) statement... ;
OR
for ( counter=start_value; counter
<=
finish_value; ++counter )
compound statement;

expression1 is evaluated before the first


iteration. After each iteration,
expression3 is evaluated. Both
expression1 and expression3 may be
ommited. If expression2 is ommited, it is
assumed to be 1. statement is executed
repeatedly until the value of expression2
is 0. The test on expression2 occurs
before each execution of statement.

Examples:
for(loop=0;loop<1000;loop++)
printf("%i\n",loop);
Prints numbers 0 through 999.
for(x=3, y=5; x<100+y; x++, y--)
{
printf("%i\n",x);
some_function();
}
Prints numbers 3 through 53.
some_function is called 51 times.

break
The break statement can only appear
in a switch body or a loop body. It
causes the execution of the current
enclosing switch or loop body to
terminate.
Syntax:
break;

Examples:
switch(henry)
{
case 1: print("Hi!\n");
break;
case 2: break;
}
If henry is equal to 2, nothing happens.

for(loop=0;loop<50;loop++)
{
if(loop==10)
break;
printf("%i\n",loop);
}
Only numbers 0 through 9 are
printed.

continue
The continue statement can only
appear in a loop body. It causes the
rest of the statement body in the
loop to be skipped.
Syntax:
continue;

continue Examples:
for(loop=0;loop<100;loop++)
{
if(loop==50)
continue;
printf("%i\n",loop);
}
The numbers 0 through 99 are
printed except for 50.

joe=0;
while(joe<1000) {
for(zip=0;zip<100;zip++) {
if(joe==500)
continue;
printf("%i\n",joe);
}
joe++;
}
Each number from 0 to 999 is printed
100 times except for the number 500
which is not printed at all.

goto
The goto statement transfers
program execution to some label
within the program.
Syntax:
goto label;
....
label:

goto Examples:
goto skip_point;
printf("This part was
skipped.\n"); skip_point:
printf("Hi there!\n");
Only the text "Hi there!" is printed.

return
The return statement causes the
current function to terminate. It can
return a value to the calling function.
A return statement can not appear in
a function whose return type is void.
If the value returned has a type
different from that of the function's
return type, then the value is
converted.

return statement without


an expression
Using the return statement without
an expression creates an undefined
result. Reaching the } at the end of
the function is the same as returning
without an expression.
Syntax:
return expression;

return Examples:
int alice(int x, int y)
{
if(x<y)
return(1);
else
return(0);
}

Functions
Every program in C has at least one
function which is main(). Unlike Pascal or
Basic, C does not provide procedures, it
uses functions to cater to both
requirements.
Functions are used to make a program
modular and to avoid repetition of
code. Any piece of code which is often
used in a program is a likely candidate for
being a function.

Syntax
In C a function has the following
structure :
<return type> function_name
(arguments list)
{
local variables;
code performing the necessary action;
}

#include <stdio.h>
void print_message()
{
printf("Inside print_message
function\n");
}
void main()
{
print_message(); // function call
printf("Back in the main program\n");
}

function call
In the above program, main() is the
entry point of the program, once
program execution begins, the control is
transferred to the print_message()
function. Inside the function it prints the
statement on the terminal and the
control returns to the main routine. After
the function call the program execution
will continue at the point where the
function call was executed.

The printf() and scanf() routines are


functions too. But since these are part of
the C standard library, one has to just
make a call to them. Whenever we use a
printf() routine, execution is transferred
to the printf() function which performs
the required task, then control is
returned back to the calling program.
If you do not want to return a value you
must use the return type void, and the
return statement must not be present in
the body of the called function.

return type
Note : If the return type of a function
is omitted, then the C compiler
assumes that the function will return
an integer. In case a function is
returning an integer value, it is a
good programming practise to
declare the return type instead
of omitting it. This improves the
readability of a program.

When a function is declared the number


of arguments passed to the function
and their names must also be
indicated. The name chosen for an
argument is called its formal parameter
name. Formal parameters must be
declared inside a function before they are
used in the function body.
<return type> function_name (arguments
list)

automatic variables
One point to remember is that
variables defined inside a function are
known as automatic variables since
they are automatically created each
time the function is called and are
destroyed once the function is
executed. Their values are local to the
function, they can be accessed only
inside the function in which they are
defined and not by other functions.

#include <stdio.h>
int square(number);
main()
{
int i; int result; i = 10; result = square(i);
printf ("Square of %d is %d\n", i, result);
}
int square(n) int n;
{
int temp; temp = n*n; return temp;
}

returning a value
When functions return a value to the
calling routine, a return() statement
needs to be used in the called
function. Also when the function is
declared we must declare the return
type. In the above program the value
returned by the function square is
stored in the variable result in the
calling program.

function call
One can call a function from
anywhere within a program. The
best use of functions is to organize a
program into distinct parts. The
function main() can only contain
calls to the various functions. The
actual work of the program is
performed in the functions following
main().

Function prototype
In C the function prototype has to be
declared before a function is used. A
function prototype is information to
the C compiler about the return
type of a function and the
parameter types that a function
expects. Usually all function prototypes
are declared at the start of a program.
Example:

int Min(int a, int b);

Scope of Function
variables
variables defined inside a function
are known as automatic variables.
Their values are local to the
function, they can be accessed only
inside the function in which they are
defined and not by other
functions.

Local variables
Local variables are local to a
function. They are created everytime
a function is called and destroyed on
return from that function. These
variables cannot be accessed
outside a function.

Global variables
Global variables are declared outside
all functions. The value stored in
global variables is available to all
functions within a
program/application.

Static variables
Static variables are declared by
prefixing the keyword static to a
variable declaration. Unlike local
variables these are not destroyed on
return from a function, they continue
to exist and retain their value. These
variables can be accessed upon reentering a function.

Recursive functions
Recursive functions are functions calling
themselves repeatedly until a certain
condition is met. Recursion involves two
conditions. First the problem must be
written in a recursive form, and second,
the problem should have a loop
terminating statement. If the loop
terminating is missing, then the function
goes into an endless loop.
A most common example of a program
demonstrating recursion is calculation of
factorial of an interger number.

#include <stdio.h>
long int factorial(int n); /* function
prototype */
main () {
int num;
printf("Enter an integer value : ");
scanf("%d", &num);
printf("factorial of %d is %ld\n", num,
factorial(num)); } //end of main()
long int factorial(int n) {
if (n &lt;= 1) return(1);
else return(n * factorial(n-1)); }

In this tutorial you will learn about C


Programming - Arrays - Declaration
of arrays, Initialization of arrays,
Multi dimensional Arrays, Elements
of multi dimension arrays and
Initialization of multidimensional
arrays.

Declaration of arrays:
Like any other variable arrays must be
declared before they are used. The
general form of declaration is:
type variable-name[50];
The type specifies the type of the
elements that will be contained in the
array, such as int float or char and the
size indicates the maximum number of
elements that can be stored inside the
array for ex:
float height[50];

Declares the height to be an array


containing 50 real elements. Any
subscripts 0 to 49 are valid. In C the
array elements index or subscript begins
with number zero. So height [0] refers to
the first element of the array. (For this
reason, it is easier to think of it as
referring to element number zero, rather
than as referring to the first element).

grades [100]=95;
for(i=0;i < 100;++i);
sum = sum + grades [i];
Will sequence through the first 100
elements of the array grades (elements
0 to 99) and will add the values of each
grade into sum. When the for loop is
finished, the variable sum will then
contain the total of first 100 values of
the grades array (Assuming sum were
set to zero before the loop was entered)

Initialisation of arrays
The initialisation of simple variables in
their declaration has already been
covered. An array can be initialised in a
similar manner. In this case the initial
values are given as a list enclosed in
curly brackets. For example initialising
an array to hold the first few prime
numbers could be written as follows:
int primes[] = {1, 2, 3, 5, 7, 11, 13};

Note that the array has not been given a


size, the compiler will make it large
enough to hold the number of elements
in the list. In this case primes would be
allocated space for seven elements. If
the array is given a size then this size
must be greater than or equal to the
number of elements in the initialisation
list. For example:
int primes[10] = {1, 2, 3, 5, 7};
would reserve space for a ten element
array but would only initialise the first
five elements.

Initialization of arrays:
We can initialize the elements in the
array in the same way as the ordinary
variables when they are declared. The
general form of initialization off arrays is:
type array_name[size]={list of
values};
The values in the list care separated by
commas, for example the statement
int number[3]={0,0,0};

Will declare the array size as a array of


size 3 and will assign zero to each
element if the number of values in the
list is less than the number of elements,
then only that many elements are
initialized. The remaining elements will
be set to zero automatically.
In the declaration of an array the size
may be omitted, in such cases the
compiler allocates enough space for all
initialized elements. For example the
statement

Strings
A string is an array of characters.
Strings must have a 0 or null character
after the last character to show where
the string ends. The null character is
not included in the string.
There are 2 ways of using strings. The
first is with a character array and the
second is with a string pointer.
A character array is declared in the
same way as a normal array.
char ca[10];

You must set the value of each


individual element of the array to the
character you want and you must
make the last character a 0.
Remember to use %s when printing
the string.
char ca[10];
ca[0] = 'H';
ca[1] = 'e';
ca[2] = 'l';
ca[3] = 'l';
ca[4] = 'o';
ca[5] = 0;
printf("%s",ca);

String pointers
String pointers are declared as a
pointer to a char.
char *sp;
When you assign a value to the string
pointer it will automatically put the 0
in for you unlike character arrays.
char *sp;
sp = "Hello";
printf("%s",sp);

You can read a string into only a


character array using scanf and not a
string pointer. If you want to read into
a string pointer then you must make
it point to a character array.
char ca[10],*sp;
scanf("%s",ca);
sp = ca;
scanf("%s",sp);

Multi dimensional
Arrays:

Often there is a need to store and


manipulate two dimensional data structure
such as matrices & tables. Here the array
has two subscripts. One subscript denotes
the row & the other the column.
The declaration of two dimension arrays is
as follows:
data_type array_name[row_size]
[column_size];
int m[10][20]

Here m is declared as a matrix


having 10 rows( numbered from 0 to
9) and 20 columns(numbered 0
through 19). The first element of the
matrix is m[0][0] and the last row
last column is m[9][19]

Elements of multi
dimension
arrays:
A 2 dimensional array marks [4][3] is

shown below figure. The first element is


given by marks [0][0] contains 35.5 &
second element is marks [0][1] and
contains 40.5 and so on.
marks [0][0] 35.5 Marks [0][1] 40.5
Marks [0][2]45.5 marks [1][0] 50.5
Marks [1][1] 55.5 Marks [1][2] 60.5
marks [2][0] Marks [2][1]
Marks [2][2]marks [3][0]
Marks [3][1] Marks [3][2]

Initialization of
multidimensional arrays:
Like the one dimension arrays, 2
dimension arrays may be initialized by
following their declaration with a list of
initial values enclosed in braces
Example:
int table[2][3]={0,0,01,1,1};
Initializes the elements of first row to
zero and second row to 1. The
initialization is done row by row. The
above statement can be equivalently
written as :
int table[2][3]={{0,0,0},{1,1,1}}

1. Write a program to read five values into


an array and print them out in reverse
order (Use two independent for loops).
2.What is meant by an array?
3.How do you declare an array?
4.What do you mean by an index of an
array?
5.How many elements are there in the
following array : int arr[10]?
6.Why do you need to specify the size of
an array?

. Structures
We already know that arrays are many
variables of the same type grouped together
under the same name. Structures are like
arrays except that they allow many
variables of different types grouped together
under the same name. For example you can
create a structure called person which is
made up of a string for the name and an
integer for the age. Here is how you would
create that person structure in C:

Here is how you would create that


person structure in C:
struct person
{
char *name;
int age;
};
The above is just a declaration of a
type. You must still create a variable
of that type to be able to use it

Here is how you create a variable


called p of the type person:
#include<stdio.h>
struct person
{
char *name;
int age;
};
int main()
{
struct person p;
return 0;
}

To access the string or integer of the


structure you must use a dot
between the structure name and the
variable name.

#include<stdio.h>
struct person
{
char *name;
int age;
};
int main()
{struct person p;
p.name = "John Smith";
p.age = 25;
printf("%s",p.name);
printf("%d",p.age);
return 0;
}

Type definitions

You can give your own name to a


variable using a type definition. Here
is an example of how to create a type
definition called intptr for a pointer to
an integer.
#include<stdio.h>
typedef int *intptr;
int main()
{
intptr ip;
return 0;
}

Type definitions for a


structure
If you don't like to use the word
struct when declaring a structure
variable then you can create a type
definition for the structure. The name
of the type definition of a structure is
usually all in uppercase letters.

#include<stdio.h>
typedef struct person
{
char *name;
int age;
} PERSON;
int main()
{PERSON p;
p.name = "John Smith";
p.age = 25;
printf("%s",p.name);
printf("%d",p.age);
return 0;
}

Anda mungkin juga menyukai