Vous êtes sur la page 1sur 59

Introduction to C Language

Day 2

by Supreet Singh
Arrays
Arrays
• An array is a series of variables, all being same
type and size
• Each variable in an array is called an array element
• All the elements are of same type, but may contain
different values
• The entire array is contiguously stored in memory
• The position of each array element is known as
array index or subscript
• An array can either be one dimensional (1-D) or two
dimensional (2-D) or Multi-dimensional
Declaring a 1-D Array
 Syntax:
data-type arrayname[size];
 Example:
int aiEmployeeNumbers[6];
float afSalary[6];

 The array index starts with zero

 The valid array indexes for the above declared array is 0 to 5

 When an array is declared inside a function without initializing it, the elements
have unknown (garbage) values and outside the function the elements have
zero/default values
Declaring and Initializing arrays (1 of 2)
 Arrays can be initialized as they are declared
 Example:
int aiEmployeeNumbers[] = {15090, 15091, 15092,
15093,15094, 15095};

 The size in the above case is optional and it is


automatically computed
 In the above example size of the array is 6 and it
occupies 6 * 4 = 24 bytes (6 is the size of the array and 4
is the number of bytes required to store one integer on
Windows platform)
Declaring and Initializing 1-D arrays (2 of
2)
 When an array is partially initialized within a
function the remaining elements will be
garbage values and outside any function the
remaining elements will be zero values
Example:
int aiEmployeeNumbers[6] = {15090,
15091, 15092};

 Inthe above example, the array indexes from


3 to 5 may contain zero or garbage values
2-D Arrays
 A 2-D array is used to store tabular data in terms of rows and
columns

 A 2-D array should be declared by specifying the row size and the
column size

 To access the individual elements, the row and the column should
be supplied

 The 2-D array is essentially a one dimensional array wherein each


element itself is another array, hence an array of arrays

 As far storage is concerned, the row elements are in continuous


locations of memory hence called row major ordering in C language

 The table type visualization of rows and columns is therefore only for
convenience
Declaring and using 2-D Arrays
 A 2-D array can be declared by specifying the maximum size for rows and
columns
 Syntax:
data type arrayname [Row Size][Column Size];
 Example:
int aiEmployeeInfo[3][2];
The above declaration declares aiEmployeeInfo with 3 rows and 2 columns

 To access the individual elements row index (starts from zero) and the
corresponding column index (starts from zero) should be supplied
 Example:
printf(“%d”,aiEmployeeInfo[0][1]);

The above printf references the information at 0th row 1st column
Initializing 2-D Arrays(1 of 2)
 A 2-D array can be initialized as given below:

int aiEmployeeInfo[3][2]= {101,1,102,1,103,2};

In the above declaration,


 101, 102 and 103 refers to employeeids and they are stored in
[0][0], [1][0] and [2][0] positions
 1,1 and 2 refers to Job Codes and they are stored in [0][1], [1]
[1] and [2][1] positions
Initializing 2-D Arrays (2 of 2)
 A 2-D array can be declared without specifying the row size if
it is initialized

 Example:
int aiEmployeeInfo[][3]= {101,1,102,1,103,2};
Since there are six initial values and the column size is 3, the
number of
rows is taken as 2

 If the column size is not supplied then there will be a


compilation error
Pointers
Pointers(1 of 5)
A pointer is a special variable which stores the
address of a memory location. It can be the address
of a variable or directly the address of a location in
memory

A variable is a name given to a set of memory


locations allocated to it

 For every variable there is an address, which is the


starting address of its set of memory locations

 Ifa variable called p holds the address of another


variable i then p is called as a pointer variable and
p is said to point to i
Pointers -Address of Operator(2 of 5)
 Ampersand (&) is the “address of” operator .It is used to fetch the
memory address of a variable
 * is called the indirection operator, dereferencing or value at
address operator and is used with a pointer variable to fetch the
value at a given memory location
 Both these operators are used with pointers
iNumber
Memory
Address

8FFE 5

&iNumber
Pointers - Address of Operator(3 of 5)
 To print the address of a variable, precede the variable with an
Since an address is an unsigned integer,
ampersand (&) %u is used as a conversion specifier

 Example:
int iNumber = 100;
printf(“The value is %d\n”,iNumber);
printf(“The address is %u\n”,&iNumber);
printf(“The address in hexa decimal is
%x\n”,&iNumber);

An address can be printed in hexa decimal form


