#include "stdafx.h"
using namespace std;
#include <iostream>
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
using namespace std;
//Search program
void read_data(int* , int); //array address, size
int seq_search(int , int* , int);//key,array address,size
int binary_search(int , int* , int);
void main(void)
{
int *arr , size , ans , key ;
cout << "Please enter the size: ";
cin >> size ;
arr = new int[size] ;
read_data(arr , size);
cout << "Enter the number to search for: ";
cin >> key ;
ans = binary_search(key, arr , size);
if(ans == -1)
cout << "The number " << key << " does not exist \n";
else
cout << "The number " << key << " exists at location " << ans << endl;
getch();
}
void read_data(int *pt , int ss)
{
cout << "Please enter " << ss << " numbers: \n";
for(int k = 0 ; k < ss ; k++)
{
cout << "Enter the " << k + 1 << " number: " ;
cin >> pt[k] ;
}
}
int seq_search(int num , int a[] , int s)
{
for(int k = 0 ; k < s ; k++)
if(num == a[k]) { return k ; }
return -1 ;
}
int binary_search(int num , int a[] , int s)
{
int first , last , mid ;
first = 0 ; last = s -1 ;
while(first <= last)
{
mid = (first + last) / 2 ;
if(num == a[mid]) return mid ;
else if(num > a[mid]) first = mid + 1 ;
else
last = mid - 1 ;
}
return -1;
}
From what I understood (I'm a real beginner) is for example *P = a; points to address if integer a, and p = %a; is the reference or the real address of a.
I understood that we use this new int in order to use the array everywhere in the program as it is destroyed when main is finished, but why didn't I declare it outside of main too to be used everywhere?