Thursday, December 17, 2009

Array

Arrays

  • Storing multiple data items of the same data type that can be represent by a common name
  • The data items are allocated in continuous memory locations and can be referred by a single name
  • Example:
    • int studentMark [5]

Index

Value

Memory Location

0

75

100000

1

80

100002

2

85

100004

3

90

100006

4

95

100008











  • Each individual data item is referred as an array element
    • studentMark[0] = 75
  • Each array element is referred to by the array name followed by one or more subscripts with each subscript enclosed in square brackets
    • studentMark[0]
  • Each subscripts must be expressed as non-negative integer
  • An array must be declared and define before it can be used
  • Declaration and definition tell the compiler the name of the array, the type of data and the number of elements
  • Example
    • An array name studentMark type integer and size 5

Data Type------Array Name-------Size
int--------------studentMark-------[5]

# include
int main( )
{
int n[10] = {32, 27, 64, 18, 95, 14, 90, 70, 60, 37};
int i;

printf("%s%13s\n", "Element", "Value");

for(i = 0; i <= 9; i++) printf("%7d%13d\n", i, n[i]); return 0; }

Output:

Element

Value

0

32

1

27

2

64

3

18

4

95

5

14

6

90

7

70

8

60

9

37


Multi Dimensional Array

  • The number of subscripts determines the dimensionality of the array
  • The multi dimensional arrays are defined in much the same manner as one-dimensional arrays
  • A pair of square brackets is required for each dimension
  • A two dimensional array will require two pairs of square brackets
    • int studentMark [5][10]

Text Files

Files

  • A collection of related data treated as a unit
  • Files are store in secondary devices
  • Read files - the data move from the external device to RAM
  • Write files - the data move from RAM to external devices
  • The data movement uses a special work area called buffer that act as a temporary storage area

Files and Streams

  • A stream is a sequence of elements in time
  • A file is define by using a standard FILE type
  • The format for the file type is shown below
    • FILE *filename
  • The asterisk is an address that pointed by the filename pointer

Standard Library Input/Output Functions

  • The open/close functions, fopen and fclose, are used to open and close the association between external files and internal streams
  • A file in C can be any of three basic modes:
    • reading, r
    • writing, w
    • appending, a
  • Standard format
    • fopen ("filename", "mode");
  • Example:

File *Infile;
Infile = fopen ("Data.dat", "w");

  • When a file is opened in reading mode, the file marker is positioned at the beginning of the existing file
  • When a file is opened in writing mode, the file marker is positioned at the beginning of the newly created empty file
  • When a file is opened for appending, the file marker is positioned at the end of existing file, before the end-of-file marker
  • fclose is used to closed and opened file
    • fclose(Infile);

Formatting Input/Output Functions

  • Formatted input/output functions allow read data from and write data to file character by character while formatting to the desired data type
  • scanf and fscanf are used for reading

File *fpInput;
fpInput = fopen("data.dat", "r");
fscanf(fpInput, "%d-%d-%d", &day, &month, &year);

  • printf and fprintf are used for writing

File *fpOutput;
fpOutput = fopen("data.dat", "w");
fprintf(fpOutput, "The date is %d-%d-%d", day, month, year);

  • Example

