Write in C++ ONLY A3.txt file include 41 0 24 27 34 41 45 50 58 61 62 64 67 69 7
ID: 3678882 • Letter: W
Question
Write in C++ ONLY
A3.txt file include
41
0 24 27 34 41 45 50 58 61 62 64 67 69 78 81
91
16 18 20 21 27 36 40 42 53 82 91 91 92 95 95
27
11 12 22 26 31 33 35 38 47 67 69 71 73 94 99
41
11 23 29 37 41 41 44 47 53 57 59 62 64 68 78
64
5 6 16 29 35 40 42 42 46 48 64 70 88 90 90
98
1 23 29 31 40 48 50 54 56 66 76 81 84 93 98
39
15 18 23 26 29 33 37 38 39 39 40 41 44 58 82
78
12 21 24 29 30 45 62 70 72 73 73 77 77 86 97
36
24 31 36 41 50 50 52 55 55 61 66 67 74 86 90
37
6 16 24 28 29 36 38 38 39 39 40 41 44 58 82
Thank You
Explanation / Answer
Reading from a file can also be performed in the same way that we did with cin-
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout << line << ' ';
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
Binary Search using Recursion
#include<iostream.h>
#include<conio.h>
void search(int a[], int beg, int end, int item) // Function to Search Element
{
if(beg==end) // if Single Element is in the List
{
if(item==a[beg])
cout<<" The Element is Found at Position : "<<beg;
else
cout<<" Data is Not Found";
}
else
{
int mid = (beg + end)/2;
if(item == a[mid])
cout<<" The Element is Found at Position : "<<mid;
else if(item < a[mid])
search(a,beg,mid-1,item); // Function Calls Itself (Recursion)
else
search(a,mid+1,end,item); // Function Calls Itself (Recursion)
}
}
void main()
{
clrscr();
int a[100],item,n,beg,end,mid,loc;
cout<<" ------- Binary Search using Recursion ------- ";
cout<<"Enter the number of Elements : ";
cin>>n;
cout<<" Enter the elements : ";
for(loc=1;loc<=n;loc++)
{
cin>>a[loc];
}
cout<<" Enter the Element to be searched : ";
cin>>item;
c++
end=n;
search(a,beg,end,item); // Function Call in Main Function
getch();
}
Writing operations on text files are performed in the same way we operated with cout.
// writing on a text file
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile ("example.txt");
if (myfile.is_open())
{
myfile << "This is a line. ";
myfile << "This is another line. ";
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
Note-By merging or by using above three codes with few modifications in C++ gives required output for the given problem.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.