SlideShare a Scribd company logo
1 of 16
/* Ranking of 60 students in a class */
int main() {                                         Array & its Advantage
         /*declaring 60 varialbes */
   int score0, score1,score2,……,score59;       score0                               scores[0]
        /* Reading scores for sixty times */   score1                               scores[1]
   printf(“Enter the score : “);               score2                               scores[2]
   scanf(“%d”, &score0);
         …. …. …. ….                           score3                               scores[3]
   printf(“Enter the score : “);                  .                                     .
   scanf(“%d”, &score59);                         .                                     .
     /* comparing & swapping for 1770 times
      * to arrange in descending order */
                                               score59                              scores[59]
   swap( score0, score1);
   swap( score1, score2);                                     Sixty variables are replaced by one Array
   swap( score2, score3);                      #include<stdio.h>
         …. …. …. ….                           int main() {                                   Sixty input
    swap( score0,score1);                         int scores[60] , i , j, temp;             statements are
    swap( score1,score2);                         for(i = 0; i < 60 ;i++) {               called by one loop
    swap( score0,score1);                             printf("Enter the score : ");           statement
      /*printing 60 scores after sorting */           scanf("%d", &scores[i]);
    printf(“%4d”, score0);                        }
    printf(“%4d”, score1);                        for(i=0;i<(60-1);i++)                       1770 comparing
          … … … …                                   for( j=0; j <(60 -(i+1)); j++)             statements are
}                                                     if(scores[ j ] < scores[ j +1]) {        included in one
void swap ( int a, int b) {                                temp = scores[ j ];                 loop statement
     int temp;                                             scores[ j ] = scores[ j +1];
     if( a < b) {                                          scores[ j + 1] = temp;
         temp = a ; a = b ; b = temp;                 }
     }                                            for( i = 0; i < 60; i ++) printf("%4d", scores[i]);
}                                              }
scores[0]         scores[1]           scores[2]           scores[3]      scores[4]



                                                                                              ...
     4022     4023     4024       4025      4026        4027   4028    4029   4030   4031   ( memory
                                                                                            addresses)
   start here                            scores Array
Mean can be calculated only after reading all scores. Each deviation is difference of individual score and
           mean. To calculate deviations of all scores, scores must be stored in an ARRAY.
                                                                                                Accessing
                           Declaration of Array                                                an element

                              Initialization of Array




                Input to an element
                                                                      Processing on Array
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.
These are also called scalar variables.
 Integer takes 2 bytes memory as a single unit to store its value. i.e.,the value of a scalar variable
cannot be subdivided into a more simpler data items.
 The address of first byte is the address of a variable .
Vector Variables (arrays):
 In contrast, an array is multivariable (an aggregate data type), which is also referred to a data
structure. It represents a collection of related data items of same type.
An individual data item of an array is called as ‘element’. Every element is accessed by index or
subscript enclosed in square brackets followed after the array name.
 All its elements are stored in consecutive memory locations, referred under a common array name.

             Ex : int marks[10] ; /* declaration of array */
 ‘0’ is first number in computer environment. The first element of array marks is marks[0] and last
element is marks[9]. (the address of first element is the address of the array)
 An array is a derived data type. It has additional operations for retrieve and update the individual
values.
 The lowest address corresponds to the first element and the highest address to the last element.
 Arrays can have from one to several dimensions. The most common array is the string, which is
simply an array of characters terminated by a null.
Declaration of One Dimensional Arrays                               Elements of
Syntax :                                                                  Array [3] by [4]
    arrayType arrayName [ numberOfElements ];
Example :
  int scores [60];
                                                                 [0][0]    [0][1]   [0][2]   [0][3]
  float salaries [20];
Initialization of Array while Declaration :                      [1][0]    [1][1]   [1][2]   [1][3]
  int numbers [ ] = { 9, 4, 2, 7, 3 };
                                                                 [2][0]    [2][1]   [2][2]   [2][3]
  char name[ ] ={‘R’,’a’,‘v’,‘i’,‘ ‘,‘T’,‘e’,‘j’,’a’,’0’ };
  char greeting[ ] = “Good Morning”;
       Declaration of Multi Dimensional Arrays                 /*passing an array to function */
Syntax :                                                       #define SIZE 10
  arrayType arrayName [ Rows ][ Columns ];                     int main() {
  arrayType arrayName [ Planes][ Rows ][ Columns ];               float list[SIZE] ,avg;
Example :                                                            ……………
        /* Each student for seven subjects */
                                                                  avg = average(SIZE , list );
  int marks[60][7];
 /* Matrix with 3 planes and 5 rows and 4 columns */
                                                                     ……………
  float matrix[3][5][4];                                       }
Initialization of Array while Declaration :                    float average( int n , float x[]) {
  int matrix [ ][ ] = { { 4, 2, 7, 3 } ,                          float sum=0,i;
                        { 6, 1, 9, 5 } ,                           for( i = 0; i < n ; i++)
                        { 8, 5, 0, 1 } };                            sum = sum + x[i];
                                                                   return ( sum / n ) ;
                                                               }
