MENU











Friday, 17 January 2014

oops week 22

Week 22 solutions

22a) a) Write a C++ program to write a function 
char* findx(const char* s, const char* x) that
find the first occurrence of the string x in s.
 Use dereference operator * instead.

   
   Same as 20a

  


22b) Write a C++ program to write a function 
string cat_dot(const string& s1, const string&s2), 
that concatenates two strings with a dot in between.

program:

#include<iostream>
#include<string.h>
using namespace std;

string cat_dot(const string&s1,const string&s2);
int main()
{
 string s1,s2,s3;
 cout<<"Enter string 1\n";
 cin>>s1;
 cout<<"Enter string 2\n";
 cin>>s2;
 s3=cat_dot(s1,s2);
 cout<<"After concatenation:\n";
 cout<<s3;
 
}
string cat_dot(const string&s1,const string&s2)
{
 string a;
 a=s1+"."+s2;
 return a;
}

output: 


Enter string 1
C++
Enter string 2
Programming
After concatenation:
C++.Programming





22c) Write a template function that adds a vector of elements of an 
object of any type to which elements can be added.
program:

#include<iostream>
#include<vector>
using namespace std;
template<class T>
T sum(vector<T>v) 
{
   T result;
   for (int i = 0; i < v.size(); ++i)
      result+=v[i];
  
 return result;
}
int main()
{
 
 vector<int>v;
 int x,res;
 cout<<"Enter the elements of vector\n";
 while(cin>>x)
 {
  v.push_back(x);
 }
 res=sum(v); 
 cout<<"sum of all elements is :"<<res<<endl;
}

output: 


Enter the elements of vector
1 2 3 4 5 6 7 8 9 10 11 11 *
sum of all elements is :77

 

No comments:

Post a Comment