Write the definition of a function, isReverse - c

Write the definition of a function, isReverse , whose first two parameters are arrays of integers of equal size, and whose third parameter is an integer indicating the size of each array. The function returns true if and only if one array is the reverse of the other. ("Reverse" here means same elements but in reverse order.)
int isReverse(int array1[], int array2[], int size)
{
int i;
for (i=0;i<size;i++)
{
if(array1[i] == array2[size-1])
return 0;
else
return 1;
}
}
i keep getting an error. whats wrong with it.

When you return from within any block in the function the function execution ends there, so in your case you are returning from function even when the first elements of the arrays are matching which is not correct, you should check whole array and then return from the function in the end, check the code below:
int isReverse(int array1[], int array2[], int size)
{
int i,status=1;
for (i=0;i<size;i++) //Size is the length of the array? if yes than you need -1 from it.
{
if(array1[i] == array2[size])
{
status=0;
--size;
}
else
return 1;
}
return status;
}
Moreover, size-1 does not change the value of the variable size itself hence size will remain same throughout the loop, use --size this will decrement the value of actual variable hence decrementing it by one every time.

The variable "size" never changes, so you're always checking elements of array1 against the last element of array2.
Since this sounds like a homework problem, I'll let you see if you can go from there.

This is how I did it.
int isReverse(int array1[], int array2[], int SIZE)
{
for( int counter = 0; counter <= SIZE/2; counter++ )
if(array1[counter] != array2[SIZE-counter] || array2[counter] != array1[SIZE-counter])
return 1;
return 0;
}
You are just comparing the value at index i with a constant SIZE-1. Instead you want to compare the value at i with the comparison array's size-i. So each time the counter increments it compares with the opposite array's size-i. And you only have to do this for half of the array.

The return value is wrong because you are checking only 1 value from each array, not all of them. What you want to do is something like this.
for (i=0;i<size;i++)
{
if(!(array1[i] == array2[size-i-1]))
return 0;
}
return 1;
Basically you go through the array one by one, if any of the values are not the same as the appropriate value on the other array, it is not a reverse, so we return 0. If we get out of the for loop without going through the if, it means they are reverses so we return 1.

int isReverse(int array1[], int array2[], int size)
{
int flag = 0;
for (int i=0;i<size;i++)
{
if(array1[i] != array2[size-1]){
flag = 1;
break;
}
return flag;
}
}
In the code you have kept the return statement inside the loop... keep the return statement outside the loop and try

int isReverse(int a[], int b[], int n)
{
int i = 0;
while (i<n)
{
if (a[i] != b[n-i-1]) {return 0; break;}
else i++;
}
return 1;
}
anw this was the correct answer.

bool isReverse(int array1[], int array2[],int size)
{
int i=0;
for (int k=0;k<size;k++){
if (array1[k]==array2[size-k-1]){
i++;
}
}
if (i==size){
return true;
}else{
return false;
}
}

Related

last number in a function array