Strings - One Dimensional Character Arrays
       A String is sequence of characters. 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”;                 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] ;
scanf(“%s”, name); /*reading a string until a white space is encountered ( & operator is not required )*/
printf(“%s”, name); /*printing a string in input window */
gets(name) ; /* reading a string including white spaces until ‘n’ is encountered. */
puts(name); /* printing a string and moves cursor to new line */


                                         String Manipulation Functions in <string.h>
  strlen(s1)                - returns the length of string excluding the last ‘null’ character.
  strcpy(s1,s2)             - copies characters in s2 into s1.
  strcat(s1,s2)- concatenates s2 to s1.
  strcmp(s1,s2)             -compares s1 with s2 lexicographically and returns ‘0’ if two strings are
                            same , returns -1 if s1 is before s2 and returns +1 if s1 is after s2.
  strcmpi(s1,s2)            -compares s1 with s2 like strcmp() but case of characters is ignored.
  strchr(s1,ch)             -returns pointer to first occurrence of the character ‘ch’ in s1.
  strstr(s1,s2) -returns pointer to first occurrence s2 in s1.
  strrev(s1)                -returns pointer to the reversed string.
Memory Address : Bit is a smallest unit of memory to store either ‘0’ or ‘1’ in memory.
Byte is unit of memory of 8 bits. Memory is a sequence of a large number of memory
locations , each of which has an address known as byte. Every byte in memory has a
sequential address number to recognized by processor.

                         Memory Sections of C-Runtime
       RAM is temporary storage place to run programs. C-Language runtime also utilizes an
allotted memory block in RAM to run its programs.
Text Section : Memory-area that contains the machine instructions(code).It is read
           only and is shared by multiple instances of a running program.
Data Section : Memory image of a running program contains storage for initialized
           global variables, which is separate for each running instance of a program.
BSS (Below Stack Segment) : Memory area contains storage for uninitialized global
variables. 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 also stores memory address of the instruction           which is the
function call, to return the value of called function.
Heap :      This memory region is reserved for dynamically allocating memory for
variables at run time. Dynamic Memory Allocation calculate the required             memory size
while program is being executed.
Shared Libraries: This region contains the executable image of shared libraries
being used by a program.
Two or more Permanent Manipulations using one Function
          Passing Parameters By Value                Passing Parameters By Reference

/* program to swap two numbers */         /* program to swap two numbers */
#include<stdio.h>                         #include<stdio.h>
void swap(int x, int y)                   void swap(int *x, int *y)
{                                         {
    int temp;                                 int temp;
    temp = x; x = y; y = temp;                temp = *x; *x = *y; *y = temp;
    printf(“nIn swap() : %d %d “,x,y);       printf(“nIn swap() : %d %d “,*x,*y);
}                                         }
int main()                                int main()
{                                         {
  int a = 25,b = 37;                        int a = 25,b = 37;
  printf(“Before swap() : %d %d”,a,b);      printf(“Before swap() : %d %d”,a,b);
  swap (a,b);                               swap (&a , &b);
  printf(“nAfter swap() : %d %d“,a,b);     printf(“nAfter swap() : %d %d“,a,b);
}                                         }




Output :                                    Output :
Before swap() 25 37                         Before swap() 25 37
In swap ()    37 25                         In swap ()    37 25
After swap() 25 37                          After swap() 37 25
Pointer variable – A variable holds the address of another variable

                          Allots some memory location               Value in ‘option’
                                4042 (for example)
  char option = ‘Y’;         with a name option and                           ‘Y’
                              stores value ‘Y’ in it
                                                                            option
                       Memory Address of variable ‘option’               4042

                            Creates a pointer variable
                                with a name ‘ptr’
char *ptr = NULL;               Which can hold a
                                Memory address                                  ptr

                            Memory address of            4042                      ‘Y’
ptr = &option;               Variable ‘option’
                             Is copied to the                                    option
                                                             ptr
                                Pointer ‘ptr’
                                                                             4042
                                The value ‘N’ is
*ptr = ‘N’;                  stored in the variable          4042                      ‘N’
                                which has the                                         option
                               memory address                 ptr
                                      4042                                      4042
Program with Using Pointers
  int main() {              pointer variables are declared
     int n1, n2 ;
                                                                n1          n2
     int *p = NULL, *q = NULL;
     n1 = 6 ;                                                   p           q NULL
                                      Prints 6 6                     NULL
     p = & n1;
     printf (“%d %d”, n1,*p );
                                       Prints address of n1
      printf (“%ld %ld”,&n1, p );                               n1    6     n2    3

                                                                p           q
      q = & n2;                         Prints 6 3
      *q = 3 ;
      printf (“ %d %d “, *p , *q ) ;
                                                                n1    6     n2    3
      p = q;            pointer ‘q’ assigned with pointer ‘q’
      printf (“ %d %d “, *p , *q ) ;                            p           q

                                         Prints 3 3
      *p = 7 ;                                                  n1    6      n2   7
      printf (“ %d %d “, *p , *q ) ;
  }                                                             p            q
                                        Prints 7 7


