Unit 5 - Array
Unit 5 - Array
🞆 Format
⚫datatype arrayname[rowsize][colsize]
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} };
🞆 char name[20];
line[i++]=c;
}while(c!=‘\n’);
c-- ;
line[c]=‘\0’;
}
READING LINE OF TEXT -
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.
int *a;
float *b;
char *c;
🞆 When is * used?
Winter Quarter
pointing to, i.e., the value of
myarray[2] */
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
🞆 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
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:
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.
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} ;
%xd
BACK