Array & Pointer & String
Array & Pointer & String
Concept of Arrays
Concept of Pointers
Concept of String
Arrays
# include<stdio.h>
Void main()
{
int num[40],i;
for(i=0;i<=100;i++)
num[i]=i;
}
A Simple Program using
Array
/*Array Initialization*/
# include<stdio.h>
Void main()
{
int avg,sum=0;
int i;
int marks[30];
/*Entering Data into an Array*/
for(i=0;i<29;i++)
{
printf("\nenter marks")'
scanf("%d",&marks[i]);
}
/*Read Data from an Array*/
for(i=0;i<29;i++)
{
sum=sum+marks[i];
avg=sum/30;
printf("\n average marks=%d",avg);
}
Representation of Array elements in
memory Name of array (Note that all elements of
To refer to an element, specify
this array have the same name, c)
Array name
Position number c[0] -45
Format: c[1] 6
arrayname[ position number ] c[2] 0
First element at position 0 c[3] 72
n element array named c: c[4] 1543
c[ 0 ], c[ 1 ]...c[ n – 1 ] c[5] -89
c[6] 0
c[7] 62
c[8] -3
c[9] 1
c[10] 6453
c[11] 78
int a=5;
int * ptr;
ptr=&a;
Use of & and *
When is & used?
When is * used?
int a=50;
int *ptr1;
int **ptr2;
ptr1=&a;
ptr2=&ptr1;
H E L L O \0
void main()
{
char name[]= "Hello"; //initialize String
for(int i=0;i<=4;i++)
printf("%c",name[i]); // print the charecter
}
Output: Hello
String function
Some standard library string function
Strlen(): Find the length of the string.
Strcat(): Appends one string at the end of
another.
Strcpy(): Copies a string into another.
Strcmp(): Compares two strings.
Strrev(): reverse a string.
Function example
Example of strlen():
#include<String.h>
void main()
{
char name[]= "Hello"; // initialize String
int len1,len2; // initialize two veriables
len1= strlen(name); // calculate the lenth of charecter name and store it in veriable len1
len2=strlen("Hello World"); // calculate the lenth of that charecter and store it in veriable len2
printf("\nstring= %s length =%d",name,len1); // Print the length
printf("\nstring= %s length =%d","Hello World",len2); // Print the length
}
Output:
string= Hello length =5
string= Hello World length =11
Function example (cont.)
Example of strrev():
#include<stdio.h>
#include<string.h>
void main()
{
char arr[100];
printf("Enter a string to reverse\n");
gets(arr);
strrev(arr);
printf("Reverse of entered string is ::%s\n",arr);
}
Output: Hello
Reverse of entered string is ::olleH