String handling functions in C

Like numbered arrays, C handles character arrays (strings).

  1. Each string is identified as a character array and ends with a ‘\0’(null) character (the compiler automatically adds the null character). So the end of string is identified as a null character.
  2. Being an array, all the elements of the string array stored in continuous memory locations

following is the declaration of character array

char name[50];

or

char name[]=”Pradeep Kumar”;

or

char name[20]=”Hello Pradeep”;

Strings can be handled or manipulated through loops or library functions. There are some library functions to handle strings are available at string.h

Some of them are

strlen(string) 

  • This is to find the length of the string and returns an integer
  • For example, if “Hello” is the string, the length will be 5 and “Hello “, the length is 6 (there is a blank space after o in hello)

strcat(String1, string2)

  • to concatenate two strings
  • One string will be appended to another string (the concatenation happens by inserting the new string at the null character ‘\0’ of the first string)
  • Example, if String1 is “Hello” and String2 is “Pradeep”, then strcat(string1, string2) will be “HelloPradeep”
  • Similarly,  if String1 is “Hello ” and String2 is “Pradeep”, then strcat(string1, string2) will be “Hello Pradeep”

strcpy(Destination, source)

  • This function is to copy one string to other
  • usually the copying string will be the 2nd parameter and copied string will be the first parameter
  • Example, if string1 is “Bad” and string2 is “Good” the strcpy(string1,string2) will give Good for string1

strcmp(Destination, source)

  • This function is to compare two strings whether they are equal or not
  • like numbers, two strings should not be compared directly like if(a==b)
  • If both the strings are equal, the function returns 0, else it will return the difference of ASCII value of the first non matching characters
  • Example, strcmp(“Their”, “There”) will return ASCII(i) – ASCII(r) (an integer will be returned)

Example Program

//program to demonstrate string handling functions
#include <stdio.h>
#include <conio.h>
int main()
{
    char a[50];
    char b[50];
    printf("Please the two strings one by one\n");
    gets(a);
    gets(b);
    printf("Length of String a is %d \n",strlen(a));
    printf("Length of String b is %d \n",strlen(b));
    if(!strcmp(a,b))  //Comparing two string will return 0, ! before strcmp() is needed
    printf("Both the strings are Equal");
    else
    printf("Both the strings are not equal");
    strcat(a,b);  //Concatenation function
    printf("the concatenated String is:");
    puts(a);
    strrev(a);
    printf("The reverse string is\n");
    puts(a);
    getch();
    return 0;
}
   
   

In the above program , instead of gets() function, scanf() can be used, but the disadvantage of scanf() being it truncates the blank space, new line, form feed, tab.

So for example, if the input give is “Hello pradeep”, then Hello only will be accepted, the string after the blank space will be omitted by the compiler, so gets() can be used.

Similarly, puts() or printf() can be used to display strings.

Passing entire structure to a function

  1. A function can accept a structure as a parameter and even it returns a parameter too.
  2. Either the individual structure elements can be passed or the entire structure can be passed.

Here is the example, for passing the entire structure to a function

#include <stdio.h>
#include <conio.h>

//Structure declaration

struct student
{
char name[10];
int no;
};

//Function prototypes

void read(struct student);
struct student display(struct student); //function which takes the entire structure as a parameter and it returns a structure also

int main()
{
    struct student s1,s;
     printf("Enter the details");
    scanf("%s %d",s1.name,&s1.no);
    s=display(s1);  //function call
printf("Name is %s and number is %d",s.name,s.no);
    getch();
}

//Function definition

struct student display(struct student s)
{
return s;
}

Nested Structures

A structure can be declared within another structure.

Example include: for a student structure maintaining the date of birth is tougher within the structure,

to avoid the complexity, dateofbirth can be a separate structure as defined below

struct dateofbirth
{
int date;
int month;
int year;
};

struct student
{
char name[50];
int no;
struct dateofbirth dob;
};

so the structure can be accessed using the following:

s.dob.date, s.dob.month, s.dob.year, and s.name, s.no

Example of Nested Structures

 

#include <stdio.h>
#include <conio.h>

//declare the structure dateofbirth which holds date,month and year

struct dateofbirth
{
int date;
int month;
int year;
};

//declare another structure student which also includes dateofbirth as a datatype

struct student
{
char name[50];
int no;
struct dateofbirth dob; //from another structure
};

int main()
{
struct student s;
printf("Enter the name number and date of birth (dd/mm/yyyy)");
scanf("%s %d %d/%d/%d",s.name,&s.no,&s.dob.date,&s.dob.month,&s.dob.year);
printf("%s %d %d/%d/%d",s.name,s.no,s.dob.date,s.dob.month,s.dob.year);
getch();
return 0;
}

