You are on page 1of 85

UNIT -3

Arrays, functions & pointers


ARRAYS
🞆 There are times when you will want to store a list
of values, e.g. the number of inches of snow each
day during a one-week period, or letter grades for
each of your classes.
🞆 While you could declare a variable for each value,
it is much more convenient to use an array in
these cases.
ARRAYS
🞆 Arrays fall under aggregate data type
🞆 What is an array?
⚫Arrays are collection of data that belong to same data
type
⚫Arrays are collection of homogeneous data
ARRAYS - DECLARATION
🞆 As with all variables, an array needs to be
declared. The syntax for declaring an array
⚫datatype arrayname[size]
🞆 In the declaration, the value in the brackets must
be a constant (either a literal, as in the code
above, or a #define value).
🞆 Note that as with other variables, declaring an
array does not initialize its values. Your code will
need to set a value for each item in the array.
ARRAYS - ACCESSING
🞆 To access an item in the array (to set or read it),
use the variable name followed by brackets
containing the index of the desired item.
⚫int student_height[5];
⚫student_height[3];

🞆 Note that index values start at 0, not 1. This


means that if there are n items in an array, the
valid index values are from 0 (the first item) to n-
1 (the last item).
🞆 Note that you need to set each item individually.
ARRAY - EXAMPLE
#include <stdio.h>
void main()
{ int list[3];
list[0] = 5; list[1] = -2; list[2] = 23;
printf("The first item in the array is %d\n", list[0]);
printf("The last item in the array is %d\n", list[2]);
return 0;
}
ARRAY INITIALIZATION
🞆 int a[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
🞆 When an array definition includes an initializer,
the array dimension may be omitted, and the
compiler will infer the dimension from the
number of initializers. For example, int b[] = {10,
11, 12, 13, 14};
🞆 If there are fewer initializers than elements in
the array, the remaining elements are
automatically initialized to 0. For example, int
a[10] = {0, 1, 2, 3, 4, 5, 6}; would initialize a[7],
a[8], and a[9] to 0
ARRAY INITIALIZATION
🞆 Further examples
⚫char name[]={‘j’, ’o’, ’h’, ’n’, ’\0’};
⚫float total[5]={1.2, 3.0, -12.5, 0.09, 0.0}
TYPES OF ARRAY
🞆 One dimensional
⚫List of items can be given one variable name using
only one subscript is called 1D array
🞆 Two dimensional
TWO – DIMENSIONAL ARRAY
🞆 A 2D array in C is treated as a 1D array whose
elements are 1D arrays (the rows).

🞆 Format
⚫datatype arrayname[rowsize][colsize]

🞆 int mat[4][3] and described by the following


scheme:
TWO – DIMENSIONAL ARRAY
TWO DIMENSIONAL ARRAYS
🞆 How to interpret a declaration like:
int d[2][4];
🞆 This is an array with two elements:
⚫Each element is an array of four int values
🞆 The elements are laid out sequentially in memory, just
like a one-dimensional array
⚫Row-major order: the elements of the rightmost subscript
are stored contiguously

(int) (int) (int) (int) (int) (int) (int) (int)

d[0][0] d[0][1] d[0][2] d[0][3] d[1][0] d[1][1] d[1][2] d[1][3]

d[0] d[1]
ACCESSING 2D ARRAY
🞆 Access individual elements using two pairs of
brackets:
🞆 int a[5][7];
🞆 int i, j;
🞆 for(i = 0; i < 5; i++)
🞆 {
🞆 for(j = 0; j < 7; j++)
🞆 a[i][j] = 0;
🞆 }
USING INDEX/SUBSCRIPT
🞆 Make sure that you remember to put each
subscript in its own, correct pair of brackets.
Neither
🞆 int a2[5, 7]; /* XXX WRONG */ nor
🞆 a2[i, j] = 0; /* XXX WRONG */ nor
🞆 int a[5][7]; - correct
🞆 a[i][j]=0; - correct
2D ARRAY INITIALIZATION
🞆 int y[3][4] = { {1, 2, 3},
{4, 5, 6},
{7, 8, 9} };

y[0][0]= 1 y[0][1]= 2 y[0][2]= 3 y[0][3]= 0

y[1][0]= 4 y[1][1]= 5 y[1][2]= 6 y[1][3]= 0

y[2][0]= 7 y[2][1]= 8 y[2][2]= 9 y[2][3]= 0


DYNAMIC ARRAYS
🞆 Array created at compile time by specifying the
size in source code & cannot be modified at
runtime
🞆 The process of allocating memory at compile
time known as static memory allocation and
array the receive static memory allocation is
called static array
🞆 This works fine as long as we know the data
requirement
DYNAMIC ARRAYS
🞆 But in certain situation array size can vary
greatly . We must guess what will the largest size
ever needed & create array
🞆 C don’t have this limitation. It is possible to
allocate memory to arrays at run time. It is
known as dynamic allocation of memory
🞆 array created at run time is called dynamic
array
⚫They are created using pointers & memory mgt
functions (which we study later in this capter)
STRINGS – CHARACTER ARRAYS
🞆 Strings in C are represented by arrays of
characters.
🞆 The end of the string is marked with a special
character, the null character, which is simply the
character with the value 0.
🞆 The null or string-terminating character is
represented by another character escape
sequence, \0
COMMON OPERATIONS - STRINGS
🞆 Read/write
🞆 Combine the strings
🞆 Copy
🞆 Compare
🞆 Extract a portion of it
🞆 There are library functions defined in string.h to
implement these function
STRING DECLARATION,
INITIALIZATION
🞆 Declaration
⚫char arrayname[size]
🞆 In the case of arrays of char, the initializer may
be a string constant:
⚫char s1[7] = "Hello,";
⚫char s2[10] = "there,";
⚫char s3[] = "world!";
⚫char name1[ ] = { 'J', 'a', 'n' ,’\0’};
READING STRINGS

🞆 char name[20];

🞆 scanf(“%s”, name); here & is not required


🞆 Scanf function automatically terminates string
with null so character array should be large
enough to hold the null (size+1)
🞆 Scanf -- reads without whitespaces (ie) if you
input ram krishna for name only ram will be
taken
READING LINE OF TEXT -
STRINGS

🞆 Using getchar() & gets() function


main()
{
char line[81], c;
int i=0;
do
{
c=getchar(); postfix ++

line[i++]=c;
}while(c!=‘\n’);
c-- ;
line[c]=‘\0’;
}
READING LINE OF TEXT -
STRINGS

🞆 Using getchar() & gets() function


main()
{
char line[81], c;
int i=0;
gets(line);
}

It reads character into line from keyboard


until newline is encountered. It does not
skip whitespaces
WRITING STRINGS

🞆 Printf(“%s”, “welcome”):
🞆 Using putchar() & puts() function
main()
{
char line[81] = “welcome to c”;
int i=0;
for(i=0; line[i]!=‘\0’; i++)
{
putchar[line[i]];
}
puts(line);
}
It writes string to screen
STRINGS - STRCPY
🞆 To do anything else with strings, we must
typically call functions. The C library contains a
few basic string manipulation functions
🞆 Since C never lets us assign entire arrays, we use
the strcpy function to copy one string to another:
#include <string.h>
char string1[] = "Hello, world!";
char string2[20];
strcpy(string2, string1);
STRING FUNCTIONS
🞆 Strcat
🞆 Strlen
🞆 Strcmp
🞆 Stricmp
🞆 strcpy
FUNCTIONS
🞆 A function is a block of code that performs a
specific task. It has a name and it is reusable i.e.
it can be executed from as many different parts
in a C Program as required. It also optionally
returns a value to the calling program
🞆 function in a C program has some properties
⚫Every function has a unique name. This name is
used to call function from “main()” function. A
function can be called from within another function.
⚫A function is independent and it can perform its task
without intervention from or interfering with other
parts of the program.
FUNCTIONS
🞆 function in a C program has some properties
⚫A function returns a value to the calling program.
This is optional and depends upon the task your
function is going to accomplish. Suppose you want to
just show few lines through function then it is not
necessary to return a value. But if you are calculating
area of rectangle and wanted to use result
somewhere in program then you have to send back
(return) value to the calling function.
🞆 C language is collection of various inbuilt
functions. Printf, scanf, clrscr etc. all are C’s
inbuilt functions. You cannot imagine a C
program without function.
FUNCTIONS
🞆 Functions must have a
⚫ definition
and
⚫ should have a declaration
🞆 definition can serve as a declaration if the declaration
appears before the function is called.
🞆 The function definition includes the function body —
the code that executes when the function is called.
🞆 A function declaration establishes the name, return
type, and attributes of a function that is defined
elsewhere in the program.
🞆 A function declaration must precede the call to the
function. This is why the header files containing the
declarations for the run-time functions are included
in your code before a call to a run-time function.
FUNCTIONS
🞆 A function call passes execution control from the
calling function to the called function.
🞆 The arguments, if any, are passed by value to
the called function. Execution of a return
statement in the called function returns control
and possibly a value to the calling function.
STRUCTURE OF A FUNCTION
🞆 A general form of a C function looks like this:
🞆
<return type> FunctionName (Argument1, Argument2,
Argument3……)
{
Statement1;
Statement2;
}
An example of function.
int sum (int x, int y)
{
int result;
result = x + y;
return (result);
}
TYPES OF FUNCTIONS:
🞆 A function may belong to any one of the following
categories:
⚫Functions with no arguments and no return values.
⚫Functions with arguments and no return values.
⚫Functions with arguments and return values.
⚫Functions with no arguments and return values.
EXAMPLE
#include<stdio.h>
#include<conio.h>
void add(int x,int y)
{
int result;
result = x+y;
printf("Sum of %d and %d is %d.\n\n",x,y,result);
}
void main()
{
clrscr();
add(10,15);
add(55,64);
add(168,325);
getch();
}
ADVANTAGES OF USING
FUNCTIONS:
🞆 We can divide c program in smaller modules.
🞆 We can call module whenever required. e.g
suppose we have written calculator program then
we can write 4 modules (i.e
add,sub,multiply,divide)
🞆 Modular programming makes C program more
readable. Easy to understand & modify
🞆 Modules once created , can be re-used in other
programs.
STORAGE CLASS
🞆 A storage class defines the scope (visibility) and
life time of variables and/or functions within a C
Program.
🞆 There are following storage classes which can be
used in a C Program
⚫auto
⚫register
⚫static
⚫extern
STORAGE CLASS
🞆 storage class tells the compiler
⚫Storage area of the variable
⚫Initial value if not initialized
⚫Scope of the variable
⚫Life, ie how long the variable would be active in pgm
AUTO - STORAGE CLASS
🞆 auto is the default storage class for all local
variables.
🞆 { int Count;
🞆 auto int Month; }
🞆 The example above defines two variables with
the same storage class.
🞆 Scope is local to current block/pgm
REGISTER - STORAGE CLASS
🞆 register is used to define local variables that
should be stored in a register instead of RAM.
🞆 {
🞆 register int Miles;
🞆 }
🞆 Register should only be used for variables that
require quick access - such as counters. It should
also be noted that defining 'register' goes not
mean that the variable will be stored in a
register. It means that it MIGHT be stored in a
register - depending on hardware and
implementation restrictions.
STATIC - STORAGE CLASS
🞆 It is once initialized & never reinitialized
🞆 The content stored in these variables persists at
each call & the last change made in the value of
static variable remain throughout the execution
of the block
🞆 static int Count;
STATIC - STORAGE CLASS
🞆 int f(void)
🞆 { static int x = 0;
🞆 x++;
🞆 return x; }
🞆 int main(void)
🞆 {
🞆 int j;
🞆 for (j = 0; j < 5; j++)
🞆 {
🞆 printf("Value of f(): %d\n", f());
🞆 }
🞆 return 0;
🞆 }
EXTERN – STORAGE CLASS
🞆 The variable that is available to all functions are
called global or external variables
🞆 It is declared outside function body
🞆 If we declare external variable, there is no need
to pass these values to another function
🞆 Memory is once allocated
⚫Extern int a;
RECURSION
🞆 Recursive functions
⚫Functions that call itself is known as recursion.
⚫Recursion is generally used when the result of the
current function call is the input to the successive
call of itself.
⚫ For example, ‘factorial of a digit’.
POINTERS
🞆 Pointers are variables that contain memory
addresses as their values.

🞆 A variable name directly references a value.

🞆 A pointer indirectly references a value.


Referencing a value through a pointer is called
indirection.

🞆 A pointer variable must be declared before it can


be used.
POINTER DECLARATION
🞆 Examples of pointer declarations:

int *a;
float *b;
char *c;

🞆 The *, when used as above in the declaration,


tells the compiler that the variable is to be a
pointer, and the type of data that the pointer
points to
POINTERS - EXAMPLE
int main()
{
float fl=3.14;
float* addr = &fl;
printf("%f\n", fl);
printf("%f\n”,*addr);
return 0;
}
USE OF & AND *
🞆 When is & used?

🞆 When is * used?

🞆 & -- "address operator" which gives or produces


the memory address of a data variable
🞆 * -- "dereferencing operator" which provides the
contents in the memory location specified by a
pointer
FEATURES OF POINTERS
🞆 Pointers save memory space
🞆 Execution time with pointer is faster
🞆 Dynamically allocated and efficient
🞆 Used with data structures (arrays)
POINTERS & FUNCTIONS
⚫Call by value/Pass by value
🞆 passing the values of the variables to the called function
⚫Call by reference/Pass by address/reference
🞆 pass addresses of variables to called functions.
POINTERS & FUNCTIONS
Pass by value
#include <stdio.h> void swap( int a, int b )
void swap ( int a, int b ) ; {
int main ( ) int temp;
{ temp= a; a= b; b = temp ;
int a = 5, b = 6; printf ("a=%d b=%d\n", a,
printf("a=%d b=%d\n",a,b) ; b);
swap (a, b) ; }
printf("a=%d b=%d\n",a,b) ; Results:
return 0 ; a=5 b=6
} a=6 b=5
a=6 b=5
POINTERS & FUNCTIONS
Pass by address/reference
#include <stdio.h> void swap( int *a, int *b )
void swap ( int *a, int *b ) ; {
int main ( ) int temp;
{ temp= *a; *a= *b; *b = temp ;
int a = 5, b = 6; printf ("a=%d b=%d\n", *a,
printf("a=%d b=%d\n",a,b) ; *b);
swap (&a, &b) ; }
printf("a=%d b=%d\n",a,b) ; Results:
return 0 ; a=5 b=6
} a=6 b=5
a=6 b=5
ARRAYS AND POINTERS
🞆 The name of an array without a subscript (index
number) is also a pointer constant. When the
name is used without the subscript it references
the address of element 0 of the array.

int myarray[10]; /* Declare an array */


int *myptr; /* Declare a pointer (not initialized)*/
printf (“%d\n”, myarray); /* print address of myarray[0]
*/
scanf (“%d”,&myarray[0]); /* get value from keyboard and
store in myarray[0] */
ARRAYS AND POINTERS
myptr = &myarray[2]; /* Assign the address of the third
element of myarray to myptr */
printf(“%d”, *myptr); /* Print the value of what myptr is

Winter Quarter
pointing to, i.e., the value of
myarray[2] */

🞆 Note that the * in front of myptr de-references the


pointer. That is, it says “use the value in the
address that is pointed to.”

🞆 The following shows a small program and its


output. Lect
15

P.
57
POINTER ARITHMETIC
🞆 Arithmetic operations can be performed on
pointers
⚫ Increment/decrement pointer (++ or --)
Example:
++vPtr, vPtr++,
--vPtr, vPtr--
⚫ Add an integer to a pointer( + or += , - or -=)
⚫ Pointers may be subtracted from each other
⚫ Operations meaningless unless performed on an
array
POINTER ARITHMETIC
🞆 Subtracting pointers
🞆 Pointer comparison ( <, == , > )
⚫See which pointer points to the higher numbered array
element
⚫Also, see if a pointer points to 0

🞆 Pointers of the same type can be assigned to each


other
POINTER ARITHMETIC
POINTER ARITHMETIC
ARRAY OF POINTERS
🞆 It is a collection of addresses
🞆 Addresses of variables stored in an array
🞆 main()
🞆 {
🞆 int *arrp[3];
🞆 int arr[3]={5,10,15},k;
🞆 for(k=0;k<3;k++)
🞆 arrp[k]=arr+k;
🞆 for(k=0;k<3;k++)
🞆 {
🞆 printf("%u",arrp[k])
🞆 printf("%d",arr[k]);
🞆 }
DYNAMIC MEMORY ALLOCATION
🞆 The process of allocating memory at run time is
known as dynamic memory allocation.
🞆 Although c does not inherently have this facility
there are four library routines which allow this
function.
DYNAMIC MEMORY ALLOCATION

🞆 Malloc
⚫ Allocates memory space in bytes and returns a pointer to the Ist byte of
allocated space
⚫ Pnt=(datatype*) malloc(size)
🞆 calloc
⚫ Allocates space for an array of elements initializes them to zero and
returns a pointer to the memory
⚫ Pnt=(datatype*)calloc(4,2)
🞆 Free
⚫ Frees previously allocated space
⚫ Free(pnt)

🞆 Realloc
⚫ Modifies the size of previously allocated space.
⚫ Pnt=(datatype*)realloc(pnt,newsize)
USER DEFINED TYPES
🞆 What are the datatypes in C?
STRUCTURE
🞆 A collection of one or more variables, typically of
different types, grouped together under a single
name for convenient handling
🞆 Known as structure in C
🞆 A struct is heterogeneous in that it can be
composed of data of different types.
🞆 In contrast, array is homogeneous since it can
contain only data of the same type
STRUCTURE
🞆 Structures hold data that belong together.
🞆 Examples:
⚫Student record: student id, name,
major, gender, start year, …
⚫Bank account: account number, name,
currency, balance, …
⚫Address book: name, address,
telephone number, …
STRUCTURES
🞆 Defines a new type
🞆 I.e., a new kind of data type that compiler regards as a unit
🞆 format
struct structtype { Data
type variable; members or
fields
type variable;

};
STRUCT EXAMPLES
🞆 Example:
struct StudentInfo{
int Id; The “StudentInfo”
int age;
char Gender; structure has 4
double CGA; members
};
of different types.
🞆 Example:
struct StudentGrade{
char Name[15];
char Course[9]; The
int Lab[5]; “StudentGrade”
int Homework[3];
int Exam[2]; structure has 5
}; members of
different array
THE STRUCT STATEMENT
🞆 Here is an example struct statement.
#include <stdio.h>
struct line {
int x1, y1; /* co-ords of 1 end of line*/
int x2, y2; /* co-ords of other end */
};
main()
{
struct line line1;
.
.
}
This defines the variable line1 to be
a variable of type line
ACCESSING PARTS OF A STRUCT
🞆 To access part of a structure we use the dot
notation

Struct line line1;


line1.x1= 3;
line1.y1= 5;
line1.x2= 7;

if (line1.y2 == 3) {
printf ("Y co-ord of end is 3\n");
}
WHAT'S THE USE OF STRUCTS?
🞆 It makes your programming easier and it makes
it easier for other programmers.
🞆 You can extend the language.
NESTED STRUCTURES
🞆 We can nest structures inside structures.

🞆 Examples:
struct point{
double x, y;
};
struct point P;

struct line{
struct point p1, p2;
};
struct line L;
NESTED STRUCTURES
🞆 We can nest structures inside structures.
🞆 struct line{
struct point p1, p2;
};
line L;
🞆 To access
⚫ L.p1.x=45.9;

line
p1 p2
x y x y

77
UNION
🞆 A union, is a collection of variables of different
types, just like a structure. However, with
unions, you can only store information in one
field at any one time.
🞆 A union can also be viewed as a variable type
that can contain many different variables (like a
structure), but only actually holds one of them at
a time (not like a structure). This can save
memory if you have a group of data where only
one of the types is used at a time. The size of a
union is equal to the size of it's largest data
member
UNION
🞆 union time
{
🞆 long simpleDate;
double perciseDate;
🞆 }mytime;
....
The union above could be used to either store the
current time (in seconds) to hold time accurate to
a second. Or it could be used to hold time
accurate to a millisecond. Presumably there are
times when you would want one or the other, but
not both
USER DEFINED DATA TYPES
(TYPEDEF)
🞆 The C language provides a facility called typedef for
creating synonyms for previously defined data type
names. For example, the declaration:

typedef int Length;

makes the name Length a synonym (or alias) for the


data type int.
🞆 The data “type” name Length can now be used in
declarations in exactly the same way that the data
type int can be used:

Length a, b, len ;
Length numbers[10] ;
TYPEDEF
🞆 Typedef allows us to associate a name with a
structure (or other data type).
🞆 Just increase readability of yr pgm.

typedef struct line {


int x1, y1;
int x2, y2;
} LINE;

int main()
{
LINE line1; line1 is now a structure of line type

}
ENUMERATION
🞆 Enumeration is a user-defined data type. It is defined
using the keyword enum and the syntax is:
enum tag_name {name_0, …, name_n} ;

🞆 The tag_name is not used directly. The names in the


braces are symbolic constants that take on integer
values from zero through n. As an example, the
statement:
enum colors { red, yellow, green } ;
🞆 creates three constants. red is assigned the value 0,
yellow is assigned 1 and green is assigned 2.
PREPROCESSOR DIRECTIVE
🞆 It used to specify special instructions in a
program which is processed before the actual
program is executed.
🞆 Recognized by a # sign
🞆 Semicolon is not placed at the end of it
PREPROCESSOR DIRECTIVE
🞆 Macro directives
⚫Used for defining symbolic constants
⚫#define identifier name value
⚫Value can be integer/string
⚫Whenever the identifier name is encountered
preprocessor replaces it with value
PREPROCESSOR DIRECTIVE
🞆 #define
⚫Ex
#define maxmarks 100
int array[maxmarks]
🞆 #undef name
🞆 #include
🞆 #ifdef endif
🞆 #ifndef endif
GUIDELINES FOR DEVELOPING A
PROGRAM
🞆 Coding character set – ascii set
🞆 Declaration – before executable
🞆 Naming convention & restrictions
🞆 Complexity – avoid excessive use nested
expression
🞆 Modularity – to manage the complexity
🞆 Datatype – result may vary on datatype
🞆 Goto - avoided
🞆 Array – index out of bound
🞆 Arithmetic expression – divide by zero error
FORMATTED INPUT
🞆 Inputting integer
🞆 The formatted input refers to input data that has
been arranged in a particular format. Input values
are generally taken by using the scanf function. The
scanf function has the general form.

Scanf (“control string”, arg1, arg2, arg3


………….argn);
🞆 The format field is specified by the control string
🞆 the arguments arg1, arg2, …………….argn specifies
the address of location where value is to be stored.
FORMATTED INPUT
🞆 Inputting integer
🞆 The general format for reading a integer number
is

%xd

% - denotes that a specifier for conversion follows


x is an integer number which specifies the width
of the field of the number that is being read
FORMATTED INPUT
🞆 Inputting integer
🞆 scanf (“%3d %4d”, &sum1, &sum2);

If the values input are 175 and 1342 here value


175 is assigned to sum1 and 1342 to sum 2.
🞆 Suppose the input data was follows 1342 and
175. The number 134 will be assigned to sum1
and sum2 has the value 2 because of %3d the
number 1342 will be cut to 134 and the
remaining part is assigned to second variable
sum2
FORMATTED INPUT
🞆 Inputting integer
🞆 A number may be skipped using *
⚫Scanf(“%d%*d%d”,&a,&b)
⚫123 456 789 (456 will be skipped a get 123 and b
get 789)
FORMATTED INPUT
🞆 Inputting real number
⚫Unlike integer , the field width of real numbers
is not to be specified
🞆 Inputting strings
⚫%ws
⚫Scanf(“%15s”,name)
FORMATTED OUTPUT
🞆 Example
DATA TYPES IN C
🞆 Primary data types
⚫int, float, char,void
🞆 Derived data types
⚫Arrays come under this category
⚫Arrays can contain collection of int or float or char or
double data
🞆 User defined data types
⚫Structure, union, typedef and enum fall under this
category.

BACK

You might also like