Write a function-based C++ program that reads an integer array from a file (“input.txt”) and finds all integers which start and end with the same digit. Write these integers into an output file (“output.txt”). You may assume the length of each integer to be a minimum of 2 digits.
#include <fstream>
#include<iostream>
using namespace std;
int first_Digit(int n)
{
while (n >= 10)
n /= 10;
return n;
}
int countDigits(int n)
{
if (n/10 == 0)
return 1;
return 1 + countDigits(n / 10);
}
int getNumsWithSameStartAndEnd(int n){
int f=first_Digit(n);
int l;
l=n%10;
if (f==l){
return n;
}
else{
return 0;
}
}
int* getNumbers(int arr2[],int size, int c){
int arr3[20];
int s_num[20];
for (int i=0;i<c;i++){
int num=arr2[i];
int n=countDigits(num);
s_num[i]=getNumsWithSameStartAndEnd(num);
}
return s_num;
}
using namespace std;
int main() {
//initialie the array size
int arr[30];
ifstream is("input.txt");
int cnt= 0;
int x;
// check that array is not already full
while (cnt < arr[30] && is >> x)
// and read integer from file
arr[cnt++] = x;
// print the integers stored in the array
cout<<"The integers are:"<<"\n";
for (int i = 0; i < cnt; i++) {
cout << arr[i] <<' ';
}
is.close();
//close the file
ofstream os("output.txt");
int *num2;
num2=getNumbers(arr,30,cnt);
for (int i=0;i<30;i++){
if (num2[i] !=0)
os<<num2[i];
}
}
Comments
Leave a comment