It is always nice to include nested structures in applications as good readability is provided

for Example: building.concrete.cement.quality

Structures in C Programming

  1. Structure in C groups different data type under a common name
  2. struct is a keyword to declare a structure
  3. The size of the structure depends on the size of the different data types
  4. Structure declaration always ends with a semicolon

Example:

struct employee

{

char name[50];

int empid;

float salary;

};

The total size occupied by the above structure is 50 + 2 + 4 = 56 bytes (on TC compiler) and 50 + 4 + 4= 58 (on other compilers like GCC, etc). Again the size depends on the compiler.

GCC compiler always increase the size of structure which is divisible by 4 for faster code generation, so the above structure takes 60 bytes of memory

  1. Declaring a structure does not consume any memory, only when the structure object is created memory occupies
  2. Variables initialization will not be done during the structure declaration

The above syntax declaration does not consume memory, but the following do

int main()

{

struct employee e1;

}

Now e1 consumes memory of 60 bytes.

Simple Structure to get some details and print them to the screen

// GCC Compiler under windows 64bit

#include <stdio.h>
#include <conio.h>

/*  structures are declared outside any functions,
so that all the functions in the program can have access to it
*/
struct employee
{
       char name[50];
       int empid;
       float salary;
};

int main()
{
    struct employee e1;
    printf("enter the name, id and salary");
    scanf("%s %d %f",e1.name, &e1.empid, &e1.salary); 

    printf("The details entered are \n");
    printf("%s %d %f",e1.name, e1.empid, e1.salary);
    getch();
    return 0;
}

In the above program name, empid and salary are part of employee, so it should be associated with the member of structure, that’s why e1.name, e1.empid and e1.salary.

 

Array of Structures

//the following program gets the inputs of 3 employees like name, id and salary and compute the total salary taken by all the employees

#include <stdio.h>
#include <conio.h>

/*  structures are declared outside any functions,
so that all the functions in the program can have access to it
*/
struct employee
{
       char name[50];
       int empid;
       float salary;
};

int main()
{
    struct employee e[3];
    int i;
    float sum=0;
    printf("enter the name, id and salary");
    for(i=0;i<3;i++)
    {
    scanf("%s %d %f",e[i].name, &e[i].empid, &e[i].salary);
    sum=sum+e[i].salary;
    }
   
   
    printf("The details entered are \n");
    for(i=0;i<3;i++)
    printf("%s %d %f",e[i].name, e[i].empid, e[i].salary);
    printf("Total Salary of all 3 employees is %f",sum);
    getch();
    return 0;
}

Sample Output

Clipboard02

 

Arrays within Structures

//The following program gets the 2 student inputs like 3 subject marks and compute the total of all three subject marks

#include <stdio.h>
#include <conio.h>

/*  structures are declared outside any functions,
so that all the functions in the program can have access to it
*/
struct student
{
       int subjects[3];
       float total;
};

int main()
{
    struct student s[2];
    int i,j;

    printf("enter the 3 subject marks");
    for(i=0;i<2;i++)
    {
    s[i].total=0;
    for(j=0;j<3;j++)
    {
    scanf("%d",&s[i].subjects[j]);
    s[i].total += s[i].subjects[j];
    }
    printf("The total marks scored by student%d is %f",i+1,s[i].total);
    }
   
    getch();
    return 0;
}

Sample Output

clip2

C Program–Multiplying two matrices

/* Program to multiply two matrices */

#include <stdio.h>
#include <conio.h>
int main()
{
    int a[2][3],b[3][2],c[2][2],k,j,i;
    printf("enter a");
    for(i=0;i<2;i++)   //Get array A
    {
    for(j=0;j<3;j++)
    {
    scanf("%d",&a[i][j]); 
    }
    }
    printf("enter b");
    for(i=0;i<3;i++) //Get array B
    {
    for(j=0;j<2;j++)
    {
    scanf("%d",&b[i][j]);
    }
    }


    for(i=0;i<2;i++) 
    {
    for(j=0;j<2;j++)
    {
    c[i][j]=0;  //to Hold a temporary multiplication
    for(k=0;k<3;k++)
    {
    c[i][j]=c[i][j]+a[i][k]*b[k][j];   //Multiplication algorithm
    }
    }
    }
    printf("C is ");
    for(i=0;i<2;i++)
    for(j=0;j<2;j++)
    printf(" c[%d][%d] - %d \n",i,j,c[i][j]); 
 
getch();  
    return 0;
}

arraymul

C Program–Adding two matrices

/* Program to add two matrices */

