EECE 230 Exam 2 Solution, Spring 2014

American University of Beirut · Introduction to Programming · 4 pages · Dr. Louay Bazzi · with solution

All EECE 230 files
EECE 230 Exam 2 Solution, Spring 2014, page 1

Stuck on a question? A tutor can walk you through it.

EECE 230 Exam 2 Solution, Spring 2014, page 2 EECE 230 Exam 2 Solution, Spring 2014, page 3 EECE 230 Exam 2 Solution, Spring 2014, page 4

More EECE 230 files

Show the text of this exam
#include<iostream> using namespace std; void flipHalves(char *s,char *t); int main() { char s1[] = "abcdefgh", t1[10]; flipHalves(s1,t1); cout<<"t1: "<<t1<<endl; char s2[] = "abcde", t2[10]; flipHalves(s2,t2); cout<<"t2: "<<t2<<endl; char s3[] = "ab", t3[10]; flipHalves(s3,t3); cout<<"t3: "<<t3<<endl; char s4[] = "a", t4[10]; flipHalves(s4,t4); cout<<"t4: "<<t4<<endl; return 0; } void flipHalves(char *s, char *t) { int n = strlen(s); if(n%2 ==0) { for(int i=0;i<n/2;i++) t[i+n/2] = s[i]; for(int i=n/2;i<n;i++) t[i-n/2] = s[i]; } else { for(int i=0;i<n/2;i++) t[i+n/2+1] = s[i]; t[n/2]=s[n/2]; for(int i=n/2+1;i<n;i++) t[i-n/2-1] = s[i]; } t[n]='\0'; } #include<iostream> using namespace std; int findOutcast(int A[], int n); void main() { int A[] = {55,50, 12, 1,0,31,39,23,25,49,43}; // 12 is the outcast and its index is 2 cout<<findOutcast(A,11)<<endl; int B[] = {1,10,2,13}; // there is no outcast cout<<findOutcast(B,4)<<endl; int C[] = {12,100,30};// they are all outcasts cout<<findOutcast(C,3)<<endl; } int findOutcast(int A[], int n) { for(int i=0;i<n;i++) { bool outCast = true; for(int j=0;j<n;j++) if(i!=j && abs(A[i]-A[j])<10) { outCast = false; break; } if(outCast) return i; } return -1; } #include <iostream> using namespace std; void f(int n, int i, int j) { if(i<=n) { cout<<i+j<<" "; f(n,i+1,j); } else if(j!=n) { cout<<endl; f(n,0,j+1); } else return; } void main () { cout<<"Enter n:"; int n; cin>>n; ////////////////////////// /* for(int i=0;i<=n;i++) { for(int j=0;j<=n;j++) cout<<i+j<<" "; cout<<endl; }*/ ///////////////////////// f(n,0,0); } #include<iostream> using namespace std; int findRepeated(int A[], int p,int q); void main() { int A[] = {10,11,12,13,13,14,15}; cout<<findRepeated(A,0,6); cout<<endl; int B[] = {10,11,11,12,13,14,15}; cout<<findRepeated(B,0,6); cout<<endl; int C[] = {10,10,11,12,13,14,15}; cout<<findRepeated(C,0,6); cout<<endl; int D[] = {10,11,12,13,14,15,15}; cout<<findRepeated(D,0,6); cout<<endl; int E[] = {10,10}; cout<<findRepeated(D,0,1); cout<<endl; } int findRepeated(int A[], int p,int q) { if(q==p+1) return A[p]; int mid = (p+q)/2; if(A[mid]==A[mid-1] || A[mid]==A[mid+1]) return A[mid]; if(A[mid]-A[p] == mid-p) return findRepeated(A,mid+1,q); else return findRepeated(A,p,mid-1); }