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

Wednesday, August 26, 2009

Loops

Loops
  • Loop is to repeat the action over and over again
  • This condition to terminate or exit a loop is referred as loop control expression
  • C provide two looping statements namely: for, while and do...while

The while loop
  • pretest loop
  • It used an expression to control the loop
  • It test the expression before every iteration of the loop
       while (expression){
             Statements
       }
  • As long as the expression is evaluated to true the statements in the loop body will be repeated.

The for loop
  • a pretest loop
  • uses three expression
  • first expression contains initialization statements
  • the second contains the limit-test expression
  • the third contains the updating expression
  • A for loop is normally used when the number of times of the loop to be executed are knowns
       for(initialization; limit-test; updating){
             Statements;
       }
  • As long as the limit-test is evaluated to true the statements in the loop body will be repeated.

The do...while loop
  • a post-test loop
  • It also uses an expression to control the loop
  • It tests the expression after the execution of the body
  • The do…while loop end with a semicolon
  • The do…while loop only test the expression at the end of the loop, the body of the loop will be at least execute for once
       do{
              Statements;
       }while (expression);
  • As long as the expression is evaluated to true the statements in the loop body will be repeated.

Tuesday, August 25, 2009

Selection Statement

Selection Statement
  • A selection statement is a control statement that allows choosing between two or more execution paths in a program.
  • C provide one-way, two-way and multiple conditional branching execution.
  • C provides this branching through two methods namely if statement and switch statement
If
  • There are three ways of writing if statements.
if
       if(expression){
                Statements;
        }
  • The expression is evaluated to either true or false.
  • True is nonzero value and false is zero value.
  • The Statements inside the if will only be executed if the expression is evaluated to true
if…else
        if(expression){
                Statements1;
        }else{
                Statements2;
        }
  • If the expression is evaluated to true then Statements1 will be executed.
  • If the expression is evaluated to false then Statements2 will be executed.
if…elseif
        if(expression1){
                Statements1;
        }elseif (expression2{
                Statements2;
        }elseif (expression3){
                Statements3;
        }else{
                Statements4;
        }

Switch Statements

  • Switch is a composite statement used to make a decision between many alternatives
  • The expression of switch statements must be evaluated to either integer type or character constant.
  • The selection condition must be one of the C integral types

        switch (expression){
               case constant-1: statement;
                                               …
                                              statement;
                                              break;
               case constant-2: statement;
                                               …
                                              statement;
                                              break;
               case constant-n: statement;
                                               …
                                              statement;
                                              break;
               default                : statement;
                                               …
                                              statement;
                                              break;
         }
  • Each case label must be a constant expression either integer or character
  • The case label simply provides an entry point to start executing the code
  • Default is executed whenever none of the other case values matches the value in the switch expression
  • The break statement causes the program to jump out of the switch statement; continue with the code after the switch statement

Saturday, August 22, 2009

Expressions

Expressions
An expression is a sequence of operands and operators that reduces to a single value
An operator is a language-specific syntactical token that requires an action to be taken.
An operand receives an operator’s action.

Precedence rule used to determine the order of execution between different operators in an expression. The higher the number, the earlier the execution.
Associativity rule used to determine the order of execution in which the operators with the same precedence level.

Assignment Expression
Assignment Expression evaluates the operand on the right side of the operator (=) and places its value in the variable on the left.

Postfix Increment/Decrement
The value of the postfix increments (decrements) expressions is determined before the variable is increase (decrease).

Example

int a = 7;

printf("%d\n", a)
printf("%d\n", a++)
printf("%d\n", a)

Output:
7
7
8

Prefix Increment/Decrement
The value of the prefix increments (decrements) expressions is increase then the value is determined.

Example

int a = 7;

printf("%d\n", a);
printf("%d\n", a++);
printf("%d\n", a);

Output:

7
8
8

Friday, August 21, 2009

Printf and Scanf

Printf
Used for formatted output in C.
Writes formatted data to the monitor
Printf needs two things
  • Instruction for formatting the data and
  • The actual data to be printed

Example:
          int a;
          char b;
          float c;
          double d;

          printf("%d %c %f %lf", a, b, c, d);

Conversion Code:

int           %d
char        %c
float        %f
double    %lf

Scanf
Used for formatted input in C.
Reads formatted data from the keyboard
It consists of two parts
  • A format string that describes the data and
  • an address list that identifies where data are to be placed in memory
scanf requires that variables in the address list be represented by their address.
To specify an address, you prefix the variable name with the address operator, the ampersand (&)

Example
          int a;
          char b;
          float c;
          double d;

          scanf("%d %c %f %lf", &a, &b, &c, &d);

Friday, August 14, 2009

Data Type, Variables and Constant

Data Type
The are four basic data type for C namely:
  • char (character)
  • int (integer)
  • float (floating-point number)
  • void
Variables

Variables are named memory locations that have a type.

Must declare and define in order to used it.

Example

          int a;
          float b;
          char c;

Can not declare a variable of type void!!!
Can initialize a value to it during the declarations refers as initialization.

Example

          int a = 1;
          float b = 1.0;
          char c = 'a';

Constant

Data values that cannot b changed during the execution of the program.
Character constants are enclosed between two single quotes.
Example:
          'a'
          '\n'
String constant is a sequence of zero or more characters enclosed in double quotes
Examples:
          "a"
          "ums"

C Program Structure

The C program structure serve as a important basic for understanding how to write a C program. This structure describe the important component for writing a C Program.

           Preprocessor Directives

           Global Declarations

           int main (void){

           Local Definitions

           Statements

           return 0;
           }