#include <stdio.h>
#include <conio.h>
int main()
{
    int a[10][10], b[10][10],c[10][10],i,j;
    printf("Enter a");
    for(i=0;i<2;i++)  //get the matrix A
        for(j=0;j<2;j++)
    scanf("%d",&a[i][j]);
    printf("Enter b");
    for(i=0;i<2;i++) //get the matrix B
        for(j=0;j<2;j++)
    scanf("%d",&b[i][j]);
   
    for(i=0;i<2;i++)
    {
        for(j=0;j<2;j++)
        {
        c[i][j] = a[i][j] +b[i][j];    //adding two matrices
        }
    }
    printf("Added Matrix is \n");
    for(i=0;i<2;i++)
        for(j=0;j<2;j++)
    printf("%d ",c[i][j]);
        getch();
        return 0;
}

arrayadd

How to interpret the NS2 tracefile (manually) for wireless simulation

Assume you created a tcl file for a wireless simulation and it generates a trace file (usually .tr as extension). If any tracing softwares are not available, how to interpret manually, here is the step

ACTION: [s|r|D]: s -- sent, r -- received, D – dropped


WHEN: the time when the action happened


 

WHERE: the node where the action happened


LAYER: AGT -- application,


RTR -- routing,
LL -- link layer (ARP is done here)
IFQ -- outgoing packet queue (between link and mac layer)
MAC -- mac,
PHY – physical

 

 

flags:

 

SEQNO: the sequence number of the packet


 

TYPE: the packet type
cbr -- CBR data stream packet
DSR -- DSR routing packet (control packet generated by routing)
RTS -- RTS packet generated by MAC 802.11
ARP -- link layer ARP packet


SIZE: the size of packet at current layer, when packet goes down, size increases, goes up size decreases
[a b c d]: a -- the packet duration in mac layer header
b -- the mac address of destination
c -- the mac address of source
d -- the mac type of the packet body


flags:

[......]: [
source node ip : port_number
destination node ip (-1 means broadcast) : port_number
ip header ttl
ip of next hop (0 means node 0 or broadcast)
]




So we can interpret the below trace

s 0.0297823400 _1_ RTR --- 2012 cbr 32 [0 0 0 0] ------- [1:0 0:0 32 0]


as Application 0 (port number) on node 1 sent a CBR packet whose ID is 2012 and size is 32 bytes, at time 0.029 second, to application 0 on node 0 with TTL is 32 hops. The next hop is not decided yet.



And we can also interpret the below trace



r 0.010176954 _9_ RTR  --- 1 gpsr 29 [0 ffffffff 8 800] ------- [8:255 -1:255 32 0]


in the same way, as The routing agent on node 9 received a GPSR broadcast (mac address 0xff, and ip address is -1, either of them means broadcast) routing packet whose ID is 1 and size is 19 bytes, at time 0.010176954 second, from node 8 (both mac and ip addresses are 8), port 255 (routing agent).



This link has been taken for reference from http://ns-2.blogspot.com/2007/06/how-to-interprete-ns2-tracefile-for.html

C Program–To search a number in a given array

//This program is to search a given number in an array
#include <stdio.h>
#include <conio.h>

int main()
{
    int a[10],i,num;
    printf("enter the array elements");
    for(i=0;i<10;i++) //get all the numbers
    scanf("%d",&a[i]);
    printf("Enter the number to search");
    scanf("%d",&num);
    for(i=0;i<10;i++)
    {
                     if(a[i]==num) //given num is matched in the array
                     {
                     printf("The number is found in the %d position",i+1);
                     getch();
                     exit(0); //to go the end of the program
                     }
    }
printf("The number is not found"); //if num not found, this will be displayed
getch();
return 0;
}

C Program–To sort a Given set of numbers in ascending order (Bubble Sort)

/* Program to sort the given set of numbers in
ascending order, this sorting is called as bubble sort algorithm
*/

#include <stdio.h>
#include <conio.h>
int main()
{
    int a[10],i,j,temp=0;
    printf("Enter all the 10 numbers");
    for(i=0;i<10;i++)
    scanf("%d",&a[i]);
    for(i=0;i<10;i++)  //This loop is for total array elements (n)
    {
    for(j=0;j<9;j++) //this loop is for total combinations (n-1)
    {
                    if(a[j]>a[j+1]) //if the first number is bigger then swap the two numbers
                    {
                    temp=a[j];
                    a[j]=a[j+1];
                    a[j+1]=temp;
                    }
    }
    }
printf("The ordered array is");
for(j=0;j<10;j++) //Finally print the ordered array
printf("%d \t",a[j]);
getch();
return 0;
}