P. 1
Unit 3

Unit 3

|Views: 2|Likes:
Published by Pravallika Reddy

More info:

Published by: Pravallika Reddy on Feb 11, 2012
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PPT, PDF, TXT or read online from Scribd
See more
See less

02/11/2012

pdf

text

original

/* Ranking of 60 students in a class */ int main() { /*declaring 60 varialbes */ int score0, score1,score2,««,score59; /* Reading scores for

sixty times */ printf(³Enter the score : ³); scanf(³%d´, &score0); «. «. «. «. printf(³Enter the score : ³); scanf(³%d´, &score59); /* comparing & swapping for 1770 times * to arrange in descending order */ swap( score0, score1); swap( score1, score2); swap( score2, score3); «. «. «. «. swap( score0,score1); swap( score1,score2); swap( score0,score1); /*printing 60 scores after sorting */ printf(³%4d´, score0); printf(³%4d´, score1); « « « « } void swap ( int a, int b) { int temp; if( a < b) { temp = a ; a = b ; b = temp; } }

Array & its Advantage
score0 score1 score2 score3 . . score59 scores[0] scores[1] scores[2] scores[3] . . scores[59]
Sixty variables are replaced by one Array
#include<stdio.h> Sixty input int main() { int scores[60] , i , j, temp; statements are for(i = 0; i < 60 ;i++) { called by one loop printf("Enter the score : "); statement scanf("%d", &scores[i]); } 1770 comparing for(i=0;i<(60-1);i++) statements are for( j=0; j <(60 -(i+1)); j++) included in one if(scores[ j ] < scores[ j +1]) { temp = scores[ j ]; loop statement scores[ j ] = scores[ j +1]; scores[ j + 1] = temp; } for( i = 0; i < 60; i ++) printf("%4d", scores[i]); }