using %x as the conversion specifier
Pointers(4 of 5)
 To declare a pointer variable, use the following syntax
data-type *pointerName;
Example:
1. int *piCount;
This declaration tells the compiler that piCount will be
used to store the address of an integer value – in other
words piCount points to an integer variable.
2. float *pfBasic;
This statement declares pfBasic as a pointer variable
which can contain the address of a float variable.

Note: The size of pointer variable on Windows platform is 4 bytes.


However it may vary from one platform to another.
Pointers(5 of 5)
Example:
int iCount = 8;
int *piCount;
piCount = &iCount;
printf(“Value=%d”,*piCount);
 iCount: an integer variable
 piCount: an integer pointer
 &: the “address of” operator
 * : the “indirection” operator
Reading Contents of a variable using
Pointers
 To access the value at the address stored in the pointer, use
the following syntax *pointervariable
 Example:
printf(“%d”, *piCount);
 Here the * operator preceding piCount will fetch the value at the
address stored in piCount

 Using ‘==’ operator (Equal to) on pointers, will check whether


both pointers being compared are pointing to the same
address or not

 Uninitialized pointers may point to any memory location

 Using * (indirection operator) on uninitialized pointers may


result in program throwing a run time error
NULL Pointers
 Usinga pointer without initializing it to any valid
address may result in data corruption or even
program crash

 To differentiate between initialized and un


initialized pointers, we usually set an un
initialized pointer to NULL

 Example:
/* Initializing pointer to NULL */
int *piCount = NULL;
Strings
Strings (1 of 2)
A string is a series of characters in a group that
occupy contiguous memory

 Example:

“CDAC”
“Information Technology”

 A string should always be enclosed with in


double quotes (“)
Strings (2 of 2)

 In
memory, a string ends with a null
character ‘\0’

 Space should be allocated to store ‘\0’ as


part of the string

Anull character (\0) occupies 1 byte of


memory
Declaration of Strings (1 of 2)
Syntax:
char variablename [Number_of_characters];
 Example:
char acEmployeeName[20];
Here 20 implies that the maximum number of characters can be 19
and one position is reserved for ‘\0’
Since a character occupies one byte, the above array occupies 20
bytes (19 bytes for the employee name and one byte for ‘\0’)
Declaration of Strings (2 of 2)

/* Declare String as a char pointer */

char *pcName = “Cdac”;

/* Declaring a string as a character array */


char acName[ ] = “Cdac”;

 Think why ‘\0’ requires only one byte!!


Printing Strings to Console (1 of 2)

 Using Character pointer:


char *pcProg = “C Fundamentals”;
printf(pcProg);
printf(“This is %s course”,pcProg);

 Using Character Array:


char acProg[] = “C Fundamentals”;
printf(acProg);
OR
printf(“%s”, acProg );
printf(“This is %s course”,acProg);
Printing Strings to Console (2 of 2)

 Printing a string as part of a formatted


string
int iCourseId = 27;
char *pcProg = “C Fundamentals”;
/* print the courseId (Int)
and Course name(char*) */
printf(“The Id of this course
is %d and this course is %s
\n”,iCourseId, pcProg);
strlen() Function
 strlen() function is used to count the number of characters in the string

 Counts all the characters excluding the null character ‘\0’

 Syntax:
unsigned int strlen (char string[]);
Here string[ ] can be a string constant or a character pointer or a character

array and the function returns unsigned int

 Example:
strlen(“Programming Fundamentals”); returns 24

strlen(acItemCategory); returns the number of characters in


the
character array ‘acItemCategory’
Input of Strings – scanf and gets functions

scanf(“%s”, acItemCategory);
scanf(“%s”, &acItemCategory[0]);

Both the input functions are valid. The first one passes the base
address (Address of the first element) implicitly
The second function passes the address of the first element explicitly

gets(acItemCategory);
gets(&acItemCategory[0]);

This is an unformatted function to read strings


String Handling functions
 The following are the string functions that are
supported by C
strlen() strcpy() strcat()
strcmp() strcmpi() strncpy()
strncat() strncmp()
strnicmp()

 These functions are defined in string.h header file

 Allthese functions take either a character pointer or a


character array as an argument
strcpy() Function
 strcpy() function is used to copy one string to another

 Syntax:
strcpy (Dest_String , Source_String);
 Here Dest_string should always be variable

 Source_String can be a variable or a string constant

 The previous contents of Dest_String, if any, will be over written

 Example:
