wu :: forums (http://www.ocf.berkeley.edu/~wwu/cgi-bin/yabb/YaBB.cgi)
riddles >> cs >> arrays
(Message started by: brock123 on Jan 2nd, 2005, 5:49am)

Title: arrays
Post by brock123 on Jan 2nd, 2005, 5:49am
Q)
Write a program that calls the function read_char which reads a set of characters into the array lst and returns the number of elements inserted into the array (lst), The input is terminated by entering the end of line character.
The program then reads a character (ch) and an integer (pos) and calls the void function inserts which inserts the character (ch) at a specified position (pos).The new arry (lst) is printed from the main function.


This is the solution:
#include<iostream.h>

int read_char (char lst[])
{
   int i=0;
   char x;
   cout<<"Enter a set of characters :"<<endl;
   cin.get(x);
   while (x!='\n')
   {
      lst[i]=x;
      ++i;
      cin.get(x);
   }
   return i;
}
void inserts (char lst[],char ch,int pos,int & s)
{
   for (int i=s;i>pos;i--)
      lst[i]=lst[i-1];
   lst[pos]=ch;
   s++;
}

int main()
{
   int s;
   int pos;
   char lst[100];
   char ch;
   s=read_char(lst);
   cout<<"number of element into the array is "<<s<<endl;
   cout<<"Enter a character:"<<endl;
   cin>>ch;
   cout<<"Enter the position:"<<endl;
   cin>>pos;
   inserts (lst,ch,pos,s);
   for (int i=0;i<s;i++)
       cout<<lst[i]<<" ";
   return 0;
}


but can you solve this program by another way
especially this part :

void inserts (char lst[],char ch,int pos,int & s)
{
   for (int i=s;i>pos;i--)
      lst[i]=lst[i-1];
   lst[pos]=ch;
   s++;
}

thank you.



Title: Re: arrays
Post by towr on Jan 2nd, 2005, 11:07am
If you're allowed to use strings ( <string> ) to read the input, you can use

std::string str;
getline(cin, str);

to read a whole line at once and if you want you can copy str.c_str() to your char lst[] (f.i. with strcopy)
It's quite possible the computer will do more work, but the code will be shorter and cleaner.

And for inserting, you could use the string::insert member function..
You're probably not supposed to do this though, since it probably defeats the purpose of the excersize.

A few notes,
if you use cin and cout, then you're programming C++. So you ought to use C++ includes, this means
#include <iostream>
instead of
#include <iostream.h>

And if you don't declare that you're using the standard namespace (which you can do after the includes section by writing
using namespace std;
), you ought to use std::cin and std::cout, rather than without the std::
Just because the compiler accepts it as it is doesn't make it good form.

Title: Re: arrays
Post by brock123 on Jan 2nd, 2005, 2:42pm
thank you towr.



Powered by YaBB 1 Gold - SP 1.4!
Forum software copyright © 2000-2004 Yet another Bulletin Board