Digital जीवन

Free Online Education for India...

Full width home advertisement

Computer Basic

C Programming

Engineering Graphics

Post Page Advertisement [Top]

Dr. A.P.J. Abdul Kalam Technical University, Lucknow

KCS151 / KCS251 Programming for Problem Solving - Using C Language


Lab Exercises


41. Write the following C program using pointer
      a. To sort the list of numbers through pointer.
      b. To reverse the string through pointer.

a. To sort the list of numbers through pointer.

/*
 File: Prgrm41a.c
 Author: Aditya Saini
 Date: Jan 20, 2021
 Description: Program to sort the list of numbers through pointer.
*/

#include <stdio.h>

int main (void)
{
     int ar[20];
     int no_of_elements;
     int key;
     int i, j;

     //Input no of elements
     printf ("Input number of elements: ");
     scanf ("%d", &no_of_elements);

     //Input array
     printf ("Input elements: ");
     for (i = 0; i <= no_of_elements - 1; i++)
          scanf ("%d", &ar[i]);

     //Print Array
     printf ("Array: ");
     for (i = 0; i <= no_of_elements - 1; i++)
          printf ("%d ", ar[i]);

     //Sorting
     for (i = 1; i <= no_of_elements - 1; i++)
     {
          key = *(ar + i);
          for (j = i - 1; j >= 0 && *(ar + j) > key; j--)
               *(ar + j + 1) = *(ar + j);
          *(ar + j + 1) = key;
     }

     //Print Array after sorting
     printf ("\nSorted Array: ");
     for (i = 0; i <= no_of_elements - 1; i++)
          printf ("%d ", ar[i]);

     return 0;
};

Output

Input number of elements: 5
Input elements: 6 9 5 7 2
Array: 6 9 5 7 2
Sorted Array: 2 5 6 7 9


b. To reverse the string through pointer.

/*
 File: Prgrm41b.c
 Author: Aditya Saini
 Date: Jan 20, 2021
 Description: Program to reverse the string through pointer.
*/

#include <stdio.h>

int main (void)
{
     char str[20];
     int length;
     char temp;
     int i, j;

     //Input string
     printf ("Input string: ");
     fflush (stdin);
     gets(str);

     //Calculate string length
     length = 0;
     while (*(str + length) != '\0')
          length++;

     //Reverse string
     for (i = 0; i <= length / 2 - 1; i++)
     {
          temp = *(str + i);
          *(str + i) = *(str + length - 1 - i);
          *(str + length - 1 - i) = temp;
     }

     //Print reverse string
     printf ("Reverse String: ");
     puts (str);

     return 0;
};

Output

Input String: www.digitalg1.com
Reverse String: moc.1glatigid.www




No comments:

Post a Comment

Please do not post spam links.

Bottom Ad [Post Page]

| Designed by Colorlib