polynomial operator+ function is causing the wrong output or is it print function - oop

this is the output showing :
+2x^0 +0x^1 +0x^2 +0x^3 -5x^4
+0x^0 +0x^1 +0x^2 +0x^3 +6x^4 +0x^5 +0x^6 +0x^7 -9x^8
+2x^0 +0x^1 +0x^2 +0x^3 +1x^4 +0x^5 +0x^6 +0x^7 +1584935467x^8 // output of p1+p2
why is is showing 158.... in x power 8 term .
it should show simply -9x^8 only .
i am trying to learn to implement operator overloading in it .
i think the problem is in loop of overloading function .
#include <iostream>
using namespace std ;
class polynomial {
int* degree ;
int capacity ;
public:
polynomial () {
degree = new int[5];
for ( int i = 0 ; i < 5 ; i ++){
degree[i] = 0 ;
}
capacity = 5 ;
}
// copy constructor
polynomial (const polynomial& p){
this -> degree = new int[p.capacity];
for( int i = 0 ; i < p.capacity ; i++){
this -> degree[i] = degree[i];
}
this -> capacity = p.capacity;
}
// assignment operator overload
void operator=(polynomial const &p){
this -> degree = new int[p.capacity];
for( int i = 0 ; i < p.capacity ; i++){
this -> degree[i] = p.degree[i];
}
this -> capacity = p.capacity;
}
void print(){
for ( int i = 0 ; i < capacity ; i ++ ){
if( degree[i] >= 0)
cout << "+"<< degree[i] <<"x^" <<i<<" ";
else cout<< degree[i] <<"x^" <<i << " ";
}
cout << endl;
}
void setCoefficient( int de , int num ){
if( de < capacity ){
degree[de] = num ;
}
else {
int ic = capacity ;
capacity = capacity+(de-capacity+1) ;
int* ne = new int[capacity];
for( int i = 0 ; i < capacity ; i ++){
ne[i] = 0 ;
}
for( int i = 0 ; i < ic; i ++){
ne[i] = degree[i];
}
delete [] degree;
degree = ne;
degree[de] = num ;
}
}
polynomial operator+( polynomial const &p){
polynomial tp ;
tp.capacity = max(capacity, p.capacity) ;
int i = 0 ;
for(; i < max(this->capacity, p.capacity) ; i ++){
if(i <= capacity && i <= p.capacity)
{tp.degree[i] = degree[i] + p.degree[i];}
else if ( i < p.capacity) tp.degree[i] = p.degree[i] ;
else tp.degree[i] = degree[i];
}
return tp;
}
polynomial operator-( polynomial const &p){
polynomial tp ;
tp.capacity = max(capacity, p.capacity) ;
for( int i = 0 ; i < max(this->capacity, p.capacity) ; i ++){
tp.degree[i] = degree[i] - p.degree[i];
}
return tp;
}
};
#include <bits/stdc++.h>
#include "polynomialClass.cpp"
using namespace std;
int main (){
polynomial p1 , p2 ;
p1.setCoefficient(4, -5);
p1.setCoefficient(0,+2);
p1.print();
p2.setCoefficient(8,-9);
p2.setCoefficient(4,+6);
p2.print();
polynomial p3 = p1 + p2;
p3.print();
}

Related

Unable to Find Time Complexity

Below I am attaching my code(complete) , pls help me get an idea of how to find time_complexity and space_complexity of my code , especially for adding , updating and copying the set.
Thanks in Advance !!!
class Solution {
public List<List<Integer>> getAncestors(int n, int[][] edges) {
Set<Integer> [] ancestors = new Set[n] ;
int [] in_degree = new int[n] ;
List<Integer>[] li = new List[n] ;
for (int i = 0; i < n; i++) { // T.C. = O(n)
ancestors[i] = new HashSet<> ();
li[i] = new ArrayList<>() ;
}
// creating adj_list
for(int []edge : edges){ // T.C. = O(E)
li[edge[0]].add(edge[1]) ;
in_degree[edge[1]] ++ ;
}
helper(n , li , in_degree , ancestors) ;
// filling from (set) to List<Integer> in (lineage)
List<List<Integer>> lineage = new ArrayList<>() ;
for (int i = 0; i < n; i++) {
List<Integer> list = new ArrayList<>() ;
for(int j : ancestors[i]){
list.add(j) ; // copying set to list
}
Collections.sort(list);
lineage.add(list) ;
}
return lineage ;
}
//_____________________________________________________________________________________________________
private void helper(int n, List<Integer>[]li, int [] in_degree , Set<Integer> [] ancestors) {
Queue<Integer> q = new LinkedList<>() ;
for (int i = 0; i < n; i++) if(in_degree[i] == 0) q.add(i) ; // T.C. = O(n)
while(!q.isEmpty()){
int node = q.remove() ;
Set<Integer> grand_ancestors = ancestors[node] ;
for(int u : li[node]){
ancestors[u].add(node) ;
ancestors[u].addAll(grand_ancestors) ;
if(--in_degree[u] == 0) q.add(u) ;
}
}
}
}

