Monday, September 11, 2017

CBSE Class 12 - Computer Science - C++ Practical Pointer Handling Snippet-13 Reverse Array of Strings (Pointers)

C++ Practical
Pointer Handling Snippet-13
Reverse Array of Strings (Pointers)  

CBSE Class 12 - Computer Science - C++ Practical Pointer Handling Snippet-13 Reverse Array of Strings (Pointers)


Question: Suppose 7 names are stored in an array of pointers names[] as shown below:

char* names[] = {"Anand", "Naureen", "Banjot", "Wahid", "Sheena", "Shahid", "Sonakshi"};

Write a program to reverse the order of these names


Answer:




// Question: Suppose 7 names are stored in an array of pointers names[] as shown below:
// char* names[] = {"Anand", "Naureen", "Banjot", "Wahid", "Sheena", "Shahid", "Sonakshi"};
// Write a program to reverse the order of these names

#include <iostream.h>
#include <string.h>

void displaynames(char names[7][]);

void main()
{
    char* names[] = {"Anand", "Naureen", "Banjot", "Wahid", "Sheena", "Shahid", "Sonakshi"};
	char tempstr[30];
    //display names before reversing array
    cout << "Array of Names before reverse:\n";
	displaynames();
    
	// reverse array
	for (i = 0; i < 7/2; ++i)
	{
		strcpy(tempstr, names[i]);
		strcpy(names[i], names[7-i-1]);
		strcpy(names[7-i-1], names[i]);
	}
	// display names after reversing array
	displaynames();
}
 
void displaynames(char strArr[7][])
{
	for (int i = 0; i < 7; ++i)
    {
       cout << i << ".\t" << strArr[i] << "\n";
    }
}

 



No comments:

Post a Comment