I want to write a function where I have a given array and number N. The last occurrence of this number I want to return address. If said number cannot be found I want to use a NULL-pointer
Start of the code I've made:
int main(void) {
int n = 3;
int ary[6] = { 1,3,7,8,3,9 };
for (int i = 0; i <= 6; i++) {
if (ary[i] == 3) {
printf("%u\n", ary[i]);
}
}
return 0;
}
result in command prompt:
3
3
The biggest trouble I'm having is:
it prints all occurrences, but not the last occurrence as I want
I haven't used pointers much, so I don't understand how to use the NULL-pointer
I see many minor problems in your program:
If you want to make a function, make a function so your parameters and return types are explicit, instead of coding directly in the main.
C arrays, like in most languages, start the indexing at 0 so if there are N element the first has index 0, then the second has 1, etc... So the very last element (the Nth) has index N-1, so in your for loops, always have condition "i < size", not "i <= size" or ( "i <= size-1" if y'r a weirdo)
If you want to act only on the last occurence of something, don't act on every. Just save every new occurence to the same variable and then, when you're sure it was the last, act on it.
A final version of the function you describe would be:
int* lastOccurence(int n, int* arr, int size){
int* pos = NULL;
for(int i = 0; i < size; i++){
if(arr[i] == n){
pos = &arr[i]; //Should be equal to arr + i*sizeof(int)
}
}
return pos;
}
int main(void){
int n = 3;
int ary[6] = { 1,3,7,8,3,9 };
printf("%p\n", lastOccurence(3, ary, 6);
return 0;
}
Then I'll add that the NULL pointer is just 0, I mean there is literally the line "#define NULL 0" inside the runtime headers. It is just a convention that the memory address 0 doesn't exist and we use NULL instead of 0 for clarity, but it's exactly the same.
Bugs:
i <= 6 accesses the array out of bounds, change to i < 6.
printf("%u\n", ary[i]); prints the value, not the index.
You don't actually compare the value against n but against a hard-coded 3.
I think that you are looking for something like this:
#include <stdio.h>
int main(void)
{
int n = 3;
int ary[6] = { 1,3,7,8,3,9 };
int* last_index = NULL;
for (int i = 0; i < 6; i++) {
if (ary[i] == n) {
last_index = &ary[i];
}
}
if(last_index == NULL) {
printf("Number not found\n");
}
else {
printf("Last index: %d\n", (int)(last_index - ary));
}
return 0;
}
The pointer last_index points at the last found item, if any. By subtracting the array's base address last_index - ary we do pointer arithmetic and get the array item.
The cast to int is necessary to avoid a quirk where subtracting pointers in C actually gives the result in a large integer type called ptrdiff_t - beginners need not worry about that one, so just cast.
First of all, you will read from out of array range, since your array last element is 5, and you read up to 6, which can lead in segmentation faults. #Ludin is right saying that you should change
for (int i = 0; i <= 6; i++) // reads from 0 to 6 range! It is roughly equal to for (int i = 0; i == 6; i++)
to:
for (int i = 0; i < 6; i++) // reads from 0 to 5
The last occurrence of this number I want to return as address.
You are printing only value of 3, not address. To do so, you need to use & operator.
If said number cannot be found I want to use a NULL-pointer
I don't understand, where do you want to return nullpointer? Main function can't return nullpointer, it is contradictory to its definition. To do so, you need to place it in separate function, and then return NULL.
If you want to return last occurence, then I would iterate from the end of this array:
for (int i = 5; i > -1; i--) {
if (ary[i] == 3) {
printf("place in array: %u\n", i); // to print iterator
printf("place in memory: %p\n", &(ary[i])); // to print pointer
break; // if you want to print only last occurence in array and don't read ruther
}
else if (i == 0) {
printf("None occurences found");
}
}
If you want to return an address you need yo use a function instead of writing code in main
As you want to return the address of the last occurence, you should iterate the array from last element towards the first element instead of iterating from first towards last elements.
Below are 2 different implementations of such a function.
#include <stdio.h>
#include <assert.h>
int* f(int n, size_t sz, int a[])
{
assert(sz > 0 && a != NULL);
// Iterate the array from last element towards first element
int* p = a + sz;
do
{
--p;
if (*p == n) return p;
} while(p != a);
return NULL;
}
int* g(int n, size_t sz, int a[])
{
assert(sz > 0 && a != NULL);
// Iterate the array from last element towards first element
size_t i = sz;
do
{
--i;
if (a[i] == n) return &a[i];
} while (i > 0);
return NULL;
}
int main(void)
{
int n = 3;
int ary[] = { 1,3,7,8,3,9 };
size_t elements = sizeof ary / sizeof ary[0];
int* p;
p = g(n, elements, ary); // or p = f(n, elements, ary);
if (p != NULL)
{
printf("Found at address %p - value %d\n", (void*)p, *p);
}
else
{
printf("Not found. The function returned %p\n", (void*)p);
}
return 0;
}
Working on the specified requirements in your question (i.e. a function that searches for the number and returns the address of its last occurrence, or NULL), the code below gives one way of fulfilling those. The comments included are intended to be self-explanatory.
#include <stdio.h>
// Note that an array, passed as an argument, is converted to a pointer (to the
// first element). We can change this in our function, because that pointer is
// passed BY VALUE (i.e. it's a copy), so it won't change the original
int* FindLast(int* arr, size_t length, int find)
{
int* answer = NULL; // The result pointer: set to NULL to start off with
for (size_t i = 0; i < length; ++i) { // Note the use of < rather than <=
if (*arr == find) {
answer = arr; // Found, so set our pointer to the ADDRESS of this element
// Note that, if multiple occurrences exist, the LAST one will be the answer
}
++arr; // Move on to the next element's address
}
return answer;
}
int main(void)
{
int num = 3; // Number to find
int ary[6] = { 1,3,7,8,3,9 }; // array to search
size_t arrlen = sizeof(ary) / sizeof(ary[0]); // Classic way to get length of an array
int* result = FindLast(ary, arrlen, num); // Call the function!
if (result == NULL) { // No match was found ...
printf("No match was found in the array!\n");
}
else {
printf("The address of the last match found is %p.\n", (void*)result); // Show the address
printf("The element at that address is: %d\n", *result); // Just for a verification/check!
}
return 0;
}
Lots of answers so far. All very good answers, too, so I won't repeat the same commentary about array bounds, etc.
I will, however, take a different approach and state, "I want to use a NULL-pointer" is a silly prerequisite for this task serving only to muddle and complicate a very simple problem. "I want to use ..." is chopping off your nose to spite your face.
The KISS principle is to "Keep It Simple, St....!!" Those who will read/modify your code will appreciate your efforts far more than admiring you for making wrong decisions that makes their day worse.
Arrays are easy to conceive of in terms of indexing to reach each element. If you want to train in the use of pointers and NULL pointers, I suggest you explore "linked lists" and/or "binary trees". Those data structures are founded on the utility of pointers.
int main( void ) {
const int n = 3, ary[] = { 1, 3, 7, 8, 3, 9 };
size_t sz = sizeof ary/sizeof ary[0];
// search for the LAST match by starting at the end, not the beginning.
while( sz-- )
if( ary[ sz ] == n ) {
printf( "ary[ %sz ] = %d\n", sz, n );
return 0;
}
puts( "not found" );
return 1; // failed to find it.
}
Consider that the array to be searched is many megabytes. To find the LAST match, it makes sense to start at the tail, not the head of the array.
Simple...

Understanding returning values functions C

I'm trying to understand how the return value of a function works, through the following program that has been given to me,
It goes like this :
Write a function that given an array of character v and its dim, return the capital letter that more often is followed by its next letter in the alphabetical order.
And the example goes like : if I have the string "B T M N M P S T M N" the function will return M (because two times is followed by N).
I thought the following thing to create the function:
I'm gonna consider the character inserted into the array like integer thank to the ASCII code so I'm gonna create an int function that returns an integer but I'm going to print like a char; that what I was hoping to do,
And I think I did, because with the string BTMNMPSTMN the function prints M, but for example with the string 'ABDPE' the function returns P; that's not what I wanted, because should return 'A'.
I think I'm misunderstanding something in my code or into the returning value of the functions.
Any help would be appreciated,
The code goes like this:
#include <stdio.h>
int maxvolte(char a[],int DIM) {
int trovato;
for(int j=0;j<DIM-1;j++) {
if (a[j]- a[j+1]==-1) {
trovato=a[j];
}
}
return trovato;
}
int main()
{
int dim;
scanf("%d",&dim);
char v[dim];
scanf("%s",v);
printf("%c",maxvolte(v,dim));
return 0;
}
P.S
I was unable to insert the value of the array using in a for scanf("%c,&v[i]) or getchar() because the program stops almost immediately due to the intepretation of '\n' a character, so I tried with strings, the result was achieved but I'd like to understand or at least have an example on how to store an array of character properly.
Any help or tip would be appreciated.
There are a few things, I think you did not get it right.
First you need to consider that there are multiple pairs of characters satisfying a[j] - a[j+1] == -1
.
Second you assume any input will generate a valid answer. That could be no such pair at all, for example, ACE as input.
Here is my fix based on your code and it does not address the second issue but you can take it as a starting point.
#include <stdio.h>
#include <assert.h>
int maxvolte(char a[],int DIM) {
int count[26] = {0};
for(int j=0;j<DIM-1;j++) {
if (a[j] - a[j+1]==-1) {
int index = a[j] - 'A'; // assume all input are valid, namely only A..Z letters are allowed
++count[index];
}
}
int max = -1;
int index = -1;
for (int i = 0; i < 26; ++i) {
if (count[i] > max) {
max = count[i];
index = i;
}
}
assert (max != -1);
return index + 'A';
}
int main()
{
int dim;
scanf("%d",&dim);
char v[dim];
scanf("%s",v);
printf("answer is %c\n",maxvolte(v,dim));
return 0;
}
#include <stdio.h>
int maxvolte(char a[],int DIM) {
int hold;
int freq;
int max =0 ;
int result;
int i,j;
for(int j=0; j<DIM; j++) {
hold = a[j];
freq = 0;
if(a[j]-a[j+1] == -1) {
freq++;
}
for(i=j+1; i<DIM-1; i++) { //search another couple
if(hold==a[i]) {
if(a[i]-a[i+1] == -1) {
freq++;
}
}
}
if(freq>max) {
result = hold;
max=freq;
}
}
return result;
}
int main()
{
char v[] = "ABDPE";
int dim = sizeof(v) / sizeof(v[0]);
printf("\nresult : %c", maxvolte(v,dim));
return 0;
}

Recursive Linear Search in C debug

Problem:1
In this code if I search a number which is not in array it should display Value not found but I don't know it's not displaying that message instead everytime it's showing Found value in element -5I don't have any clue why it's happening.
#include<stdio.h>
#define SIZE 100
size_t linearSearch(const int array[], int key, size_t size);
int main(void)
{
int a[SIZE];
size_t x;
int searchKey;
size_t element;
for(x=0; x<SIZE; ++x){
a[x] = 2*x;
}
for(x=0; x<SIZE; ++x){
if(x%10 == 0){
puts("");
}
printf("%5d", a[x]);
}
puts("\n\nEnter integer search key:");
scanf("%d", &searchKey);
// attempt to locate searchKey in array a
element = linearSearch(a, searchKey, SIZE);
// display results
if(element != -1){
printf("Found value in element %d", element);
}
else{
puts("Value not found");
}
}
size_t linearSearch(const int array[], int key, size_t size)
{
if(size<0){
return -1;
}
if(key == array[size-1]){
return size-1;
}
return linearSearch(array, key, size-1);
}
Problem:2
I can't understood how
size_t linearSearch(const int array[], int key, size_t size)
function working specially these line
if(key == array[size-1]){
return size-1;
return linearSearch(array, key, size-1);
As everyone said that you have a little mistake that is, you should write if(size==0) not if(size<0).
let me explain what's going on recursively in linearSearch() function
size_t linearSearch(const int array[], int key, size_t size)
{
if(size == 0){
return -1;
}
else
if(key == array[size-1]){
return size-1;
}
else{
return linearSearch(array, key, size-1);
}
}
Suppose you gave an input 198 as searchkey.
When you calling linearSearch() function by the statement
element = linearSearch(a, searchKey, SIZE);
you are passing reference to array[], searchKey 198, and Size 100 as argument.
In linearSearch function first if statement if(size==0) checks if the size is equal to zero if not then else if statement runs.
in else if statement If(198 == array[100-1]) condition is checked.
and we see 198 is present in array[99] so the else if condition is true thus linearSearch function return the 99 as result.
Now lets see what happend if you input 55 which is not in the array list.
if(size==0) is not true so program will skip it and will go to the next statement.
if(55 == array[100-1] will be checked as its not true then linearSearch(array, 55, 100-1) will be called. again if(55==array[99-1]) will be checked.
at some point size will become 0. and the first if(size==0) statement will execute.
1) The main problem is if(size<0){. Conditional expression will always be false. because size_t is unsigned integer. So, it returns a random position with the values found(It's undefined behavior) by chance become a large numbers(e.g. -5 is 4294967291 as unsigned) without end(not found).
if(size<0){ should be if(size==0){
2) If key match the last element, returns its position. If not, repeat with a shorter one size. key not found if size is zero.
Just change the if statement from if(size<0) to if(size==0)your code will work.

Checking array for identical numbers and their value

As part of a program that I have to make, one of the function that I need to program should check if the array has any identical numbers that are the same, and if one of them is bigger/equals to a given number.
The given number is also the amount of numbers in the array
This is what I have so far:
int checkarray(int *arr, int num)
{
int check = num;
int check2 = num;
int *lor;
int *poi;
int *another;
another = arr;
lor = arr;
poi = arr;
int check3 = num;
for ( ; num > 1; num--) {
for ( ; check3 >= 0; check3--) {
if (*arr == *poi)
return 0;
poi++;
}
arr++;
poi = another;
}
for ( ; check2 > 0; check2--) {
if (*lor >= check)
return 0;
lor++;
}
return 1;
}
I know that I made too many pointers/int for the function, but that's not the problem..
The part of checking for a given value works fine if I'm not mistaken so I think you can ignore that part (that's the last 'for' loop)
I know it should be easy but for some reason I just can't get it to work...
Edit:
I'll give an example: If the array is 0 1 2 3 1 the function will return 0, cause the second and the last number are identical. The function will also return 0 if the given number is 5, and one of the numbers is bigger or equals to 5, for example 0 1 2 5 4.
Otherwise, the function returns 1.
I create a new array where I'm going to save the numbers so I can check if you have a repeat number in the array. I also have one more argument in the function to know the size of the array.
#include <stdio.h>
#include <stdlib.h>
int checkArray(int *arr, int size, int number){
int i,j;
int *countArray = calloc(size,sizeof(int));
for(i=0;i<size;i++){
if(arr[i]>=number){ //Check >= number
free(countArray);
return 0;
}
for(j=0;j<i;j++){ //Check repeat number
if(countArray[j]==arr[i]){
free(countArray);
return 0;
}
}
countArray[j]=arr[i]; //no repeat number so we save it.
}
free(countArray);
return -1; //Error
}
int main(){
int arr[6] = {0,8,2,3,4,1};
printf("Result %d",checkArray(arr,6,5));
}
I hope this can help you.
Update without new array
int checkArray(int *arr, int size, int number){
int i,j;
for(i=0;i<size;i++){
if(arr[i]>=number){
return 0;
}
for(j=0;j<i;j++){
if(arr[i]==arr[j]){
return 0;
}
}
}
return -1; //Error
}
Change your upper for loop to:
for ( ; num > 0; num--) {
if(arr[i]>=number){
return 0;
}
int check3 = num;
poi=arr+1;
for ( ; check3 > 0; check3--) {
if (*arr == *poi)
return 0;
poi++;
}
arr++;
}
and remove the bottom one.
The mistakes here are as following:
1- You need to change the lines:
int check3 = num;
for ( ; num > 1; num--) {
to be:
for ( ; num > 1; num --) {
int check3 = check; // Move to inside loop to reset each time for a fresh inner loop and use check instead of num to reset the value
2- You need to change the line:
for ( ; check3 >= 0; check3--) {
To be
for ( ; check3 > 0; check3--) { // Because `>=0` means attempting to read past the array
3- poi should be initialised every time in the loop as arr+1 to skip comparing the same member of the array to itself, and to skip re-comparing members more than one time.
I suggest re-writing the method with better code style to enable easier detection of such errors and typos

Variable returned by Reference from a function gives weird values

I've been working on a hangman game lately, and this function supposedly checks for a letter that the user inputs in an array (Containing a pre-defined word such as "BUILDING") and adds on a Counter (Count) if the letter exists or decreases the lives (Which start at 5 -defined in the main function-) if it doesn't exist.
Now the Count variable works fine but the Lives variable keeps decreasing anyways, even if the letter exists and it doesn't just decrease by 1 but by bigger amounts resulting in rather big negative numbers.
Here's the code, thanks in advance:
void Checkf(char X,int r,int Length,char *Hidden, int *Lives,int *Count)
{
int i;
for (i=0;i<Length;i++)
{
if (X==Words[r][i] && Hidden[i]=='*')
{
Hidden[i] = X;
*Count = *Count + 1;
}
else if (X!=Words[r][i] && Hidden[i]=='*')
*Lives = *Lives - 1;
}
}
That behavior occurs because you (optionally) decrease the value of Lives on each iteration of the loop.
You can add a variable that indicates whether the letter was found or not, and then decrease the value of Lives after the loop ends, like this:
void Checkf(char X,int r,int Length,char *Hidden, int *Lives,int *Count)
{
int i;
unsigned char found = 0;
for (i=0;i<Length;i++)
{
if (X==Words[r][i] && Hidden[i]=='*')
{
Hidden[i] = X;
*Count = *Count + 1;
found = 1;
}
}
if (!found)
{
*Lives -= 1;
}
}

Resources