Exception thrown at 0x7A12FF80 (ucrtbased.dll) in Project 3.exe: 0xC0000005: Access violation reading location 0x00000000

I have attempted to run this code. Prior to running this, no warnings or errors exist but once it is executed I have an exception thrown and it stops the program from compiling. Here is my code and the error is in the subject line. The CDA file is being used as header file to create a Circular Dynamic Array that is going to be manipulated in Heaps.cpp. The heaps.cpp is to create a binary heap that is to be used in to create Binomial heaps, but that code has not been developed yet.
#include <iostream>
using namespace std;
template <class T>
class CDA
{
private:
int rear;
int size;
int capacity;
T* circArray;
int front;
bool ordered;
T placeHolder;
public:
CDA();
CDA(int s);
~CDA();
int Front();
T Data(int n);
T& operator[](int i);
void AddEnd(T v);
void AddFront(T v);
void DelEnd();
void DelFront();
int Length();
int Capacity();
int Clear();
bool Ordered();
int SetOrdered();
int S01(int n);
T Select(int k);
void InsertionSort();
void QuickSort();
void QuickSort1(int low, int high);
void CountingSort(int m);
int Search(T e);
void reSize();
void Shrink();
int BinarySearch(int left, int right, T e);
int QSortPartition(int low, int high);
void Swap(int* x, int* y);
int QSelPartition(int front, int rear);
T QuickSelect(int front, int rear, int k);
CDA<T>& operator=(const CDA& a);
CDA(const CDA& old);
int Median(int low, int high);
};
template <class T>
CDA<T>::CDA()
{
capacity = 1;
circArray = new T[capacity];
size = 0;
rear = size - 1;
front = -1;
ordered = false;
placeHolder = 0;
}
template <class T>
CDA<T>::CDA(int s)
{
size = s;
capacity = s;
circArray = new T[capacity];
front = 0;
rear = size - 1;
ordered = false;
}
template <class T>
CDA<T>::CDA(const CDA& a)
{
size = a.size;
capacity = a.capacity;
circArray = new T[a.capacity];
front = a.front;
rear = a.size - 1;
ordered = a.ordered;
for (int i = a.front; i < a.front + (a.size); i++)
{
circArray[i % capacity] = a.circArray[i % capacity];
}
}
template <class T>
CDA<T>::~CDA()
{
delete[]circArray;
}
template <class T>
T& CDA<T>::operator[](int i)
{
if (i > capacity)
{
cout << "Array index is out of bounds; exiting." << endl;
placeHolder = i;
cout << endl;
return placeHolder;
exit(0);
}
else
{
return circArray[(front + i) % capacity];
}
}
template <class T>
void CDA<T>::AddEnd(T v)
{
size++;
if (front == -1)
{
circArray[0] = v;
front++;
rear++;
return;
}
if (size > capacity)
{
reSize();
}
else if (front == -1)
{
front = 0;
rear = size - 1;
}
else
{
rear = (rear + 1) % capacity;
}
circArray[rear] = v;
}
template <class T>
void CDA<T>::AddFront(T v)
{
size++;
if (size > capacity)
{
reSize();
}
if (front == -1) //means the array is empty
{
front = 0;
rear = capacity % size;
}
else if (front == 0) //means something is in spot 0
{
front = capacity - 1; //puts front at the end and places the input there
}
else //go until it is back at zero
{
front--;
}
circArray[front] = v;
}
template <class T>
void CDA<T>::DelEnd()
{
size--;
if (size <= capacity / 4)
{
Shrink();
}
else if (rear == front)
{
front = -1;
rear = -1;
}
else
{
rear--;
}
}
template <class T>
void CDA<T>::DelFront()
{
size--;
double shrMeasure;
shrMeasure = capacity / 4.0;
if (size <= shrMeasure) // make an empty and shrink function
{
Shrink();
}
/*
else if (front == rear)
{
if (front == 0)
front = size - 1;
else
front++;
}
*/
else
{
if (front == size) //brings it full circle
{
front = 0;
}
else
{
front++;
}
}
if (front > capacity)
front = front % capacity;
}
template <class T>
int CDA<T>::Length()
{
return size;
}
template <class T>
int CDA<T>::Capacity()
{
return capacity;
}
template <class T>
int CDA<T>::Clear()
{
~CDA();
size = 1;
circArray[size] = NULL;
}
template <class T>
bool CDA<T>::Ordered()
{
return ordered;
}
template <class T>
int CDA<T>::SetOrdered()
{
for (int i = 1; i < size - 1; i++)
{
if (circArray[(i - 1)] > circArray[i])
{
ordered = false;
return -1;
}
}
ordered = true;
return 1;
}
template <class T>
T CDA<T>::Select(int k)
{
if (ordered == true)
{
return circArray[(front + k - 1) % capacity];
}
else
QuickSelect(front, front + (size - 1), k);
}
template <class T>
int CDA<T>::QSelPartition(int left, int right)
{
int pivot = circArray[right % capacity];
int x = left - 1;
//Swap(&circArray[pivIndex], &circArray[right]);
for (int i = left; i <= right - 1; i++)
{
if (circArray[i % capacity] <= pivot)
{
x++;
Swap(&circArray[x % capacity], &circArray[i % capacity]);
}
}
Swap(&circArray[(x + 1) % capacity], &circArray[right % capacity]);
return (x + 1);
}
template <class T>
T CDA<T>::QuickSelect(int left, int right, int k)
{
if (k > 0 && k <= (right - left) + 1)
{
int index = QSelPartition(left, right);
if (index - 1 == k - 1)
return circArray[index % capacity];
else if (index - 1 > k - 1)
return QuickSelect(left, index - 1, k);
else
return QuickSelect(index - 1, right, k - index + left - 1);
}
return -1;
}
template <class T>
void CDA<T>::InsertionSort() //must be utilized in quicksort
{
for (int i = front + 1; i < (front + size); i++)
{
int val = circArray[i % capacity];
int inc = (i - 1) % capacity;
while (inc >= 0 && circArray[inc] > val)
{
circArray[(inc + 1) % capacity] = circArray[inc];
inc--;
if (inc == -1)
{
inc = capacity - 1;
}
}
circArray[(inc + 1) % capacity] = val;
}
ordered = true;
}
template <class T>
void CDA<T>::QuickSort() // change to other quicksort before leaving the ferg
{
QuickSort1(front, front + (size - 1));
}
template <class T>
void CDA<T>::QuickSort1(int low, int high)
{
while (low < high)
{
if (high - low < 900)
{
InsertionSort();
break;
}
else
{
int pivot = QSortPartition(low, high);
if (pivot - low < high - pivot)
{
QuickSort1(low, pivot--);
low = pivot + 1;
}
else
{
QuickSort1(pivot++, high);
high = pivot - 1;
}
}
}
}
template <class T>
int CDA<T>::QSortPartition(int low, int high)
{
int pivot = circArray[Median(low, high) % capacity];
Swap(&circArray[(Median(low, high)) % capacity], &circArray[(high) % capacity]);
int index = low % capacity;
for (int i = low; i < high; i++)
{
if (circArray[i % capacity] <= pivot)
{
T t = circArray[i % capacity];
circArray[i % capacity] = circArray[index % capacity];
circArray[index % capacity] = t;
index++;
}
}
Swap(&circArray[index % capacity], &circArray[high % capacity]);
return index;
}
template <class T>
int CDA<T>::Median(int low, int high)
{
T left, mid, right;
left = circArray[low % capacity];
mid = circArray[((low + high) / 2) % capacity];
right = circArray[high % high];
if (left < right && left > mid)
return low % capacity;
if (left < mid && left > right)
return low % capacity;
if (right < left && right > mid)
return high % capacity;
if (right < mid && right > left)
return high % capacity;
if (mid < left && mid > right)
return ((low + high) / 2 % capacity);
if (mid < right && mid > left)
return ((low + high) / 2 % capacity);
}
template <class T>
void CDA<T>::Swap(int* x, int* y)
{
int temp = *x;
*x = *y;
*y = temp;
}
template <class T>
void CDA<T>::CountingSort(int m) ////NEED TO FIX THIS
{
int* OP = new int[size];
int* Counter = new int[m + 1];
for (int i = front; i <= rear; i++)
{
cout << "CircArray[" << i << "] is " << circArray[i] << endl;
}
for (int i = 0; i <= m; i++)
{
Counter[i] = 0;
}
for (int i = front; i < front + (size); i++)
{
Counter[circArray[i % capacity]]++;
}
for (int i = 1; i <= m; i++)
{
Counter[i] += Counter[i - 1];
}
for (int i = rear - 1; i > 0; i--)
{
OP[Counter[circArray[i]] - 1] = circArray[i];
cout << "Circular array at " << i << " is " << circArray[i] << endl;
Counter[circArray[i]] -= 1;
if (i == front % capacity)
break;
if (i == 0)
i = capacity;
}
for (int i = 0; i < size; i++)
circArray[i] = OP[i];
ordered = true;
front = 0;
}
template <class T>
int CDA<T>::Search(T e)
{
if (ordered == true) //binary search of item e
{
return BinarySearch(front, front + (size - 1), e);
}
else if (ordered == false)
{
for (int i = 0; i < size - 1; i++)
{
if (circArray[i] == e)
return i;
}
}
return -1;
}
template <class T>
int CDA<T>::BinarySearch(int left, int right, T e)
{
while (left <= right)
{
int mid = (left + right) / 2;
int value = circArray[mid % capacity];
if (value == e)
return (mid - front) % capacity;
else if (value < e)
return BinarySearch(mid + 1, right, e);
else if (value > e)
return BinarySearch(left, mid - 1, e);
}
return -1;
}
template <class T>
void CDA<T>::reSize()
{
capacity = capacity * 2;
T *nArray = new T[capacity];
for (int i = 0; i < size - 1; i++)
{
int l = (front + i) % (size-1);
nArray[i] = circArray[l];
}
//delete[]circArray;
circArray = nArray;
front = 0;
rear = (size - 1);
}
template <class T>
void CDA<T>::Shrink()
{
int tFront = front;
capacity = capacity / 2;
T* bArr = new T[capacity];
int index = 0;
while (front <= rear)
{
bArr[index] = circArray[(front + index) % capacity];
index++;
}
T* circArray = bArr;
front = 0;
rear = (size - 1);
}
template <class T>
CDA<T>& CDA<T>::operator=(const CDA<T>& a)
{
if (this != &a)
{
delete[]circArray;
size = a.size;
capacity = a.capacity;
circArray = new T[a.capacity];
front = a.front;
rear = a.size - 1;
ordered = a.ordered;
for (int i = a.front; i < a.front + (a.size); i++)
{
circArray[i % capacity] = a.circArray[i % capacity];
}
}
return *this;
}
template <class T>
int CDA<T>::Front()
{
return front;
}
template <class T>
T CDA<T>::Data(int n)
{
return circArray[n];
}
#include <iostream>
#include "CDA-1.cpp"
using namespace std;
template<class keytype, class valuetype>
class Heap
{
private:
CDA<keytype>* K;
CDA<valuetype>* V;
int size;
public:
Heap()
{
this->K = new CDA<keytype>();
this->V = new CDA<valuetype>();
size = 0;
}
Heap(keytype k[], valuetype v[], int s)
{
//allocate two different arrays for each type
//fill those arrays concurrently using insert
//sort concurrently using heapafy recursively
this->K = new CDA<keytype>(s);
this->V = new CDA<valuetype>(s);
this->size = s;
for (int i = 0; i < s; i++)
{
insert(k[i], v[i]);
}
heapify(s, K->Front());
}
void heapify(int s, int i)
{
//Errors for evans to fix: swap the n's with s.
//Fix the left and right variable logic. Hepaify smallest not small at the bottom.
//Also we need to pass V[] in a parameter so we can edit it in this.
//How to better swap V with K and not just K.
int smallest = i;
int left = 2*i +(-i+1);
int right = 2*i + (-i+2);
keytype kl = K->Data(left);
keytype kr = K->Data(right);
keytype ks = K->Data(smallest);
if (left < s && kl < ks) //FIX
smallest = left;
if (right < s && kr < ks) //FIX
smallest = right;
if (smallest != i)
{
swap(K[i], K[smallest]);
swap(V[i], V[smallest]); //FIX
heapify(s, smallest);
}
}
~Heap() {
return;
}
//items should be inserted using bottom up heap building method
void insert(keytype k, valuetype v)
{
K->AddEnd(k);
V->AddEnd(v);
heapify(size, K->Front());
}
keytype peekKey()
{
int f = K->Front();
return K->Data(f);
}
valuetype peekValue()
{
int f = V->front();
return V->Data(f);
}
keytype extractMin()
{
keytype temp = K->Data(K->Front());
K->DelFront();
V->DelFront();
heapify(size, K->Front());
return temp;
}
void printKey()
{
ActualPrintKey(K->Front());
}
void ActualPrintKey(int n)
{
keytype rt = K->Data(n);
if (rt != size)
{
cout << K->Data(rt) << " ";
ActualPrintKey((2 * n) + (-n + 1));
ActualPrintKey((2 * n) + (-n + 2));
}
}
};
/*
template <class keytype, class valuetype>
class BHeap
{
BHeap();
BHeap(keytype k[], valuetype v[], int s);
~BHeap();
keytype peekKey();
valuetype peekValue();
keytype extractMin();
//items should be inserted using repeated insertion
void insert(keytype k, valuetype v);
void merge(BHeap<keytype, valuetype>& H2);
void printKey();
};
*/
#include <iostream>
#include "Heaps.cpp"
using namespace std;
int main() {
string K[10] = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "K" };
int V[10] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
Heap<string, int> T1, T2(K, V, 10);
cout << T2.peekKey() << endl;
cout << endl;
system("pause");
return 0;
}
In general "Access violation reading location", means you are trying to read virtually memory address space to a process which does not belong to your application and the operating system protective mechanism is kicking in to protect the rest of the loaded applications and resource from been accessed (read or write) by your application "memory leak vulnerability". If I was at your place I would review the code and all variables and arrays if they are properly initialized before use. Another thing which needs to be taken in consideration is the operating system and the permissions required by your application (Windows run as Administrator / GNU/Linux sudo).
Cheers