When two pointers are referencing with one variable, both pointers contains address of the
same variable, and the value changed through with one pointer will reflect to both of them.
Pointer and Arrays

     Even though pointers and arrays work alike and strongly related,
    they are not synonymous. When an array is assigned with pointer,
    the address of first element of the array is copied into the pointer.

#include<stdio.h>
int main()
                                         Pointer is an address variable, having no
 {
                                         initialized value by default. The address
    int a[3] = { 12, 5 ,7}, b[3];         stored in the pointer can be changed
    int *p ,*q;                                  time to time in the program.
                    Prints 12 12
    p = a;
    printf("%d %dn", *p, *a);
                   Prints 12 12
    q = p;                                  Array name is an address constant,
    printf("%d %d",*p,*q);                initialized with the address of the first
                                         element (base address )in the array. The
                                         address stored in array name cannot be
    b = a; /* error */                            changed in the program.
}
Pointer Arithmetic and Arrays
#include <stdio.h>
int main() {
    int arr [5] = { 12, 31, 56, 19, 42 };
    int *p;
    p = arr + 1;                     Prints 31
                                                         Prints 12 31 56
    printf("%d n", *p);
    printf("%d %d %dn", *(p-1), *(p), *(p + 1));
    --p;
    printf("%d", *p);                  Prints 12



                        arr[0] or *( arr + 0 )      12     p - 1
                        arr[1] or *( arr + 1 )      31     p
                        arr[2] or *( arr + 2 )      56     p +1
                        arr[3] or *( arr + 3 )      19     p +2
                        arr[4] or *( arr + 4 )      42     p +3


      Subscript operator [ ] used to access an element of array
           implements address arithmetic, like pointer.
Array of Pointers
            The advantage of pointer array is that the length of each row in the array may
   be different. The important application of pointer array is to store character strings
   of different length. Example :
        char *day[ ] = { “Sunday”, “Monday”, ”Tuesday”, “Wednesday”, “Thursday”,
                                “Friday”, “Saturday” };

                              Pointer to Pointer ( Double indirection )
 Example :
   int a = 25;                                                 a                      pa                      ppa
   int *pa = &a;
   int **ppa ;                                                 25                    4024                     4056
   *ppa = &pa;
   printf(“%d”, *pa);  prints 25                                                    4056                     4078
                                                              4024
   printf(“%d”, **ppa);  prints 25

                              Two Dimensional Array -- 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 )
void Pointer                                       Function Pointers
        ‘void’ type pointer is a generic              Function pointers are pointers, which
 pointer, which can be assigned to any              point to the address of a function.
 data type without cast during                      Declaration :
 compilation or runtime. ‘void’ pointer              <return type> (* function_pointer)
 cannot be dereferenced unless it is                          (type1 arg1, type2 arg2, ……. );
 cast.
                                                    int add ( int a, int b ) { return (a + b) ; }
int main( ) {                                       int sub ( int a, int b ) { return (a – b) ; }
   void* p;
   int x = 7;                                       int (*fp ) (int, int ) ; /* function pointer */
   float y = 23.5;
   p = &x;                                          int main( ) {
   printf(“x contains : %dn”, *( ( int *)p) );        fp = add;
   p = &y;                                             printf(“Sum = %dn”, fp( 4, 5 ) ) ;
   printf(“y contains : %fn”, *( ( float *)p) );      fp = sub;
}                                                      printf(“Difference = %dn”, fp( 6 , 2 ) ) ;
                                                    }

  Output :
  x contains 7                                         Output :
  y contains 23.500000                                 Sum = 9
                                                       Difference = 4
Dynamic Memory Allocation (DMA) of pointers

    Static memory allocation means allocating memory by compiler. When using address operator,
    the address of a variable is assigned to a pointer. Ex : int a = 20 ; int *p = &a ;

    Dynamic memory allocation means allocating memory using functions like malloc() and calloc().
    The values returned by these functions are assigned to pointer variables only after execution of
    these functions. Memory is assigned at run time.

int main()                              Allocates memory in bytes and returns the address of first
{                                                       byte to the pointer variable
    int *p, *q ;
    p = (int *) malloc ( sizeof( int ) );            Releases previously allocated memory space.
    if( p == NULL )
    {                                                     calloc ( ) is used for allocating memory space
        printf(“Out of memoryn”);                 during the program execution for derived data types
                                                   such as arrays, structures etc.,
        exit(-1);
                                                   Example :
    }                                               struct book {
    printf(“Address in p : %d“, p );                   int no ; char name[20] ; float price ;
                                                   };
     free ( p );                                   struct book b1 ;
     p = NULL;                                      b1 *ptr ;
}                                                   ptr = (book *) calloc ( 10, sizeof ( book ) );


                                                 ptr = (book * ) realloc ( ptr , 35 * sizeof ( book ) );
                                                Modifies the size of previously allocated memory to
                                                                      new size.
