No return error in c - c

I'm getting an error saying no return for this function.
This function is supposed to return the number of even numbers in an array.
int even (int a[],int size){
int a;
for(a=0; a< size; a++)
{
if (abcdef[a] % 2 == 0)
{
printf("%d", abcdef[a]);
}
return 0;
}

If you want to return something, you have to
Calculate whatever you want to return
Add a return statement returning the result of your calculation.
In your code you are not doing either of these two things:
You have no variable that would keep count of even numbers, and
You are returning from the middle of your for loop.
To fix this, add an int count = 0 variable before the loop, increment it every time you print an even number, and move the return statement to the back of your code:
int count = 0;
for(...) { // Your "for" loop
if (...) { // if the number is even...
...
count++; // Increment the count
}
}
return count; // Return goes outside the loop

You should try something like this:
int even (int myArray[],int size){
int count = 0;
int a;
for(a=0; a<size; a++)
{
if (myArray[a] % 2 == 0)
{
printf("%d", myArray[a]);
count++;
}
}
return count;
}

Related

Going through user input and multi-dimensional arrays in C

I am trying to make a code where a user has 5 tries to guess a number and if any of the 3 series of numbers within Winning_order then both of the for loops will break. The usersInputs stores the users inputs to be compared with Winning_order. So for example, if the number 1,2,3 or 1,2,4,5,3 is inputted by the user the loop will print There is a Correlation and the for loops will stop. If the input is 7,8,9,3,2 since no 3 numbers are present within the Winning_order the loops will just stop. There is a problem with the match_arrays function and I do not know how to go about stopping the nested for loops if the if statement is valid.
Checking if the function has a correlation
int match_arrays(int *arr1, int *arr2, int len) {
for (int p = 0; p < len; p++) {
if (arr1[p] != arr2[p]) {
return 0;
}
}
return 1;
}
main() function
int main(void)
{
int Winning_order[3][3] = {{1,2,3}, {1,4,7}, {2,5,8}};
int input = 0;
int usersInputs[5] = {0};
for (int i = 0; i <= 4; i++){
printf("\nPlayer input: ");
scanf("%d", &input);
usersInputs[i] = input;
for (int p = 0; p < 5; p++) {
if (match_arrays(usersInputs, Winning_order[p], 3)) {printf("There's a Corelation");}
}}
return 0;
}
There are different ways of approaching breaking a double loop (or to generalize: a nested loop), this solution is not the optimal, the best, or the recommended, but it works. I fixed the indentation and some naming issues, but I won't fix anything else.
This is a working snippet:
#include <stdio.h>
int match_arrays(int *arr1, int *arr2, int len) {
for (int p = 0; p < len; p++) {
if (arr1[p] != arr2[p]) {
return 0;
}
}
return 1;
}
int main(void) {
int winning_order[3][3] = {{1,2,3}, {1,4,7}, {2,5,8}};
int input = 0;
int users_inputs[5] = {0};
for (int i, break_i = 0; !break_i && i < 5; i++){
printf("\nPlayer input: ");
scanf("%d", &input);
users_inputs[i] = input;
for (int p = 0; p < 3; p++) {
if (match_arrays(users_inputs, winning_order[p], 3)) {
printf("There's a Corelation\n");
break_i = 1;
break;
}
}
}
return 0;
}
I made this easy for you to understand. I added a new flag to the outer for loop called break_i with an initial falsy value. Simultaneously, I added a short circuit && operation to the for loop.
Inside your inner loop, I added a break_i = 1 statement that will make the outer loop stop. Immediately after that, I use the break statement to break the inner loop.
P.S.: I also fixed the index out of bounds pointed out by #kaylum. You may want to use a macro or sizeof() next time, but that's beyond the scope of your question.

C Program isn't returning anything

I wrote a C program to sort an array, but the program isn't returning anything -- it just runs and stuck there as if it is waiting for input. Below is the code:
#include<stdio.h>
bool unsorted(int ar[],int x){
int c;
for(int i=1;i<=x;i++){
if(ar[0]>ar[i]){
return true;
} else {
return false;
}
}
}
void sort(int arr[],int s){
int h,b;
while(unsorted(arr,s)){
h=arr[0];
for(int i=0;i<=s;i++){
if(arr[i]>h){
b=arr[i];
arr[i]=h;
h=b;
}
}
}
for(int i=0;i<=s;i++){
printf("%d",arr[i]);
}
}
int main(){
int arr[3]={ 2,1,3 };
sort(arr,3);
return 0;
}
Your function unsorted returns true if the first element ist not the smallest. It is not checked whether any other 2 elements are in wrong order. This will cause wrong results but is not the reason for current problem.
In your sorting loop you check if any element is larger than the first and then swaps them.
This means ascending order is changed to descending.
This will cause unsorted function to return true all the time and your loop never terminates.
To fix it change condition:
void sort(int arr[],int s) {
int h,b;
while (unsorted(arr,s)) {
h=arr[0];
for (int i = 1; i < s; i++) {
if (h > arr[i]) {
b = arr[i];
arr[i] = h;
h = b;
}
}
}
for (int i=0; i < s; i++) {
printf("%d",arr[i]);
}
}
Also the index range was fixed.
This should at least make your loop terminate.
It will not produce a sorted list as you terminate too early.
First of all your unsorted function needs some update:
bool unsorted(int ar[], int x) {
int c;
for (int i = 1; i < x; i++) {
if (ar[i-1] > ar[i]) {
return true;
}
}
return false;
}
This should also return true if first element is lowest but others don't fit like {1, 4, 3, 6}. Also note the fixed index range.
You need to apply a similar fix to the sorting part to handle out-of-order values in the elements after the first one.

How to reverse digits of each number in an array using pointer arithmetic

I tried to write a program in C that reverses all the numbers in an array, but it actually doesn't reverse anything, so I get unchanged numbers back. I guess I got something wrong with the pointers.
Here is my code:
#include <stdio.h>
void reverse(int *n) {
int number = *n, number2 = 0;
while (number!=0) {
number2 *= 10;
number2 += number % 10;
number /= 10;
}
*n = number2;
}
void ReverseDigits(int *p, int n) {
int i = 0;
while (i < n) {
reverse(&p);
p++;
i++;
}
}
int main() {
int array[3] = {123, 456, 789}, i = 0;
while (i < 3) {
ReverseDigits(array, 3);
i++;
}
return 0;
}
In ReverseDigits the variable p is an int pointer. When you do &p you'll get a pointer to int pointer. But your reverse function just expects an int pointer so your call of reverseis wrong. Simply do
reverse(p); // insteand of reverse(&p)
In main you shall not call ReverseDigits in a loop as the function already loops the array (i.e. the number of elements passed). So skip the while and simply do:
int main() {
int array[3] = {123, 456, 789};
ReverseDigits(array, 3);
return 0;
}
It seems to me that your reverse() function is "both baffling, and necessarily wrong." (Hey, don't take that personally...)
How could such a function possibly work, without being told, not only where the (array) is, but how long it is? You seem to be missing a parameter here.
Once you've settled that problem in your design, the task of "reversing" an array is simply a process of "swapping" the first-and-last elements in an algorithm that goes something like this: (pseudocode!)
function reverse( array[], array_size) {
int i = 0;
int j = array_size - 1; // since zero-based
while (i < j) { // no need to use "<=" here"
temp = array[i];
array[i] = array[j];
array[j] = temp;
i++;
j--;
}
}

filling 2d array with mutiplicatio table

#include<stdio.h>
#include<stdlib.h>
int** createMatrix(int n)
{
int i, a, **tab,x;
tab=(int**)malloc(n*sizeof(int*));
if(tab==0)
{
return NULL;
free(tab);
}
for(i=0;i<n;i++)
{
tab[i]=(int*)malloc(n*sizeof(int));
if(tab[i]==NULL)
{
for(x=0;x<i;x++)
{
free(tab[x]);
}
free(tab[i]);
return NULL;
}
}
}
void fillMatrix(int*** tab, int n)
{
int i, a;
for(i=0;i<n;i++)
{
for(a=0;a<n;a++)
{
*tab[i][a]=(a*i);
}
}
}
int main()
{
int roz, **tab,i,x;
printf("size of the array: \n");
scanf("%d",&roz);
tab=createMatrix(roz);
if(tab==NULL)
{
printf("error");
return -1;
}
fillMatrix(&tab, roz);
for(i=0;i<roz;i++)
{
printf("\n");
for(x=0;x<roz;x++)
printf("%d",tab[i][x]);
}
return 0;
}
Hi! I need to write a program that makes 2d arrays and I want to fill them with multiplication table. Program compiles without single warning or error, but after puttintan input it crashes. And by the way, could you tell me why I have to put 3x* in fillMatrix?
int** createMatrix(int n)
You should be returning the double pointer from the function which I see you are not doing.
int** createMatrix(int n)
{
int i, a, **tab,x;
tab=(int**)malloc(n*sizeof(int*));
// Do your allocations and other stuff
return tab;
}
Take care of accessing the elements using triple pointer. Like
(*tab)[i][a] = (a*i);
You can get the job done using doule pointers itself.
You have several problems
Pointeless free(tab) in your createMatrix() function, it's after the return statement, it will never be executed.
You free the tab[i] element which is NULL in createMatrix() inside the loop where you malloc the pointers of the array.
What you should do is
free(tab);
instead.
You never return the malloced tab.
Your fillMatrix() function is unecessarily taking a int *** triple pointer, you don't need that, if you pass the pointer you directly modify the data.
You have an operator precedence issue in fillMatrix()
*tab[i][a] = (a*i);
this doesn't mean what you think, first [] is applied, and then you dereference it with * which is equivalent to
*(tab[i][a]) = (a * i); -> *(tab[i][a]) -> tab[i][a][0]
what you want is
(*tab)[i][a] = a * i;
You don't free the pointers after printing them.
This is your code with all this issues fixed.
#include <stdio.h>
#include <stdlib.h>
int **createMatrix(int n)
{
int i, **tab, x;
tab = malloc(n*sizeof(int*));
if (tab == 0)
return NULL;
for (i = 0 ; i < n ; i++)
{
tab[i] = malloc(n * sizeof(int));
if (tab[i] == NULL)
{
for (x = 0 ; x < i ; x++)
free(tab[x]);
free(tab);
return NULL;
}
}
return tab;
}
void fillMatrix(int **tab, int n)
{
int i, a;
for (i = 0 ; i < n ; i++)
{
for (a = 0 ; a < n ; a++)
{
tab[i][a] = (a*i);
}
}
}
int main()
{
int roz, **tab, i, x;
printf("size of the array: \n");
scanf("%d", &roz);
tab = createMatrix(roz);
if (tab == NULL)
{
printf("error");
return -1;
}
fillMatrix(tab, roz);
for (i = 0 ; i < roz ; i++)
{
printf("\n");
for (x = 0 ; x < roz ; x++)
printf("%4d ", tab[i][x]);
printf("\n");
free(tab[i]);
}
free(tab);
return 0;
}
And by the way, could you tell me why I have to put *** in fillMatrix?
That is an excellent question. Incidentally, it provides the key to answering the "why does my program crash" question. The reason the program crashes is that you are using the matrix incorrectly: you treat it like a 2D array of pointers, rather than a pointer to a 2D array. If you add parentheses, your program would stop crashing:
(*tab)[i][a]=(a*i);
Better yet, change the program to take ** that it needs:
void fillMatrix(int** tab, int n) {
...
tab[i][a]=(a*i); // <<== No asterisk
}
...
fillMatrix(tab, roz); // <<== No ampersand
Note: when you compile your program, you should see the "control reaches the end of non-void function without returning a value". This is because you forgot to add return tab at the end of the function that creates your matrix.
Demo.
You asked:
And by the way, could you tell me why I have to put 3x* in fillMatrix?
That is not necessary. You could use:
void fillMatrix(int** tab, int n)
{
int i, a;
for(i=0;i<n;i++)
{
for(a=0;a<n;a++)
{
tab[i][a]=(a*i);
}
}
}

How do I write a function that returns true if every integer in the array is different?

I have to write a function that will return true if every integer in the array is unique (different). So, I've tried correcting my for loops/my if statement and I've tried running the tests that I wrote. But, the test for a string with an integer appearing more than once still fails. I've reviewed my code but I still can't find the problem.
#include "in.h"
int in(int input[], int size)
{
for (int i = 0; i < size - 1; i++)
{
for (int j = i + 1; j < size; j++)
{
if (input[i] == input[j])
{
return 0;
}
}
}
return 1;
}
Here are my test cases:
#include "in.h"
#include "checkit.h"
void in_tests(void)
{
int input[3] = {2, 4, 5};
int answer;
answer = in(input, 3);
checkit_int(answer, 1);
int input1[4] = {1, 3, 4, 1};
int answer1;
answer1 = in(input1, 4);
checkit_int(answer, 0);
}
int main()
{
in_tests();
return 0;
}
without sort, an O(n2):
j begins with i+1.
int IsDiff(int array[], int count)
{
int i,j;
for (i=0; i<count; i++)
{
for (j=i+1;j<count;j++)
{
if (array[i] == array[j])
return 0;
}
}
return 1;
}
If space is not an issue, then we can have a O(n) solution using a hashtable. Start storing each element of the array in a hashtable. While inserting elements, make a check to see if it already present in the hashtable ( which takes O(1) time.) If the element is already present, then return false immediately, else iterate until the end of array and return true.
actually, thats not why your function doesn't work. the main reason is because currently you are checking if any pair DONT match, which would be great if you wanted to see if all the elements matched, but you want to do the opposite, so you want to check the opposite, if any pair DOES match. so first change your if to be
if(input[i] == input[j]) return false;
if one pair is equal then you know that your test has already failed so there is no need to check the remaining pairs, just return false there and then.
the only other thing to do is to sort out your loops so that you only iterate over each pair once and don't compare a value against it's self. to do that change the for loops to be:
for(int i =0; i<size-1; i++)
for(int j=i+1; j<size; j++)
then if you make it to the end of the function, it means no pair as matched, so just return true;
O(n^2) as well.. but I added this function that makes the code more understandable...
int unique(int input[], int value,int size){
int times=0;
for (int i = 0; i < size; i++)
{
if(input[i]==value){
times++;
if(times==2)
return 0;
}
}
return 1;
}
int in(int input[], int size)
{
int x, answer;
for (int i = 0; i < size; i++)
{
if(!unique(input,input[i],size))
return 0;
}
return 1;
}
You are very close, try this:
#include "in.h"
int in(int input[], int size)
{
int answer = 1;
for (int i = 0; i < size-1; i++)
{
for (int j = i+1; j < size; j++) //check everything above your current
//value because you have already checked
//below it.
{
if (input[i] == input[j])
{
answer = 0; //If any are not unique you
break; //should exit immediately to save time
}
}
if (answer == 0)
break
}
return answer;
}
Thinking about the problem
let's say you have an array like this: int array[] = { 3, 1, 4, 8, 2, 6, 7, 7, 9, 6 };
if you start with the first element you need to compare to the rest of the elements in the set ; so 3 needs to be compared to 1, 4, 3... etc.
if 3 is unique you need to now go to 1 and look at the remaining elements, but next time around you don't need to worry about the 3 ; so your value under consideration (let's call that V) needs to be each of, array[0] to array[N-1] where N is the size of array (in our case 10);
But if we imagine ourselves in the middle of the array, we'll notice that we have already compared previous elements to the current element when the previous element was the value under consideration. So we can ignore any elements "behind" us; which means comparison has to start the each time with the INDEX of current value under consideration (let's call that k) and compare it to values starting with the NEXT index and going to the end of the array ; so pseudo-code for our array of 10 it would look like this:
int is_a_set(int array[])
{
for ( k = 0; k < 10-1 ; k++ ) { /* value under consideration */
v = array[k];
for ( m = k+1 ; m < 10; m++ ) { /* compared to the remaining array starting
* starting from the next element */
if ( v == array[m] ) { /* we found a value that matches, no need to
* to continue going, we can return from this function
*/
return true;
}
}
}
return false;
}
now you can use something like:
if ( is_a_set(my_array) ) {
}
You should be able to use this to figure the rest of your code out :-)
NOTE: a collection with unique elements is called a set so I named the function is_a_set
HINTS: convert size of the array (10) into a parameter or a variable of some sort
Here's my attempt at it (very simple and inefficient though):
#include <stdio.h>
int uniq_int(int arr [], int size)
{
int i, j;
for (i = 0; i < size; i++)
for (j = i + 1; j < size; j++)
if (arr[i] == arr[j])
return 0;
return 1;
}
int main()
{
int arr [] = {1, 2, 4, 3, 5};
(uniq_int(arr, 5)) ? printf("Unique!\n") : printf("Not...\n");
/* the above can be written more traditionally like this:
if (uniq_int(arr, 5) != 0)
{
printf("Unique!\n");
}
else
{
printf("Not...\n");
}
*/
return 0;
}
This will compare every member of the array against the rest, starting from the first
and comparing it against the next one and so on until the end of the inner loop.
Then we start the outer loop again but this time we compare the second element of the array against the ones after it.
As soon as a match is found the function will return and there won't be a need to compare the other elements. Otherwise the outer loop will go on until the last element and once that's reached it will exit and return 1, meaning every member is unique.
It has a complexity of O(n^2) as the set is processed twice for each member in the worst case.

Resources