Is that the right way to check if an existing password is stored?

I'm creating an application with 2 ATMega16 micro controller.
The second micro should check if a password is stored in the external EEPROM then send this information to the first one. So, if there were a stored password user will be ask to log-in, else the user should set a new password and send it to the second micro to save it in the external EEPROM.
The code doesn't run in a right way; can you help me to understand what happens?
Note: all driver used are tested and all of them works correctly.
First Micro Code
#define PASSWORD_LENGTH 5
#define PASSWORD_ADDRESS 0x0311
#define HMI_READY 0
#define CONTROL_READY 1
#define IS_PASSWORD_EXIST 6
#define PASSWORD_EXISTS 7
#define PASSWORD_NOT_EXISTS 8
#include "lcd.h"
#include "keypad.h"
#include "uart.h"
void HMI_init(void) ;
void HMI_set_new_password(uint8 *a_ptrPassword) ;
void HMI_send_password(uint8 *a_ptrPass) ;
uint8 g_password[PASSWORD_LENGTH] = {0} ;
int main(void)
{
HMI_init() ;
UART_sendByte(HMI_READY) ;
LCD_clearDisplay() ;
LCD_displayString("Stuck Here : ( ") ; /*<<<<<<<<<<<<<<<<<<<<<*/
if(UART_receiveByte() == PASSWORD_NOT_EXISTS)
{
LCD_sendCommand(CLEAR_DISPLAY) ;
LCD_displayString("N O ") ;
}
else if(UART_receiveByte() == PASSWORD_EXISTS) ;
{
LCD_sendCommand(CLEAR_DISPLAY) ;
LCD_displayString("Y E S ") ;
while(1)
{
}
}
}
/* Functions Definitions */
void HMI_init(void)
{
LCD_init() ;
LCD_sendCommand(CLEAR_DISPLAY) ;
LCD_sendCommand(CURSOR_OFF) ;
LCD_displayStringRowCol(0,4,"WELCOME") ;
LCD_displayStringRowCol(1,1,"TO DOOR LOCKER") ;
UART_init();
SREG |=(1<<7) ;
}
void HMI_set_new_password(uint8 *a_ptrPassword)
{
uint8 i = 0 ;
uint8 key = 0 ;
uint8 temp_pass[PASSWORD_LENGTH] = {0} ;
uint8 confirm_flag = 0 ;
while(confirm_flag == 0)
{
i = 0 ;
LCD_sendCommand(CLEAR_DISPLAY) ;
LCD_sendCommand(CURSOR_ON) ;
LCD_displayString("SET A PASSWORD : ") ;
LCD_goToRowCol(1,0) ;
while(i<PASSWORD_LENGTH)
{
key = KeyPad_getPresssedKey() ;
if(key>=0 && key<=9)
{
a_ptrPassword[i] = key ;
LCD_displayCharacter('*') ;
i++ ;
}else
{
}
_delay_ms(2000) ;
}
LCD_sendCommand(CLEAR_DISPLAY) ;
LCD_sendCommand(CURSOR_ON) ;
LCD_displayString("REPEAT PASSWORD : ") ;
LCD_goToRowCol(1,0) ;
i = 0 ;
while(i<PASSWORD_LENGTH)
{
key = KeyPad_getPresssedKey() ;
if(key>=0 && key <=9)
{
temp_pass[i] = key ;
i++ ;
LCD_displayCharacter('*') ;
}else
{
}
_delay_ms(2000) ;
}
/* compare */
for(i = 0 ; i<PASSWORD_LENGTH ; i++)
{
if(a_ptrPassword[i] != temp_pass[i])
{
confirm_flag = 0 ;
break ;
}else{
confirm_flag = 1 ;
}
}
if(confirm_flag == 1)
{
LCD_sendCommand(CLEAR_DISPLAY) ;
LCD_displayString("CONFIRMED") ;
_delay_ms(2000) ;
}else if(confirm_flag == 0 )
{
LCD_sendCommand(CLEAR_DISPLAY) ;
LCD_displayString("NOT CONFIRMED") ;
_delay_ms(2000) ;
}
}
}
void HMI_send_password(uint8 *a_ptrPass)
{
uint8 i = 0 ;
for(i = 0 ; i<PASSWORD_LENGTH ; i++)
{
UART_sendByte(a_ptrPass[i]) ;
}
}
Second micro code
#define PASSWORD_LENGTH 5
#define PASSWORD_ADDRESS 0x0311
#define HMI_READY 0
#define CONTROL_READY 1
#define IS_PASSWORD_EXIST 6
#define PASSWORD_EXISTS 7
#define PASSWORD_NOT_EXISTS 8
#include "lcd.h"
#include "uart.h"
#include "eeprom.h"
void CONTROL_init(void) ;
uint8 CONTROL_password_exist(void) ;
void CONTROL_receive_password(uint8 *a_ptrPass) ;
void CONTROL_save_password(uint8 *a_ptrPass) ;
uint8 g_received_password[PASSWORD_LENGTH] = {0} ;
int main(void)
{
CONTROL_init() ;
if(CONTROL_password_exist() == 0)
{
while(UART_receiveByte() != HMI_READY) ;
UART_sendByte(PASSWORD_NOT_EXISTS) ;
}
else
{
while(UART_receiveByte() != HMI_READY) ;
UART_sendByte(PASSWORD_EXISTS) ;
while(1)
{
}
}
}
void CONTROL_init(void)
{
LCD_init() ;
LCD_sendCommand(CLEAR_DISPLAY) ;
LCD_sendCommand(CURSOR_OFF) ;
EEPROM_init() ;
UART_init() ;
SREG |=(1<<7) ;
}
uint8 CONTROL_password_exist(void)
{
uint8 i = 0 ;
uint8 temp = 0 ;
for(i=0 ; i<PASSWORD_LENGTH ; i++)
{
EEPROM_readByte((PASSWORD_ADDRESS+i) , &temp) ;
_delay_ms(150) ;
if(temp != 0xFF)
{
return 1 ;
}
}
return 0 ;
}
void CONTROL_receive_password(uint8 *a_ptrPass)
{
uint8 i = 0 ;
for(i = 0 ; i<PASSWORD_LENGTH ; i++)
{
a_ptrPass[i] = UART_receiveByte() ;
}
}
void CONTROL_save_password(uint8 *a_ptrPass)
{
uint8 i = 0 ;
for(i = 0 ; i<PASSWORD_LENGTH ; i++)
{
EEPROM_writeByte((PASSWORD_ADDRESS+i) , a_ptrPass[i]);
_delay_ms(150) ;
}
}
The synchronisation is poorly implemented - you have a start-up race condition. You have no guarantee that CONTROL is ready when HMI sends its single HMI_READY byte.
The HMI should wait for a response, and if none is received in a reasonable time (a matter of milliseconds), resend the HMI_READY:
Pseudo-code - this is just to illustrate a possible structure and logic:
// Wait for response
response = false ;
while( !response )
{
// Send or resend synchronisation byte
send( HMI_READY )
// Wait for response or timeout
start_time = now() ;
while( !response && (now() - start_time) < TIMEOUT )
{
ch = receive() ;
response = ( ch == PASSWORD_NOT_EXISTS || ch == PASSWORD_EXISTS )
}
}
if( ch == PASSWORD_NOT_EXISTS)
{
...
}
else // password exists
{
...
}
Your CONTROL may be fine, since it does wait indefinitely for HMI_READY, but might better be structured thus:
// Wait for synch byte
while( receive() == HMI_READY )
{
// wait
}
if( CONTROL_password_exist() )
{
send( PASSWORD_EXISTS )
}
else
{
send( PASSWORD_NOT_EXISTS )
}
...
In this way, it does not matter when or in what order each micro is started, each will wait for the other - synchronisation.