Standard Character Functions
                                                                  Command Line Arguments
   Classification of Characters
                                                                File Name : cmdline.c
   control              printable
  iscntrl ( )           isprint ( )                       int main( int argc , char* argv [ ])
                                                          {
                                                             int i ;
             space                    graphical
          isspace ( )                 isgraph ()             printf(“Number of arguments : %d“, argc );
                                                             printf(“nName of Program : %s“, argv [0] );
                alpha-numeric              punctuation
                                                              for ( i = 1; i < argc ; i++ )
                  isalnum ( )               ispunct ( )        printf(“nUser value %d : %s “,
                                                                                            i , argv [ i ] );
     alphabetic                 digit                     }
      isalpha( )              isdigit ()

                                                              output
  upper                   lower
isupper ( )             islower ()                        Compile the program :
                                                          c:>tcc cmdline.c
                                                          c:>cmdline welcome to c-programming
Other character functions in <ctype.h>                    c:>Number of arguments : 4
                                                          Name of Program : c:cmdline.exe
toupper( ) – converts to uppercase.                       User value 1 : welcome
tolower ( ) – converts to lowercase.                      User value 2 : to
toascii ( ) – converts greater than 127 to                User value 3 : c-programming
              with in the range 0 – 127
Standard C-Library Functions
                                                <stdlib.h>
int atoi(s)                  Converts string s to an integer
long atol(s)                 Converts string s to a long integer.
float atof(s)                Converts string s to a double-precision quantity.
void* calloc(u1,u2)          Allocate memory to an array u1, each of length u2 bytes.
void exit(u)                 Closes all files and buffers, and terminate the program.
void free (p)                Free block of memory.
void* malloc (u)             Allocate u bytes of memory.
int rand(void)               Return a random positive integer.
void* realloc(p,u)           Allocate u bytes of new memory to the pointer variable p.
void srand(u)                Initialize the random number generator.
void systerm(s)              Pass command string to the operating system.

                                                 <time.h>
clock_t clock()              Returns clock ticks since program starts.
char *asctime(stuct tm)      Converts date and time into ascii.
int stime(time_t *tp)        Sets time.
time_t time(time_t *timer)   Gets time of day.
double difftime(t1,t2)       Returns difference time between two times t1 and t2.

More Related Content

What's hot

Swift for TensorFlow - CoreML Personalization
Swift for TensorFlow - CoreML PersonalizationSwift for TensorFlow - CoreML Personalization
Swift for TensorFlow - CoreML PersonalizationJacopo Mangiavacchi
 
C# Summer course - Lecture 3
C# Summer course - Lecture 3C# Summer course - Lecture 3
C# Summer course - Lecture 3mohamedsamyali
 
Core c sharp and .net quick reference
Core c sharp and .net quick referenceCore c sharp and .net quick reference
Core c sharp and .net quick referenceArduino Aficionado
 
Type script by Howard
Type script by HowardType script by Howard
Type script by HowardLearningTech
 
TypeScript by Howard
TypeScript by HowardTypeScript by Howard
TypeScript by HowardLearningTech
 
C# Summer course - Lecture 4
C# Summer course - Lecture 4C# Summer course - Lecture 4
C# Summer course - Lecture 4mohamedsamyali
 
Practical scalaz
Practical scalazPractical scalaz
Practical scalazoxbow_lakes
 
Object Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in PythonObject Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in PythonTendayi Mawushe
 
A limited guide to intermediate and advanced Ruby
A limited guide to intermediate and advanced RubyA limited guide to intermediate and advanced Ruby
A limited guide to intermediate and advanced RubyVysakh Sreenivasan
 
DEF CON 23 - Atlas - fun with symboliks
DEF CON 23 - Atlas - fun with symboliksDEF CON 23 - Atlas - fun with symboliks
DEF CON 23 - Atlas - fun with symboliksFelipe Prado
 

What's hot (19)

Swift for TensorFlow - CoreML Personalization
Swift for TensorFlow - CoreML PersonalizationSwift for TensorFlow - CoreML Personalization
Swift for TensorFlow - CoreML Personalization
 
Java string handling
Java string handlingJava string handling
Java string handling
 
Lecture 7 arrays
Lecture   7 arraysLecture   7 arrays
Lecture 7 arrays
 
C# Summer course - Lecture 3
C# Summer course - Lecture 3C# Summer course - Lecture 3
C# Summer course - Lecture 3
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
 
Python programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphismPython programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphism
 
Python: Basic Inheritance
Python: Basic InheritancePython: Basic Inheritance
Python: Basic Inheritance
 
Core c sharp and .net quick reference
Core c sharp and .net quick referenceCore c sharp and .net quick reference
Core c sharp and .net quick reference
 
Type script by Howard
Type script by HowardType script by Howard
Type script by Howard
 
TypeScript by Howard
TypeScript by HowardTypeScript by Howard
TypeScript by Howard
 