char acCourseName[40];
strcpy(acCourseName , “C Programming”);

The resultant string in ‘acCourseName’ will be “C Programming”


strcat() Function
 strcat() function is used to concatenate (Combine) two strings

 Syntax
strcat( Dest_String_Variable , Source_String ) ;
 In this, the Destination should be a variable and Source_String can
either be a string constant or a variable.
 The contents of Dest_String is concatenated with Source_String
contents and the resultant string is stored into Dest_String variable.

 Example:
char acTraineeFpCourse [50] = “The course is “;
strcat(acTraineeFpCourse,”Oracle 10G”);

The resultant string in ‘acTraineeFPCourse’ will be “The course is


Oracle 10G”
strcmp() Function (1 of 2)
 strcmp() function is used to compare two
strings

 strcmp() does a case sensitive (Upper case


and lower case alphabets are considered to be
different) comparison on strings

 Syntax:
int strcmp( String1 , String2 );
 Here both String1 and String2 can either be a variable or a string
constant
strcmp() Function (2 of 2)
 strcmp() function returns an integer value

 If strings are equal, it returns zero

 Ifthe first string is alphabetically greater than the second


string then, it returns a positive value

 Ifthe first string is alphabetically less than the second


string then, it returns a negative value

 Example:
strcmp(“My Work”, “My Job”); returns a positive
value
strcmpi() Function
 strcmpi()function is same as strcmp()
function but it is case insensitive

 Example:
strcmpi(“My WoRk” , “MY work”); returns zero
Functions
Functions
 A function is a section of a program that performs a specific task

 Function groups a number of program statements into a unit and


gives it a name. This unit can be reused wherever it is required in
the program

 Functions employ the top down approach and hence becomes


easier to develop and manage
main() User defined function

Function
call
Advantages of Functions
 The functions can be developed by different people and can
be combined together as one application

 Solving a problem using different functions makes


programming much simpler with fewer defects

 Easy to code,modify,debug and also to understand the code

 Functions support reusability ie. once a function is written it


can be called from any other module without having to rewrite
the same. This saves time in rewriting the same code
Passing values to functions and returning
values
 Functions are used to perform a specific task on a set of values

 Values can be passed to functions so that the function performs the


task on these values

 Values passed to the function are called arguments

 After the function performs the task, it may send back the results to
the calling function

 The value sent back by the function is called return value

 A function can return back only one value to the calling function
through a return statement

 Function may be called either from within main() or from within


another function
Elements of a Function
 Function Declaration or Function Prototype :
 The function should be declared prior to its usage

 Function Definition :
 Implementing the function or writing the task of the function

 Consists of

• Function Header
• Function Body

 Function Invocation or Function call:


 To utilize a function’s service, the function have to be invoked
(called)
Declaring Function Prototypes (1 of 2)
A function prototype is the information to the compiler
regarding the user-defined function name, the data
type and the number of values to be passed to the
function and the return data type from the function

 This is required because the user-defined function is


written towards the end of the program and the ‘main’
does not have any information regarding these
functions

 Thefunction prototypes are generally written before


‘main’. A function prototype should end with a
semicolon
Declaring Function Prototypes (2 of 2)
 Function Prototypes declare ONLY the signature of the function before
actually defining the function
 Here signature includes function name, return type, list of parameter data
types and optional names of formal parameters

 Syntax:
Return_data_type FunctionName (data_type arg1,
data_type arg2,...,data_type argn );

 Example:
int fnValidateDate(int iDay,int iMonth, int iYear);

In the above example, iDay, iMonth and iYear are optional. The
same can also be written as:

int fnValidateDate(int,int, int);


Writing User-Defined Functions
 A function header and body looks like this:
Return-data-type function-name(data-type argument-1,
data-type argument-2,….){
/* Local variable declarations */
/* Write the body of the function here */
Statement(s);
return (expression);
}
 The return data type can be any valid data type
 If a function does not return anything then the ‘void’ is the return type
 A function header does not end with a semicolon
 The ‘return’ statement is optional. It is required only when a value
has to be returned
Writing User-Defined Functions
Return data type Arguments
(Parameters)
int fnAdd(int iNumber1, int iNumber2){
/* Variable declaration*/
Function header
int iSum;

/* Find the sum */ Function Body


iSum = iNumber1 + iNumber2;

/* Return the result */


return (iSum);
}
Can also be written as return iSum;
Returning values
 The result of the function can be given back to the calling functions

 ‘return’ statement is used to return a value to the calling function

 Syntax:
