Uploaded by rao.sana10

Data Structure and Analysis of Algorithms Lab 2

advertisement
Data Structure and Analysis
of Algorithms
Lab 2
Create a String
• #include<iostream>
• #include<string>
• using namespace std;
• int main()
•{
•
string a = "create a string";
•
cout<<a;
•
return 0;
•}
Exercise
Output:
• Welcome to Data Structure Lab.
• A Lab Lecture.
String Concatenation
#include<iostream>
#include<string>
using namespace std;
int main(){
string firstname = "John";
string lastname = "Doe";
string fullname = firstname + " " + lastname;
cout << fullname;
return 0;
}
Exercise
Output:
Enter the first string: Course
Enter the second string: Data Structure
Resultant String: Course Data Struture
String Length
cout<<"Length of string is:"<<s1.size();
Exercise
Output:
John Doe
Length of string is:8
Access String
#include<iostream>
#include<string>
using namespace std;
int main()
{
string mystring = "structure";
cout<<mystring[1];
return 0;
}
String Insertion
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str1 = "Programming C++";
cout<<str1<<endl;
cout<<"New string is: "<<str1.insert(11," with");
return 0;
}
Exercise
Output:
• Data Structure is favorite subject.
• Data structure is my favorite subject.
Array Insertion
#include<iostream>
using namespace std;
int main()
{
int arr[10]={1,2,3,4,5};
int val , pos;
cout<<"Array Element Before Insertion"<<endl;
for(int i=0;i<5;i++)
{
cout<<arr[i];
cout<<"Enter Value";
cin>>val;
for(int i=5; i>pos ;i--)
{
arr[i] = arr[i-1];
}
arr[pos-0] = val;
cout<<"After
insertion"<<endl;
for(int i=0; i<5+1; i++)
{
cout<<arr[i]<<" ";
}
return 0;
}
cout<<"\n Enter Position";
cin>>pos;
}
Exercise
Output:
Array Element Before Insertion:
12345
Enter Position: 3
Enter Value: 9
After Insertion :
123945
Array Traversing
#include<iostream>
using namespace std;
int main()
{
int arr[5]={1,3,5,7,8};
for(int i=0;i<5;i++)
{
cout<<arr[i]<<endl;
}
}
Exercise
• Traversing Through While loop
Search Element in Array
#include<iostream>
using namespace std;
int main()
{
int arr[10], i, num, index;
for(i=0;i<10;i++)
{
cout<<"Enter numbers:";
cin>>arr[i];
}
cout<<"Enter a number to search:";
cin>>num;
for(i=0;i<10;i++)
{
if(arr[i]==num)
{
index = i;
cout<<"Found at index no."<<index;
break;
}
}
return 0;
}
Download