C# Summer course - Lecture 4
C# Summer course - Lecture 4C# Summer course - Lecture 4
C# Summer course - Lecture 4
 
Practical scalaz
Practical scalazPractical scalaz
Practical scalaz
 
Plc (1)
Plc (1)Plc (1)
Plc (1)
 
Plc (1)
Plc (1)Plc (1)
Plc (1)
 
Object Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in PythonObject Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in Python
 
Fp201 unit4
Fp201 unit4Fp201 unit4
Fp201 unit4
 
ddd+scala
ddd+scaladdd+scala
ddd+scala
 
A limited guide to intermediate and advanced Ruby
A limited guide to intermediate and advanced RubyA limited guide to intermediate and advanced Ruby
A limited guide to intermediate and advanced Ruby
 
DEF CON 23 - Atlas - fun with symboliks
DEF CON 23 - Atlas - fun with symboliksDEF CON 23 - Atlas - fun with symboliks
DEF CON 23 - Atlas - fun with symboliks
 

Viewers also liked

Introduction to Programming with C# Book - книга за C# програмиране
Introduction to Programming with C# Book - книга за C# програмиранеIntroduction to Programming with C# Book - книга за C# програмиране
Introduction to Programming with C# Book - книга за C# програмиранеIntro C# Book
 
Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)EngineerBabu
 
14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining ClassesIntro C# Book
 
Overview of c language
Overview of c languageOverview of c language
Overview of c languageshalini392
 
C Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointC Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointJavaTpoint.Com
 
Basics of C programming
Basics of C programmingBasics of C programming
Basics of C programmingavikdhupar
 
C language (Collected By Dushmanta)
C language  (Collected By Dushmanta)C language  (Collected By Dushmanta)
C language (Collected By Dushmanta)Dushmanta Nath
 

Viewers also liked (9)

Introduction to Programming with C# Book - книга за C# програмиране
Introduction to Programming with C# Book - книга за C# програмиранеIntroduction to Programming with C# Book - книга за C# програмиране
Introduction to Programming with C# Book - книга за C# програмиране
 
Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)
 
14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining Classes
 
08. Numeral Systems
08. Numeral Systems08. Numeral Systems
08. Numeral Systems
 
Overview of c language
Overview of c languageOverview of c language
Overview of c language
 
C Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointC Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpoint
 
Basics of C programming
Basics of C programmingBasics of C programming
Basics of C programming
 
C language ppt
C language pptC language ppt
C language ppt
 
C language (Collected By Dushmanta)
C language  (Collected By Dushmanta)C language  (Collected By Dushmanta)
C language (Collected By Dushmanta)
 

Similar to C Language Unit-3

Similar to C Language Unit-3 (20)

Unit3 C
Unit3 C Unit3 C
Unit3 C
 
Arrays
ArraysArrays
Arrays
 
Arrays In C
Arrays In CArrays In C
Arrays In C
 
VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2
 
Array.pptx
Array.pptxArray.pptx
Array.pptx
 
Array in C.pdf
Array in C.pdfArray in C.pdf
Array in C.pdf
 
Array.pdf
Array.pdfArray.pdf
Array.pdf
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
CSEG1001Unit 3 Arrays and Strings
CSEG1001Unit 3 Arrays and StringsCSEG1001Unit 3 Arrays and Strings
CSEG1001Unit 3 Arrays and Strings
 