return (expression) ;

 Example:
return(iNumber * iNumber);
return 0;
return (3);
return;
return (10 * iNumber);
Calling User-Defined Functions (1 of 2)
A function is called by giving its name and passing the
required arguments

 The constants can be sent as arguments to functions


/* Function is called here */
iResult = fnAdd(10, 15);

 Thevariables can also be sent as arguments to


functions
int iResult,iNumber1=10, iNumber2=20;
/* Function is called here */
iResult = fnAdd(iNumber1, iNumber2);
Calling User-Defined Functions (2 of 2)

 Calling
a function which does not return
any value
/* Calling a function */
fnDisplayPattern(15);

 Calling
a function that do not take any
arguments and do not return anything
/* Calling a function */
fnCompanyNameDisplay();
Function Terminologies
Function Prototype
void fnDisplay() ;
Calling Function
int main(int argc, char **argv){
fnDisplay();
return 0;
} Function Call Statement

void fnDisplay(){
printf(“Hello World”);
}

Called Function
Function Definition
Formal and Actual Parameters
 The variables declared in the function header
are called as formal parameters

 The variables or constants that are passed in


the function call are called as actual
parameters

 The formal parameter names and actual


parameters names can be the same or
different
Functions – Example (1 of 2)
Function Prototype
int fnAdd(int iNumber1, int iNumber2);

int main(int argc, char **argv) {


int iResult,iValue1=5, iValue2=10;
/* Function is called here */
iResult = fnAdd(iValue1, iValue2);
printf(“Sum of %d and %d is %d\n”,iValue1,
iValue2,iResult);
return 0;
}

Actual Arguments
Functions – Example (2 of 2)
Formal Arguments

/* Function to add two integers */


int fnAdd(int iNumber1, int iNumber2){
/* Local variable declaration*/
int iSum;
iSum = iNumber1 + iNumber2; /* Find the sum */
return (iSum); /* Return the result */
}

Return value
Parameter Passing Techniques
 When a function is called and if the
function accepts some parameters, then
there are two ways by which the function
can receive parameters
 Pass by value
 Pass by reference
Pass by Value (1 of 3)
 When parameters are passed from the
called function to a calling function, the
value of the actual argument is copied onto
the formal argument

 Since the actual parameters and formal


parameters are stored in different memory
locations, the changes in formal parameters
do not alter the values of actual parameters
Pass by Value (2 of 3)
void fnUpdateValues(int iNumber1, int iNumber2);
int main(int argc, char **argv) {
int iValue1=100, iValue2=250;
printf("\n\nBefore calling the function: ");
printf("ivalue1=%d iValue2=%d\n\n",iValue1,iValue2);
/* Call the function */
fnUpdateValues(iValue1, iValue2);
printf("After calling the function: ");
printf(" ivalue1=%d iValue2=%d\n\n",iValue1,iValue2);
return 0;
}
void fnUpdateValues(int iNumber1, int iNumber2){
/* Update the values */
iNumber1 = iNumber1 + 15;
iNumber2 = iNumber2 - 10;
}
Pass by Value (3 of 3)

main() fnUpdateValues()

100 115
200 240

End of function fnUpdateValues


Pass by Reference (1 of 4)
 Addresses of actual parameters are passed

 The function should receive the addresses


of the actual parameters through pointers

 The actual parameters and formal


parameters if referencing the same memory
location, then the changes that are made
become permanent
Pass By Reference (2 of 4)
void fnUpdateValues(int *piNumber1, int *piNumber2);

int main(int argc, char **argv){


int iValue1=100, iValue2=250;
printf("\n\nBefore calling the function: ");
printf("ivalue1=%diValue2=%d\n\n",iValue1,iValue2);
/* Call the function and send the address of the
variables */
fnUpdateValues(&iValue1, &iValue2);
printf("After calling the function: ");
printf("ivalue1=%diValue2=%d\n\n",iValue1,iValue2);
return 0;
}
Pass By Reference (3 of 4)

void fnUpdateValues(int
*piNumber1, int *piNumber2){
*piNumber1 = *piNumber1 + 15;

*piNumber2 = *piNumber2 - 10;


}
Pass by Reference (4of 4)

a fnUpdateValues()
main()

115 Address of
iValue1

240 Address of
iValue2

End of function fnUpdateValues


QUESTIONS?
THANK YOU.

Vous aimerez peut-être aussi