![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Newbie
|
return a value from a function
Hi all i am new to programming and after i learnt Pascal i try to learn C.I have working to this program and from the pinakas function i want to return to main the first negative value of the array or if there isn't a negative value to return the first value of the array.Here is the code
#include<stdio.h>
#define n 5
int *pinakas(int *pin);
main()
{
int *ptr,pin[n],i;
//fill the array
printf("Dwse ta stoixeia toy pinaka :\n");
for(i=0;i<n;i++)
scanf("%d",&pin[i]);
ptr=pinakas(pin);
printf("%d\n",*ptr);
}
int *pinakas(int *pin)
{
int k;
for (k=0;k<n;k++)
{
if(*(pin+k)<0)
return pin+k;
else
return pin;
}
}Any help? |
|
|
|
|
|
#2 |
|
I eat cake for breakfast.
![]() ![]() ![]() ![]() Join Date: Jul 2004
Location: In my box.
Posts: 4,434
Rep Power: 9
![]() |
The problem is that your function always returns a value on the first iteration. If it's negative, it returns it, otherwise, it returns it anyway. You want:
int *pinakas (int *pin)
{
int k;
for (k = 0; k < n; k++)
{
if (*(pin + k) < 0)
return (pin + k);
}
return pin;
} |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|