C (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxC (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptx
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Arrays
ArraysArrays
Arrays
 
presentation_arrays_1443553113_140676.ppt
presentation_arrays_1443553113_140676.pptpresentation_arrays_1443553113_140676.ppt
presentation_arrays_1443553113_140676.ppt
 
Session 7 En
Session 7 EnSession 7 En
Session 7 En
 
Session 7 En
Session 7 EnSession 7 En
Session 7 En
 
Arrays
ArraysArrays
Arrays
 
Programming Fundamentals Arrays and Strings
Programming Fundamentals   Arrays and Strings Programming Fundamentals   Arrays and Strings
Programming Fundamentals Arrays and Strings
 
Lecture14.pdf
Lecture14.pdfLecture14.pdf
Lecture14.pdf
 
07 Arrays
07 Arrays07 Arrays
07 Arrays
 
Array
ArrayArray
Array
 

More from kasaragadda srinivasrao (8)

C Language Unit-8
C Language Unit-8C Language Unit-8
C Language Unit-8
 
C Language Unit-7
C Language Unit-7C Language Unit-7
C Language Unit-7
 
C Language Unit-6
C Language Unit-6C Language Unit-6
C Language Unit-6
 
C Language Unit-5
C Language Unit-5C Language Unit-5
C Language Unit-5
 
C Language Unit-4
C Language Unit-4C Language Unit-4
C Language Unit-4
 
C-Language Unit-2
C-Language Unit-2C-Language Unit-2
C-Language Unit-2
 
C Language Unit-1
C Language Unit-1C Language Unit-1
C Language Unit-1
 
Coupon tango site demo
Coupon tango site demoCoupon tango site demo
Coupon tango site demo
 

Recently uploaded

Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 

Recently uploaded (20)

Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 

C Language Unit-3

  • 1. /* Ranking of 60 students in a class */ int main() { Array & its Advantage /*declaring 60 varialbes */ int score0, score1,score2,……,score59; score0 scores[0] /* Reading scores for sixty times */ score1 scores[1] printf(“Enter the score : “); score2 scores[2] scanf(“%d”, &score0); …. …. …. …. score3 scores[3] printf(“Enter the score : “); . . scanf(“%d”, &score59); . . /* comparing & swapping for 1770 times * to arrange in descending order */ score59 scores[59] swap( score0, score1); swap( score1, score2); Sixty variables are replaced by one Array swap( score2, score3); #include<stdio.h> …. …. …. …. int main() { Sixty input swap( score0,score1); int scores[60] , i , j, temp; statements are swap( score1,score2); for(i = 0; i < 60 ;i++) { called by one loop swap( score0,score1); printf("Enter the score : "); statement /*printing 60 scores after sorting */ scanf("%d", &scores[i]); printf(“%4d”, score0); } printf(“%4d”, score1); for(i=0;i<(60-1);i++) 1770 comparing … … … … for( j=0; j <(60 -(i+1)); j++) statements are } if(scores[ j ] < scores[ j +1]) { included in one void swap ( int a, int b) { temp = scores[ j ]; loop statement int temp; scores[ j ] = scores[ j +1]; if( a < b) { scores[ j + 1] = temp; temp = a ; a = b ; b = temp; } } for( i = 0; i < 60; i ++) printf("%4d", scores[i]); } }
  • 2. scores[0] scores[1] scores[2] scores[3] scores[4] ... 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 ( memory addresses) start here scores Array Mean can be calculated only after reading all scores. Each deviation is difference of individual score and mean. To calculate deviations of all scores, scores must be stored in an ARRAY. Accessing Declaration of Array an element Initialization of Array Input to an element Processing on Array
  • 3. 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. These are also called scalar variables.  Integer takes 2 bytes memory as a single unit to store its value. i.e.,the value of a scalar variable cannot be subdivided into a more simpler data items.  The address of first byte is the address of a variable . Vector Variables (arrays):  In contrast, an array is multivariable (an aggregate data type), which is also referred to a data structure. It represents a collection of related data items of same type. An individual data item of an array is called as ‘element’. Every element is accessed by index or subscript enclosed in square brackets followed after the array name.  All its elements are stored in consecutive memory locations, referred under a common array name. Ex : int marks[10] ; /* declaration of array */  ‘0’ is first number in computer environment. The first element of array marks is marks[0] and last element is marks[9]. (the address of first element is the address of the array)  An array is a derived data type. It has additional operations for retrieve and update the individual values.  The lowest address corresponds to the first element and the highest address to the last element.  Arrays can have from one to several dimensions. The most common array is the string, which is simply an array of characters terminated by a null.
  • 4. Declaration of One Dimensional Arrays Elements of Syntax : Array [3] by [4] arrayType arrayName [ numberOfElements ]; Example : int scores [60]; [0][0] [0][1] [0][2] [0][3] float salaries [20]; Initialization of Array while Declaration : [1][0] [1][1] [1][2] [1][3] int numbers [ ] = { 9, 4, 2, 7, 3 }; [2][0] [2][1] [2][2] [2][3] char name[ ] ={‘R’,’a’,‘v’,‘i’,‘ ‘,‘T’,‘e’,‘j’,’a’,’0’ }; char greeting[ ] = “Good Morning”; Declaration of Multi Dimensional Arrays /*passing an array to function */ Syntax : #define SIZE 10 arrayType arrayName [ Rows ][ Columns ]; int main() { arrayType arrayName [ Planes][ Rows ][ Columns ]; float list[SIZE] ,avg; Example : …………… /* Each student for seven subjects */ avg = average(SIZE , list ); int marks[60][7]; /* Matrix with 3 planes and 5 rows and 4 columns */ …………… float matrix[3][5][4]; } Initialization of Array while Declaration : float average( int n , float x[]) { int matrix [ ][ ] = { { 4, 2, 7, 3 } , float sum=0,i; { 6, 1, 9, 5 } , for( i = 0; i < n ; i++) { 8, 5, 0, 1 } }; sum = sum + x[i]; return ( sum / n ) ; }
  • 5. Strings - One Dimensional Character Arrays A String is sequence of characters. 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”; 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] ; scanf(“%s”, name); /*reading a string until a white space is encountered ( & operator is not required )*/ printf(“%s”, name); /*printing a string in input window */ gets(name) ; /* reading a string including white spaces until ‘n’ is encountered. */ puts(name); /* printing a string and moves cursor to new line */ String Manipulation Functions in <string.h> strlen(s1) - returns the length of string excluding the last ‘null’ character. strcpy(s1,s2) - copies characters in s2 into s1. strcat(s1,s2)- concatenates s2 to s1. strcmp(s1,s2) -compares s1 with s2 lexicographically and returns ‘0’ if two strings are same , returns -1 if s1 is before s2 and returns +1 if s1 is after s2. strcmpi(s1,s2) -compares s1 with s2 like strcmp() but case of characters is ignored. strchr(s1,ch) -returns pointer to first occurrence of the character ‘ch’ in s1. strstr(s1,s2) -returns pointer to first occurrence s2 in s1. strrev(s1) -returns pointer to the reversed string.
  • 6. Memory Address : Bit is a smallest unit of memory to store either ‘0’ or ‘1’ in memory. Byte is unit of memory of 8 bits. Memory is a sequence of a large number of memory locations , each of which has an address known as byte. Every byte in memory has a sequential address number to recognized by processor. Memory Sections of C-Runtime RAM is temporary storage place to run programs. C-Language runtime also utilizes an allotted memory block in RAM to run its programs. Text Section : Memory-area that contains the machine instructions(code).It is read only and is shared by multiple instances of a running program. Data Section : Memory image of a running program contains storage for initialized global variables, which is separate for each running instance of a program. BSS (Below Stack Segment) : Memory area contains storage for uninitialized global variables. 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 also stores memory address of the instruction which is the function call, to return the value of called function. Heap : This memory region is reserved for dynamically allocating memory for variables at run time. Dynamic Memory Allocation calculate the required memory size while program is being executed. Shared Libraries: This region contains the executable image of shared libraries being used by a program.
  • 7. Two or more Permanent Manipulations using one Function Passing Parameters By Value Passing Parameters By Reference /* program to swap two numbers */ /* program to swap two numbers */ #include<stdio.h> #include<stdio.h> void swap(int x, int y) void swap(int *x, int *y) { { int temp; int temp; temp = x; x = y; y = temp; temp = *x; *x = *y; *y = temp; printf(“nIn swap() : %d %d “,x,y); printf(“nIn swap() : %d %d “,*x,*y); } } int main() int main() { { int a = 25,b = 37; int a = 25,b = 37; printf(“Before swap() : %d %d”,a,b); printf(“Before swap() : %d %d”,a,b); swap (a,b); swap (&a , &b); printf(“nAfter swap() : %d %d“,a,b); printf(“nAfter swap() : %d %d“,a,b); } } Output : Output : Before swap() 25 37 Before swap() 25 37 In swap () 37 25 In swap () 37 25 After swap() 25 37 After swap() 37 25
  • 8. Pointer variable – A variable holds the address of another variable Allots some memory location Value in ‘option’ 4042 (for example) char option = ‘Y’; with a name option and ‘Y’ stores value ‘Y’ in it option Memory Address of variable ‘option’ 4042 Creates a pointer variable with a name ‘ptr’ char *ptr = NULL; Which can hold a Memory address ptr Memory address of 4042 ‘Y’ ptr = &option; Variable ‘option’ Is copied to the option ptr Pointer ‘ptr’ 4042 The value ‘N’ is *ptr = ‘N’; stored in the variable 4042 ‘N’ which has the option memory address ptr 4042 4042
  • 9. Program with Using Pointers int main() { pointer variables are declared int n1, n2 ; n1 n2 int *p = NULL, *q = NULL; n1 = 6 ; p q NULL Prints 6 6 NULL p = & n1; printf (“%d %d”, n1,*p ); Prints address of n1 printf (“%ld %ld”,&n1, p ); n1 6 n2 3 p q q = & n2; Prints 6 3 *q = 3 ; printf (“ %d %d “, *p , *q ) ; n1 6 n2 3 p = q; pointer ‘q’ assigned with pointer ‘q’ printf (“ %d %d “, *p , *q ) ; p q Prints 3 3 *p = 7 ; n1 6 n2 7 printf (“ %d %d “, *p , *q ) ; } p q Prints 7 7 When two pointers are referencing with one variable, both pointers contains address of the same variable, and the value changed through with one pointer will reflect to both of them.
  • 10. Pointer and Arrays Even though pointers and arrays work alike and strongly related, they are not synonymous. When an array is assigned with pointer, the address of first element of the array is copied into the pointer. #include<stdio.h> int main() Pointer is an address variable, having no { initialized value by default. The address int a[3] = { 12, 5 ,7}, b[3]; stored in the pointer can be changed int *p ,*q; time to time in the program. Prints 12 12 p = a; printf("%d %dn", *p, *a); Prints 12 12 q = p; Array name is an address constant, printf("%d %d",*p,*q); initialized with the address of the first element (base address )in the array. The address stored in array name cannot be b = a; /* error */ changed in the program. }
  • 11. Pointer Arithmetic and Arrays #include <stdio.h> int main() { int arr [5] = { 12, 31, 56, 19, 42 }; int *p; p = arr + 1; Prints 31 Prints 12 31 56 printf("%d n", *p); printf("%d %d %dn", *(p-1), *(p), *(p + 1)); --p; printf("%d", *p); Prints 12 arr[0] or *( arr + 0 ) 12 p - 1 arr[1] or *( arr + 1 ) 31 p arr[2] or *( arr + 2 ) 56 p +1 arr[3] or *( arr + 3 ) 19 p +2 arr[4] or *( arr + 4 ) 42 p +3 Subscript operator [ ] used to access an element of array implements address arithmetic, like pointer.
  • 12. Array of Pointers The advantage of pointer array is that the length of each row in the array may be different. The important application of pointer array is to store character strings of different length. Example : char *day[ ] = { “Sunday”, “Monday”, ”Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday” }; Pointer to Pointer ( Double indirection ) Example : int a = 25; a pa ppa int *pa = &a; int **ppa ; 25 4024 4056 *ppa = &pa; printf(“%d”, *pa);  prints 25 4056 4078 4024 printf(“%d”, **ppa);  prints 25 Two Dimensional Array -- 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 )
  • 13. void Pointer Function Pointers ‘void’ type pointer is a generic Function pointers are pointers, which pointer, which can be assigned to any point to the address of a function. data type without cast during Declaration : compilation or runtime. ‘void’ pointer <return type> (* function_pointer) cannot be dereferenced unless it is (type1 arg1, type2 arg2, ……. ); cast. int add ( int a, int b ) { return (a + b) ; } int main( ) { int sub ( int a, int b ) { return (a – b) ; } void* p; int x = 7; int (*fp ) (int, int ) ; /* function pointer */ float y = 23.5; p = &x; int main( ) { printf(“x contains : %dn”, *( ( int *)p) ); fp = add; p = &y; printf(“Sum = %dn”, fp( 4, 5 ) ) ; printf(“y contains : %fn”, *( ( float *)p) ); fp = sub; } printf(“Difference = %dn”, fp( 6 , 2 ) ) ; } Output : x contains 7 Output : y contains 23.500000 Sum = 9 Difference = 4
  • 14. Dynamic Memory Allocation (DMA) of pointers Static memory allocation means allocating memory by compiler. When using address operator, the address of a variable is assigned to a pointer. Ex : int a = 20 ; int *p = &a ; Dynamic memory allocation means allocating memory using functions like malloc() and calloc(). The values returned by these functions are assigned to pointer variables only after execution of these functions. Memory is assigned at run time. int main() Allocates memory in bytes and returns the address of first { byte to the pointer variable int *p, *q ; p = (int *) malloc ( sizeof( int ) ); Releases previously allocated memory space. if( p == NULL ) { calloc ( ) is used for allocating memory space printf(“Out of memoryn”); during the program execution for derived data types such as arrays, structures etc., exit(-1); Example : } struct book { printf(“Address in p : %d“, p ); int no ; char name[20] ; float price ; }; free ( p ); struct book b1 ; p = NULL; b1 *ptr ; } ptr = (book *) calloc ( 10, sizeof ( book ) ); ptr = (book * ) realloc ( ptr , 35 * sizeof ( book ) ); Modifies the size of previously allocated memory to new size.
  • 15. Standard Character Functions Command Line Arguments Classification of Characters File Name : cmdline.c control printable iscntrl ( ) isprint ( ) int main( int argc , char* argv [ ]) { int i ; space graphical isspace ( ) isgraph () printf(“Number of arguments : %d“, argc ); printf(“nName of Program : %s“, argv [0] ); alpha-numeric punctuation for ( i = 1; i < argc ; i++ ) isalnum ( ) ispunct ( ) printf(“nUser value %d : %s “, i , argv [ i ] ); alphabetic digit } isalpha( ) isdigit () output upper lower isupper ( ) islower () Compile the program : c:>tcc cmdline.c c:>cmdline welcome to c-programming Other character functions in <ctype.h> c:>Number of arguments : 4 Name of Program : c:cmdline.exe toupper( ) – converts to uppercase. User value 1 : welcome tolower ( ) – converts to lowercase. User value 2 : to toascii ( ) – converts greater than 127 to User value 3 : c-programming with in the range 0 – 127
  • 16. Standard C-Library Functions <stdlib.h> int atoi(s) Converts string s to an integer long atol(s) Converts string s to a long integer. float atof(s) Converts string s to a double-precision quantity. void* calloc(u1,u2) Allocate memory to an array u1, each of length u2 bytes. void exit(u) Closes all files and buffers, and terminate the program. void free (p) Free block of memory. void* malloc (u) Allocate u bytes of memory. int rand(void) Return a random positive integer. void* realloc(p,u) Allocate u bytes of new memory to the pointer variable p. void srand(u) Initialize the random number generator. void systerm(s) Pass command string to the operating system. <time.h> clock_t clock() Returns clock ticks since program starts. char *asctime(stuct tm) Converts date and time into ascii. int stime(time_t *tp) Sets time. time_t time(time_t *timer) Gets time of day. double difftime(t1,t2) Returns difference time between two times t1 and t2.