Sunday, January 3, 2010

Structures

Structures

  • Collection of related variables
  • derived data types
  • Contain variables of many different data types
  • Individual structure elements are known as members
  • The general syntax structure declaration is:

struct name_tag{
member_1;
member_2;
member_3;
...
member_n;
};

  • "struct" is a keyword
  • name_tag is a name that identifies the structure
  • The individual members can be ordinary variables, pointers, arrays and other structures
  • Example

struct student{
int matrikno;
char name[40];
float height;
};

  • A structure member can be accessed by a dot operator
  • The syntax of a dot operator is:
    • variable.member
  • where variable refers to the name of a structure type variable and member represents to the name of a member within a structure
  • Example

#include

struct studentdate{
int matno;
int month;
int date;
int year;
};

int main (void){

studentdate joiningdate;

scanf("%d", &joiningdate.matno);
scanf("%d", &joiningdate.month);
scanf("%d", &joiningdate.date);
scanf("%d", &joiningdate.year);

printf("%d\n", joiningdate.matno);
printf("%d\n", joiningdate.month);
printf("%d\n", joiningdate.date);
printf("%d\n", joiningdate.year);

return 0;
}

Saturday, January 2, 2010

Pointers

Pointers

  • A variable that represents the location of a data item
  • Used to pass information between a function and its reference point
  • Provide a way to return multiple data items from a function
  • Every data item is stored in the computer memory and it occupies one or more bytes of contiguous memory cells
  • Example

char letter;

letter = 'A'

letter

5566

65

(Address Memory Location)

  • The address of the variable can be determined using the expression, &letter
  • The address can be stored to a new variable
    • pv = &letter
  • The variable pv contains the address of the variable (1188) "letter"
  • The new variable is called pointer to "letter" since it points to the location where the letter is stored in memory
  • The data item represented by "letter" can be accessed by the expression *pv where * is an unary operator called indirection operator
  • The indirection operator * can operate only on address
  • Example 1

#include

int main (void){

char letter;
char *pletter;
letter = 'A';

printf("The address of the variable letter is %x\n", &letter);
pletter = &letter
printf("The address of the variable letter is %x\n", pletter);
printf("The character stored in the letter is %c\n, letter);
printf("The character stored in the letter is %c\n, *pletter);

return 0;
}

Result:
The address of the variable letter is ABCD
The address of the variable letter is ABCD
The character stored in the letter is A
The character stored in the letter is A

  • Example 2

#include

int main (void){

int a, b;
int pta;
a = 10;
pta = &a;
b = 2 * (*pta + 15);
printf("The expression value is %d\n", b);
return 0;
}


Result:
The expression value is 50

%s format and %[ ] format specifier

  • The %s format and the square bracket specifiers are used to read string of characters
  • %s format will read all the character from the input buffer till it encounters a blank space
  • %[ ] format will read all the character from the input buffer till it encounters a character that is not found in the list within the square bracket
  • ^ symbol is used as first symbol in side the %[ ] format specifier then it represents compliment of characters
  • Example 1:

#include

int main (void){

char string[40];
char string1[40];

printf("Please enter the input string:");
scanf("%s", string);
printf("Please enter the input string1:");
scanf("%[1234567890abcdefghijklmnopqrstuvwxyz]", string1);
printf("The output for variable string is: %s\n", string);
printf("The output for variable string1 is: %s", string1);

return 0;
}

Result:
Please enter the input string: Today is very hot
Please enter the input string1: Today is very hot
The output for variable string is: Today
The output for variable string1 is: Today is very hot

Pointer and One Dimensional Array

1800

1802

1804

1806

1808

(2 bytes)

(2 bytes)

(2 bytes)

(2 bytes)

(2 bytes)

50

60

70

80

90

mark[0]

mark[1]

mark[2]

mark[3]

mark[4]

*mark

*(mark + 1)

*(mark + 2)

*(mark + 3)

*(mark + 4)

  • int mark [5] = {50, 60, 70, 80, 90}
  • The array of the first array element of mark can be represented as &mark[0] or simply by the mark itself
    • &mark[0] and mark represent the same memory address which is the 1800
  • The address of second array element can be written as &mark[1] or (mark + 1)
  • In general, the address of (i +1)th array element cab be written as &mark[i] or (mark + i)
  • Example:

#include

int main (void){

int i;
int x[5] = {50, 60, 70, 80, 90};
for(i=0;i<5;i++)
printf("i = %d, address is %x, value is %d\n", i, &x[i], x[i]);
printf("\n");
for(i=0;i<5;i++)
printf("i = %d, address is %x, value is %d\n", i, (x+i), *(x+i));
return;
}

Output:
0 address is 1800 value is 50
1 address is 1800 value is 60
2 address is 1800 value is 70
3 address is 1800 value is 80
4 address is 1800 value is 90

0 address is 1800 value is 50
1 address is 1800 value is 60
2 address is 1800 value is 70
3 address is 1800 value is 80
4 address is 1800 value is 90

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