sum = sum + scores[i].. printf("%. for(i=0. printf("\nVariance = %. stddev = sqrt(variance). stddev. Each deviation is difference of individual score and mean. printf("Standard Deviation : %f".i. } Input to an element mean = (float)sum / SIZE. Accessing #include<stdio. &scores[i] ). i++) { deviation = scores[i] .2f\t".mean).i++) { printf("Enter score : ).. total=total + deviation*deviation. total=0.i<SIZE .2f". } variance = total / SIZE. To calculate deviations of all scores.sum=0. mean. float deviation. float variance . #define SIZE 10 Initialization of Array int main() { int scores[SIZE].h> printf("\nMean : %. deviation). for(i=0. } Processing on Array . variance).scores[0] scores[1] scores[2] scores[3] scores[4] . Declaration of Array an element #include<math.mean. stddev). i < SIZE .2f\n".h> printf("\nDeviations : "). scores must be stored in an ARRAY. scanf("%d". 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 start here ( memory addresses) scores Array Mean can be calculated only after reading all scores.

 The address of first byte is the address of a variable . Vector Variables (arrays):  In contrast. It represents a collection of related data items of same type. An individual data item of an array is called as element .  The lowest address corresponds to the first element and the highest address to the last element. which is simply an array of characters terminated by a null.the value of a scalar variable cannot be subdivided into a more simpler data items. It has additional operations for retrieve and update the individual values.e. referred under a common array name.  Integer takes 2 bytes memory as a single unit to store its value. /* declaration of array */  0 is first number in computer environment. which is also referred to a data structure.. The first element of array marks is marks[0] and last element is marks[9]. i.  All its elements are stored in consecutive memory locations. (the address of first element is the address of the array)  An array is a derived data type. an array is multivariable (an aggregate data type).  Arrays can have from one to several dimensions. . These are also called scalar variables. The most common array is the string. Ex : int marks[10] . Every element is accessed by index or subscript enclosed in square brackets followed after the array name.Scalar variable for single data item & Vector variable for multiple data items Scalar Variables :  A variable represents a data item and it can be used to store a single atomic value at a time.

9.¶a¶. 2. 5 } . Declaration of Multi Dimensional Arrays Syntax : arrayType arrayName [ Rows ][ Columns ]. 7. 2. float x[]) { float sum=0.i.Declaration of One Dimensional Arrays Syntax : arrayType arrayName [ numberOfElements ]. } . 1 } }.µT¶. 3 }. char greeting[ ] = ³Good Morning´. Example : int scores [60]. Initialization of Array while Declaration : int numbers [ ] = { 9. Elements of Array [3] by [4] [0][0] [1][0] [2][0] [0][1] [1][1] [2][1] [0][2] [1][2] [2][2] [0][3] [1][3] [2][3] /*passing an array to function */ #define SIZE 10 int main() { float list[SIZE] .µi¶. 1. arrayType arrayName [ Planes][ Rows ][ Columns ].avg.µv¶. i++) sum = sum + x[i]. for( i = 0. Initialization of Array while Declaration : int matrix [ ][ ] = { { 4.µj¶. { 6. i < n . Example : /* Each student for seven subjects */ int marks[60][7]. list ). 3 } . 4. 7.¶a¶. 5. char name[ ] ={µR¶.µ µ.µe¶. } float average( int n . avg = average(SIZE . return ( sum / n ) . /* Matrix with 3 planes and 5 rows and 4 columns */ float matrix[3][5][4]. 0. { 8. float salaries [20].¶\0¶ }.

ch) -returns pointer to first occurrence of the character ch in s1.Strings .s2) -compares s1 with s2 lexicographically and returns 0 if two strings are same . /*printing a string in input window */ gets(name) . name). strchr(s1. strcpy(s1.s2) . /* printing a string and moves cursor to new line */ String Manipulation Functions in <string. scanf( %s . /*reading a string until a white space is encountered ( & operator is not required )*/ printf( %s . strrev(s1) -returns pointer to the reversed string. In C strings are implemented by an array of characters terminated with a null character \0 (back slash followed by zero ). char name[] = Ravi Kiran . name).One Dimensional Character Arrays A String is sequence of characters.s2) . strcmpi(s1. R a v i K i r a n \0 name name is an array of characters has size of eleven characters including a null character \0 (ascii code is zero). char name[25] .returns the length of string excluding the last null character. strstr(s1. strcmp(s1. */ puts(name).concatenates s2 to s1. /* reading a string including white spaces until \n is encountered.h> strlen(s1) .s2) -returns pointer to first occurrence s2 in s1.s2) -compares s1 with s2 like strcmp() but case of characters is ignored.copies characters in s2 into s1. strcat(s1. . returns -1 if s1 is before s2 and returns +1 if s1 is after s2.

each of which has an address known as byte.Memory Address : Bit is a smallest unit of memory to store either 0 or 1 in memory. BSS (Below Stack Segment) : Memory area contains storage for uninitialized global variables. It also stores memory address of the instruction which is the function call. . Data Section : Memory image of a running program contains storage for initialized global variables. Memory is a sequence of a large number of memory locations . to return the value of called function. Shared Libraries: This region contains the executable image of shared libraries being used by a program. It is also separate for each running instance of a program. Stack : Area of memory image of a running program contains storage for automatic variables of a function.It is read only and is shared by multiple instances of a running program. Byte is unit of memory of 8 bits. C-Language runtime also utilizes an allotted memory block in RAM to run its programs. Memory Sections of C-Runtime RAM is temporary storage place to run programs. Dynamic Memory Allocation calculate the required memory size while program is being executed. Text Section : Memory-area that contains the machine instructions(code). Every byte in memory has a sequential address number to recognized by processor. Heap : This memory region is reserved for dynamically allocating memory for variables at run time. which is separate for each running instance of a program.

b).y).a. printf( \nAfter swap() : %d %d . } int main() { int a = 25.a. int y) { int temp.x.Two or more Permanent Manipulations using one Function Passing Parameters By Value /* program to swap two numbers */ #include<stdio.*y). int *y) { int temp. temp = x. y = temp. } int main() { int a = 25.h> void swap(int x. printf( Before swap() : %d %d . &b). swap (a.b).a.b = 37. printf( \nIn swap() : %d %d . temp = *x.h> void swap(int *x.a.b = 37. printf( \nIn swap() : %d %d . swap (&a . } Output : Before swap() 25 37 In swap () 37 25 After swap() 25 37 Output : Before swap() 25 37 In swap () 37 25 After swap() 37 25 . *y = temp. } Passing Parameters By Reference /* program to swap two numbers */ #include<stdio.b). *x = *y.b).b). x = y. printf( \nAfter swap() : %d %d . printf( Before swap() : %d %d .*x.

*ptr = N . Memory Address of variable option Creates a pointer variable with a name ptr Which can hold a Memory address Memory address of Variable option Is copied to the Pointer ptr The value N is stored in the variable which has the memory address 4042 char *ptr = NULL.Pointer variable A variable holds the address of another variable Allots some memory location 4042 (for example) with a name option and stores value µY¶ in it Value in option Y option 4042 char option = Y . ptr 4042 ptr Y option 4042 ptr = &option. 4042 ptr N option 4042 .

int *p = NULL. p ). printf (³ %d %d ³.Program with Using Pointers int main() { pointer variables are declared int n1. n2 . and the value changed through with one pointer will reflect to both of them. both pointers contains address of the same variable. *q = 3 . Prints 3 3 6 n2 q 3 p *p = 7 . Prints 6 6 p = & n1. *p . *q ) . *q = NULL.*p ). *p . } Prints 7 7 n1 p 6 n2 q 7 When two pointers are referencing with one variable. Prints 6 3 n1 p 6 n2 q 3 n1 pointer µq¶ assigned with pointer µq¶ p = q. . Prints address of n1 n1 p NULL n2 q NULL printf (³%ld %ld´. printf (³ %d %d ³. *q ) . printf (³%d %d´. *p . printf (³ %d %d ³. n1 = 6 .&n1. q = & n2. *q ) . n1.

*q). /* error */ } Prints 12 12 Prints 12 12 Pointer is an address variable. p = a. q = p. int *p . The address stored in the pointer can be changed time to time in the program. the address of first element of the array is copied into the pointer. b[3].Pointer and Arrays Even though pointers and arrays work alike and strongly related. printf("%d %d\n". they are not synonymous.*q. When an array is assigned with pointer. *a).h> int main() { int a[3] = { 12. printf("%d %d". The address stored in array name cannot be changed in the program. b = a. having no initialized value by default. . 5 . #include<stdio. *p. Array name is an address constant.*p.7}. initialized with the address of the first element (base address )in the array.

printf("%d %d %d\n". *(p).1 p p +1 p +2 p +3 Subscript operator [ ] used to access an element of array implements address arithmetic. int *p. 31.h> int main() { int arr [5] = { 12. Prints 31 p = arr + 1. --p. *(p + 1)). *p). *(p-1). 56. arr[0] or *( arr + 0 ) arr[1] or *( arr + 1 ) arr[2] or *( arr + 2 ) arr[3] or *( arr + 3 ) arr[4] or *( arr + 4 ) Prints 12 31 56 12 31 56 19 42 p . *p). 19. like pointer. .Pointer Arithmetic and Arrays #include <stdio. Prints 12 printf("%d". printf("%d \n". 42 }.

int *pa = &a. ³Saturday´ }. prints 25 printf(³%d´.Array of Pointers The advantage of pointer array is that the length of each row in the array may be different. *ppa = &pa. **ppa). ³Thursday´. The important application of pointer array is to store character strings of different length. printf(³%d´. Pointer to Pointer ( Double indirection ) Example : int a = 25.Pointers a[0][0] a[0][1] a[0][2] a[1][0] a[1][1] a[1][2] a[2][0] a[2][1] a[2][2] a[3][0] a[3][1] a[3][2] base_address Array name contains base address Address of a[ i ] [ j ] = *( * ( base_address + i ) + j ) = * ( * ( a + i ) + j ) . ³Monday´. Example : char *day[ ] = { ³Sunday´. prints 25 a 25 4024 pa 4024 4056 ppa 4056 4078 Two Dimensional Array -. int **ppa . ´Tuesday´. ³Friday´. ³Wednesday´. *pa).

). type2 arg2. p = &x. *( ( int *)p) ). float y = 23. which can be assigned to any data type without cast during compilation or runtime. int b ) { return (a + b) .void Pointer µvoid¶ type pointer is a generic pointer. int x = 7.5. µvoid¶ pointer cannot be dereferenced unless it is cast. printf(³Difference = %d\n´. int ) . } Output : Sum = 9 Difference = 4 . fp = sub. ««. fp( 4.500000 Function Pointers Function pointers are pointers. *( ( float *)p) ). 5 ) ) . int add ( int a. fp( 6 . 2 ) ) . which point to the address of a function. printf(³y contains : %f\n´. printf(³Sum = %d\n´. Declaration : <return type> (* function_pointer) (type1 arg1. int b ) { return (a ± b) . } Output : x contains 7 y contains 23. int main( ) { void* p. } int (*fp ) (int. printf(³x contains : %d\n´. p = &y. } int sub ( int a. /* function pointer */ int main( ) { fp = add.

. Allocates memory in bytes and returns the address of first int main() byte to the pointer variable { int *p. ptr = (book * ) realloc ( ptr . ptr = (book *) calloc ( 10.Dynamic Memory Allocation (DMA) of pointers Static memory allocation means allocating memory by compiler. Example : } struct book { printf(³Address in p : %d³. The values returned by these functions are assigned to pointer variables only after execution of these functions. float price . int *p = &a . struct book b1 . Releases previously allocated memory space. b1 *ptr . p = NULL.. char name[20] . } }. int no . structures etc. When using address operator. free ( p ). p ). p = (int *) malloc ( sizeof( int ) ). *q . Ex : int a = 20 . Dynamic memory allocation means allocating memory using functions like malloc() and calloc(). if( p == NULL ) calloc ( ) is used for allocating memory space { during the program execution for derived data types printf(³Out of memory\n´). 35 * sizeof ( book ) ). such as arrays. exit(-1). sizeof ( book ) ). the address of a variable is assigned to a pointer. Modifies the size of previously allocated memory to new size. Memory is assigned at run time.

argc ). i .exe User value 1 : welcome User value 2 : to User value 3 : c-programming . argv [0] ). Other character functions in <ctype. i < argc . tolower ( ) ± converts to lowercase. toascii ( ) ± converts greater than 127 to with in the range 0 ± 127 output Compile the program : c:\>tcc cmdline. printf(³\nName of Program : %s³.c int main( int argc . argv [ i ] ).h> toupper( ) ± converts to uppercase.c c:\>cmdline welcome to c-programming c:\>Number of arguments : 4 Name of Program : c:\cmdline. for ( i = 1. i++ ) printf(³\nUser value %d : %s ³.Standard Character Functions Classification of Characters control iscntrl ( ) space isspace ( ) alpha-numeric isalnum ( ) alphabetic isalpha( ) upper isupper ( ) digit isdigit () lower islower () printable isprint ( ) graphical isgraph () punctuation ispunct ( ) } Command Line Arguments File Name : cmdline. printf(³Number of arguments : %d³. char* argv [ ]) { int i .

Allocate u bytes of new memory to the pointer variable p. Initialize the random number generator. Allocate memory to an array u1. Free block of memory. each of length u2 bytes. Closes all files and buffers. <time. and terminate the program. Allocate u bytes of memory. Converts date and time into ascii. Pass command string to the operating system.h> int atoi(s) long atol(s) float atof(s) void* calloc(u1.t2) Returns clock ticks since program starts.u2) void exit(u) void free (p) void* malloc (u) int rand(void) void* realloc(p. Sets time. Return a random positive integer. Converts string s to a double-precision quantity.u) void srand(u) void systerm(s) Converts string s to an integer Converts string s to a long integer. Gets time of day.Standard C-Library Functions <stdlib.h> clock_t clock() char *asctime(stuct tm) int stime(time_t *tp) time_t time(time_t *timer) double difftime(t1. . Returns difference time between two times t1 and t2.

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->