Lab 1 Week 12
Lab 1 Week 12
Lab 1 Week 12
LAB 1 WEEK 12
Objective
By the end of this lab session, you will be able to:
1. Understand pointers
2. Understand dynamic memory allocation
3. Understand linked list
Activity #1
int num[20];
and using only pointer notation, write a for loop to read integer values from the
keyboard to fill up the array.
Activity #2
int main(void)
{
int a = 6;
int b = 39;
int c[5] = {7,3,12,44,60};
int* poinC = c;
a = play(poinC,a,&b);
printf("1. %d %d %d\n",*poinX,y,*poinZ);
for (p = poinX;p < poinX + 5; p++)
*p = y + *p;
*poinX = 2 * i;
return (*poinZ + *poinX + y);
}
Activity #3
July 2008
TAB1013 Structured Programming
Lab 1 Week 12
Copy, compile, run the code and understand how linked list works.
#include <stdio.h>
#include <conio.h>
#include <malloc.h>
struct node
{
int a;
struct node *next;
};
struct node *create()
{
struct node *p, *r, *n;
int s,k;
s=sizeof(struct node);
printf("Enter the element-1 to stop:");
scanf("%d", &k);
p=r=NULL;
while(k!=-1)
{
n=(struct node *)malloc(s);
n->a=k;
n->next=NULL;
if(r==NULL)
r=n;
else
p->next=n;
p=n;
printf("Enter the element-1 to stop:");
scanf("%d", &k);
}
return(r);
}
void display(r)
struct node *r;
{
printf("\nRoot ");
while(r!=NULL)
{
printf("\t%d", r->a);
r=r->next;
}
printf("\tnull");
}
main()
{
struct node *r;
Activity #4 r=create();
display(r);
getch();
}
July 2008
TAB1013 Structured Programming
Lab 1 Week 12
Copy, compile, run the code and understand how linked list works (insertion and
deletion).
/* self-referential structure */
struct listNode
{
char data; /* each listNode contains a character */
struct listNode *nextPtr; /* pointer to next node*/
}; /* end structure listNode */
/* prototypes */
void insert( ListNodePtr *sPtr, char value );
char delete( ListNodePtr *sPtr, char value );
int isEmpty( ListNodePtr sPtr );
void printList( ListNodePtr currentPtr );
int main()
{
ListNodePtr startPtr = NULL; /* initially there are no nodes */
int choice; /* user's choice */
char item; /* char entered by user */
case 2:
/* if list is not empty */
if (!isEmpty(startPtr))
{
printf("Enter character to be deleted: ");
scanf("\n%c", &item);
July 2008
TAB1013 Structured Programming
Lab 1 Week 12
break;
default:
printf("Invalid choice.\n\n");
printf("Enter your choice:\n");
printf("\t1 to insert an element into the list.\n");
printf("\t2 to delete an element from the list.\n");
printf("\t3 to end.\n\n");
break;
}
printf("Your Choice > ");
scanf("%d", &choice);
}
printf("End of run.\n");
return 0;
}
previousPtr = NULL;
currentPtr = *sPtr;
July 2008
TAB1013 Structured Programming
Lab 1 Week 12
*sPtr = newPtr;
}
else /* insert new node between previousPtr and currentPtr */
{
previousPtr->nextPtr = newPtr;
newPtr->nextPtr = currentPtr;
}
}
else
printf( "%c not inserted. No memory available.\n", value );
} /* end function insert */
July 2008
TAB1013 Structured Programming
Lab 1 Week 12
July 2008