Can't stop while loop which has scanf inside

#include <stdio.h>
int main() {
int test,i = 0,a = NULL;
int max2 = 0;
int n;
int max = -1000000, min = 1000000;
while (scanf("%d", &n) == 1 && max2 < 50)
{
if(n < min) { min = n; }
if(n > max) { max = n; }
max2++;
}
printf("%d",min+max);
return 0;
}
Input should be like this "1 5 8 9 10", I don't know how many numbers would be entered so I have to use the while loop.
Try using do while to put the scanf inside the loop.
#include <stdio.h>
int main() {
int test,i = 0,a = NULL;
int max2 = 0;
int n;
int max = -1000000, min = 1000000;
do{
scanf("%d", &n);
if(n < min) { min = n; }
if(n > max) { max = n; }
max2++;
}while ( n == 1 && max2 < 50)
printf("%d",min+max);
return 0;
}

Bubble sort Descending and Ascending in C won't sort

I'm giving a user choices to whether sort the elements in ascending or descending order. I know my code can sorts the elements right but somewhere in main I think I'm making mistake in calling my function to print the ascending/descending element in their proper order. Or do I have to have another if statement like I have in the bubble_sort function? I need to make it so the Main function prints the final results to the user. Here's the output I'm getting:
Enter number of elements
3
Enter 3 integers
43
7
90
Enter sort order
Please enter A for ascending or D for descending order
d
Sorted list in descending order:
43
7
90
#include <stdio.h>
void bubble_sort(long [], char n);
int main()
{
long array[100], n, c;
printf("Enter number of elements\n");
scanf("%ld", &n);
printf("Enter %ld integers\n", n);
for (c = 0; c < n; c++)
scanf("%ld", &array[c]);
printf("Enter sort order\n");
fflush(stdin);
printf("Please enter A for ascending or D for descending order\n");
scanf("%ld", &n);
bubble_sort(array, n);
printf("Sorted list in descending order:\n");
for ( c = 0 ; c < n ; c++ )
{
printf("%ld\n", array[c]);
}
fflush(stdin);
getchar();
return 0;
}
void bubble_sort(long list[], char n)
{
long c, d, temp;
if(n=='a' || n=='A')
{
for (c = 0 ; c < ( n - 1 ); c++)
{
for (d = 0 ; d < n - c - 1; d++)
{
if (list[d] > list[d+1])
{
temp = list[d];
list[d] = list[d+1];
list[d+1] = temp;
}
}
}
}
if(n=='d' || n=='D')
{
long c, d, temp;
for (c = 0 ; c < ( n - 1 ); c++)
{
for (d = 0 ; d > n - c - 1; d++)
{
if (list[d] < list[d+1])
{/* Swapping */
temp = list[d];
list[d] = list[d+1];
list[d+1] = temp;
}
}
}
}
}
EDIT: Here I added a swap function just so the ascending/descending logic is more efficient. But I seem to mixed up use of the variables which I think is a big problem. Would anyone point out and help me understand where and why I'd need to use those variables? Thanks much!
#include <stdio.h>
void bubble_sort(int list[], int n, char c);
void swap(int x, int y, int array[]);
int main()
{
int array[100], j, i;
char c;
printf("Enter number of elements\n");
scanf("%d", &j);
printf("Enter %d integers\n", j);
for (i = 0; i < j; i++)
scanf("%d", &array[i]);
printf("Please enter A for ascending or D for descending order\n");
scanf("%s", &c);
bubble_sort(array, j, i);
printf("Sorted list in descending order:\n");
for (i = 0 ; i < j ; i++ )
{
printf("%d\n", array[i]);
}
getchar();
return 0;
}
void bubble_sort(int list[], int n, char c)
{
int i, j;
if(c=='a' || c=='A'){
for (i = 0; i < (n - 1); i++){
for (j = 0; j < (n - i) - 1; j++){
if (list[i] > list[j])
{
swap(i, j, list); }
}
}
}
if(c=='d' || c=='D') {
for (i = 0 ; i < ( n - 1 ); i++) {
for (j = 0 ; j > (n - i) - 1; j++) {
if (list[i] < list[j])
{
swap(i, j, list);
}
}
}
}
}
void swap(int x, int y, int array[])
{
int hold; //temp hold a number
hold = array[x];
array[x] = array[y];
array[y] = hold;
}
In this statements
printf("Please enter A for ascending or D for descending order\n");
scanf("%ld", &n);
you are overwritting the value stored in n that before these statements denoted the number of the elements in the array. You should declare one more variable of type char and use it for this code snippet.
Also the sort function should be declared as
void bubble_sort(long list[], int n, char c );
where n is the array size and c is either 'A' or 'D'
EDIT: Your new code contains many typos. Try the following
#include <stdio.h>
void swap( int x, int y, int array[] )
{
int hold; //temp hold a number
hold = array[x];
array[x] = array[y];
array[y] = hold;
}
void bubble_sort( int list[], int n, char c )
{
int i, j;
if ( c == 'a' || c == 'A' )
{
for ( i = 0; i < n - 1; i++ )
{
for ( j = 0; j < n - i - 1; j++ )
{
if ( list[j] > list[j+1] )
{
swap( j, j + 1, list);
}
}
}
}
if ( c=='d' || c=='D' )
{
for ( i = 0 ; i < n - 1; i++ )
{
for ( j = 0 ; j < n - i - 1; j++ )
{
if ( list[j] < list[j+1] )
{
swap( j, j + 1, list);
}
}
}
}
}
int main(void)
{
int array[100], j, i;
char c;
printf("Enter number of elements: ");
scanf( "%d", &j);
printf( "Enter %d integers\n", j );
for ( i = 0; i < j; i++ ) scanf( "%d", &array[i] );
printf("Please enter A for ascending or D for descending order: ");
scanf( " %c", &c );
printf( "%c\n", c );
bubble_sort( array, j, c );
printf( "Sorted list in the selected order:\n" );
for ( i = 0; i < j; i++ )
{
printf( "%d ", array[i] );
}
puts( "" );
return 0;
}