1301068321 - TM minggu 2

1301068321 - TM minggu 2 - { char temp[100];int x; for (int...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
David Tanady 1301068321 04PBH 1. Define a function to input a list of names and store them as dynamically-allocated strings in an array, and a function to output them: void ReadNames (char *names[], const int size); void WriteNames (char *names[], const int size); Continued. Write another function which sorts the list using bubble sort: void BubbleSort(char *names[], const int size); Bubble sort involves repeated scans of the list, where during each scan adjacent items are compared and swapped if out of order. A scan that involves no swapping indicates that the list is sorted. void ReadNames (char *names[], const int size) { char name[128]; for (int i = 0; i < size; ++i) { cout << "names[" << i << "] = "; cin >> name; names[i] = new char[strlen(name) + 1]; strcpy(names[i], name); } cout<<endl; } void WriteNames (char *names[], const int size) { for (int i = 0; i < size; ++i) { cout << names[i]<<endl; } cout<<endl; } void BubbleSort (char *names[], const int size)
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: { char temp[100];int x; for (int i = 0; i < size-1 ; i++) { if (strcmp(names[i], names[i+1]) > 0 ) { strcpy(temp,names[i]); strcpy(names[i],names[i+1]); strcpy(names[i+1],temp); } } } void main() { int n;char *name[128]; cout<<"insert size "; cin>>n; cout<<endl; ReadNames(name,n); WriteNames(name,n); BubbleSort(name,n); for (int i = 0; i < n; ++i) { cout << name[i]<<endl; } cout<<endl; } 2. Rewrite the following function using pointer arithmetic: char* ReverseString (char *str) { int len = strlen(str); char *result = new char[len + 1]; for (register I = 0; I < len; ++i) result[i] = str[len – i – 1]; result[len] = ‘\0’; return result; } include<iostream> using namespace std; char* ReverseString (char *str) { int len = strlen(str); char *result = new char[len + 1]; char *res = result + len; *res-- = '\0'; while (*str) *res-- = *str++; return result; }...
View Full Document

This note was uploaded on 11/14/2011 for the course DDDD h0322 taught by Professor Whoknow during the Spring '11 term at Bina Nusantara University.

Page1 / 2

1301068321 - TM minggu 2 - { char temp[100];int x; for (int...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online