#include
void main () {
int num, sum = 0;
FILE *inptr, *outptr;


if ((inptr = fopen(“infile.txt”, “r”)) != NULL) {
     while(fscanf(inptr, “%d”, &num) != EOF)
        sum += num;
     fclose(inptr);
     if ((outptr = fopen(“outfile.txt”, “w”)) != NULL) {
        fprintf(outptr,“The sum of the numbers is %d\n”,sum);
     fclose(outptr);
     }
}
return ;

Character Input and Output

  • Character input and output are used to read or write files character by character
  • fgetc, getc, and getchar can be used for reading
  • Example:
    • charatcter = getchar( ) //Get character from keyboard
    • character = getc(filepointer) //Get character from file
    • character = fgetc(file pointer) //Get character from file
  • fputc, putc and putchar can be used for writing
  • Example
    • putchar(character)
    • fputc (character, filepointer)
    • putc (character, filepointer

Wednesday, December 16, 2009

Functions

FUNCTIONS

  • Functions in C is to decompose a program into its component functions means smaller part to ease solving the problem
  • A C program is made up of one or more functions, exactly one of which must be named main
  • The execution of the C program begins and terminates with main.
  • The main function can call other functions to do specific jobs
  • Functions is an independent module and each functions solves part of the problem

Benefit of Functions

  • Can test the components separately
  • Can change one function without changing or affecting the other functions
  • Provide a way to reuse code that is required in more than one place.

Declared and Define Functions

  • Like any other object in C, a function must be declared and defined
  • In order to use a function, there are three steps to be done:
  1. Function declaration
  2. Functions definition (function body)
  3. Functions called

1. Function Declaration

  • A function declaration consist of three parts
    Return Type----Function Name----------(Parameter List);
    int--------------addnum------------------(int num1, int num2);
  • The return type of the function can be any of the basic data type (void, int, float, char)
  • The name of the function is a valid C identifier.
  • The parameter list are the place holder for the arguments that the function expects
  • The function declaration must end with a semicolon
  • The function declaration normally declare as global declaration in order to be used in the whole program

2. Function Definition

  • A function definition is made up of two parts
    • Function header
    • Function body
  • A function header is same as the function declaration just that there is no semicolon at the end of the function header
  • A function body is a compound statement which enclosed between open and closed braces
  • The function body contains local variable and declarations and statements and terminated by a return statement
  • A return statement return a value to the main program and exit the function
  • Example:

int addnum (int num1, int num2)
{
int sum;
sum = num1 + num2;
return sum;
}

3. Function call

  • A function call is used to call or invoke the function to be used in the C program
  • A function call is an post fix expression
  • Example:

void main (void)
{
int a, b, result;
scanf(“%d%d”, &a, &b)l;
result = addnum (a, b);
printf(“The sum is: %d”, result);
return;
}

The name of the function is used in three ways:

1. For function declaration
2. In a function call
3. For function definition

There are two ways to call a function in C:

Call By Value

  • Every argument to a function is an expression, which has a value
  • C passes argument to an invoked function by making a copy of the expression value, storing it in a temporary cell
  • Only the copy of the value is passed to the function argument
  • The original data in the calling function are unchanged. As only the copy of the values are passed to the function.
  • Example:

#include
int change (int x);
int main (void){
int a;
printf(“Enter a value: “);
scanf(“%d”, &a);
printf(“Value before call function: %d\n”, a);
change(a);
printf(“Value after call function: %d\n”, a);
return 0;
}

int change (int x){
x = 10;
return 0;
}

Output:
Enter a value: 5
Value before call function: 5
Value after call function: 5

Call by Reference

  • It links the variable identifiers in the calling function to their corresponding parameters in the called function
  • When the called function changes a value in a variable, then it actually changes the variables in the calling function
  • This is done by passing the an address to the called function
    • & - the address operator
    • * - the indirection operator
  • Example

#include
int change (int *x);
int main (void){
int a;
printf(“Enter a value: “);
scanf(“%d”, &a);
printf(“Value before call function: %d\n”, a);
change(&a);
printf(“Value after call function: %d\n”, a);
return 0;
}

int change (int *x){
*x = 10;
return 0;
}

Output:
Enter a value: 5
Value before call function: 5
Value after call function: 10

Standard Library Functions

  • To perform various data manipulations functions will build in functions in the header files
  • The functions called abs, fabs, and labs return the absolute value of a number
  • An absolute number value is the positive rendering of the value regardless of its sign
  • Example:

int abs (int num)
abs (-5) = 5
double fabs (double num)
fabs(-5.6) = 5.6

  • The ceil function return the smallest integer value greater than or equal to the number
  • Example:

ceil (1.2) = 2
ceil (-2.85) =-2

  • The floor function returns he largest integral value that is equal to or less than a number
  • Example:

floor (1.2) = 1
floor (-2.85) = -3

  • The pow function returns the value of the x raised to the power y – that is xy
  • Example:

pow (3.0, 4.0) = 81.0
pow (3.4, 2.3) =16.687893

  • The sqrt function returns the non-negative square root of number
  • Example:

sqrt (36.0) = 6.0

  • The rand function returns a pseudorandom integer between 0 and RAND_MAX, which is defined in the standard library as the largest number that rand can generate
  • Example:

rand( )

  • Generalizing the algorithm for generating a random number between ranges is

    • rand ( ) % ((max + 1) – min) + min