C exercises and solutions: C pointers


C pointer: exercises (more)

1. Write a C program to accept five integer values from keyword.

The five values will be stored in an array using a pointer. Then print the elements of the array on the screen.
Solution:

#include<stdio.h>
#include<conio.h>  
   int main()
    {
     int arr[5],i;
     int *p=arr;
     printf("Enter five numbers separated by space:");
     scanf("%d%d%d%d%d",p,p+1,p+2,p+3,p+4);
     printf("Your numbers are:\n");
     for(i=0;i<5;i++)
        printf("%d\n",arr[i]);     
     getch();
     return 0;  
    }
 

2. Modify the solution of exercise 1 in order to print the elements of the array in reverse order using a pointer.

Solution:


#include<stdio.h> #include<conio.h>
 
   int main()
    {
     int arr[5],i;
     int *p=arr;
     printf("Enter five numbers separated by space:");
     scanf("%d%d%d%d%d",p,p+1,p+2,p+3,p+4);
     printf("Your numbers are:\n");
     for(i=4;i>=0;i--)
        printf("%d\n",*(p+i));
    
     getch();
     return 0;
 
    }


Comments




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.