2019-10-05 18:59:46 (edited by Ethin 2019-10-05 19:00:59)

Though there is a min, max, and minmax function in the C++ stdlib, your problem is in C, not C++. This is where a nice sorting algorithm comes into play. I will take the code from this page on RosettaCode and implement it into your program to show you how you would do it (this is with Heapsort, though other algorithms will work too). This will complicate your code, but it will also (always) give you the largest and smallest values in your list.

#include <stdio.h>

long long max (long long* a, long long n, long long i, long long j, long long k) {
long long m = i;
if (j < n && a[j] > a[m]) {
m = j;
}
if (k < n && a[k] > a[m]) {
m = k;
}
return m;
}
 
void downheap (long long* a, long long n, long long i) {
while (1) {
long long j = max(a, n, i, 2 * i + 1, 2 * i + 2);
if (j == i) {
break;
}
long long t = a[i];
a[i] = a[j];
a[j] = t;
i = j;
}
}
 
void heapsort (long long* a, long long n) {
for (long long i = (n - 2) / 2; i >= 0; i--) {
downheap(a, n, i);
}
for (long long i = 0; i < n; i++) {
int t = a[n - i - 1];
a[n - i - 1] = a[0];
a[0] = t;
downheap(a, n - i - 1, 0);
}
}

int main() {
int n;
long long maximum = 0;
long long minimum = 0;
printf("Enter a number between 1 to 300:");
scanf("%d",&n);
long long* list = (long long*)malloc(sizeof(long long)*n);
for (long long i = 0; i < n; i++) {
printf("Enter the number %d",i+1);
scanf("%d",&list[ i ]);
}
heapsort(list, n);
// Element 0 contains smallest number, element n-1 contains largest.
// ...
}

This could be greatly simplified to be a much smaller LOC count, but this also works (and isn't overblown, since you now, with that list, can get any number in a sorted way). Don't forget to free() the memory that I allocated (or you can rewrite it to suit your needs). I would encourage you to go try implementing this on your own though; I may have provided a sample, but you won't learn anything by copy-pasting it. This code is also versatile; you can easily replace the sorting algorithm I chose with something different if you so choose.

"On two occasions I have been asked [by members of Parliament!]: 'Pray, Mr. Babbage, if you put into the machine wrong figures, will the right answers come out ?' I am not able rightly to apprehend the kind of confusion of ideas that could provoke such a question."    — Charles Babbage.
My Github

2019-10-06 01:12:01

The above code is overly complicated and less efficient than a simple solution. You absolutely do not need a complicated sorting algorithm to find the minimum and maximum numbers in an array (besides, heapsort is O(n log n) and finding minimum and maximum of an array is just O(n) efficiency).

The problem with the code is this section

for(i=1;i<n;i++)
{
if(list[0]<list[ i ])
{
maximum=list[0];
}
if(list[1]>list[ i ])
{
minimum=list[1];
}//if closed.
}//loop closed

The problem is that you are always comparing the current list item with the first or second (indexes 0 and 1), wihch means you won't end up with the accurate maximum or minimum. To get this to work, you need some base value for minimum and maximum to start out as, before the loop even begins. The first element in the array or list or whatever works (in this case set minimum and maximum to

list[0]

). Now you can iterate through the list. If the current element (

list[i]

) is less than minimum, simply set minimum to

list[i]

. Likewise if

list[i]

is greater than maximum, set maximum to

list[i]

. Also the for loop should start at i=0 not i=1.

Deep in the human unconscious is a pervasive need for a logical universe that makes sense. But the real universe is always one step beyond logic.

2019-10-07 12:10:47

Thanks again, guys.

2019-10-07 15:42:19

@52, I did already say it was overcomplicated... but it is a good way of killing two birds with one stone. He can learn algorithms/data structures as well as this at the same time.

"On two occasions I have been asked [by members of Parliament!]: 'Pray, Mr. Babbage, if you put into the machine wrong figures, will the right answers come out ?' I am not able rightly to apprehend the kind of confusion of ideas that could provoke such a question."    — Charles Babbage.
My Github

2019-10-14 20:10:32

In this problem, I have to divide two numbers, and if there is a fractional part in the result, ad
0.5
If it is positive, or minus
0.5
If negative.

The final result which would be printed is a truncated intijer, with the 0.5 added to it.

Aside from that, if the result is a perfectly divizible without any decimal points, then print it as normal.

For example, 12/8=0.5

But when I print it as a intiger, it truncates to 1. if the 0.5 is also added to it, it should print 2.

I tried this approach:
if(result>0)
{
result=result+0.5;
}
else
{
result=result-0.5
}

Of course it did not worked as it was supposed to. while this did gave me correct values if the divide was perfect and did not resulted in a decimal. but the decimal part did not gave me the result as I thought, it still gave me the result 1.

Any ideas for this one?

2019-10-14 20:51:57 (edited by Ethin 2019-10-14 20:52:48)

Give this a try:

#include <math.h>
// ...
if (val != (int)val) { // check for fractional part
float iptr;
float integral_part = modf(val, &iptr);
if (iptr > 0.5) {
val += 0.5;
} else if (iptr < -0.5) {
val -= 0.5;
}
}

It may not work on the else condition; the docs say:

C++ Reference (cppreference) wrote:

If the implementation supports IEEE floating-point arithmetic (IEC 60559),

  • If arg is ±0, ±0 is returned, and ±0 is stored in *iptr.

  • If arg is ±8, ±0 is returned, and ±8 is stored in *iptr.

  • If arg is NaN, NaN is returned, and NaN is stored in *iptr.

  • The returned value is exact, the current rounding mode is ignored.

Source: https://en.cppreference.com/w/c/numeric/math/modf

"On two occasions I have been asked [by members of Parliament!]: 'Pray, Mr. Babbage, if you put into the machine wrong figures, will the right answers come out ?' I am not able rightly to apprehend the kind of confusion of ideas that could provoke such a question."    — Charles Babbage.
My Github

2019-10-14 21:22:19

@55 Hello.
Could you post the entire code?
If not, of which type is result?

Paul

2019-10-15 11:43:38

@pauliyobo:
Here's the code:

#include <stdio.h>
int main(void)
{
int i, n;
long result, dividend, divizer;
printf("Enter the numbers of pairs which you wish to divide:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the numbers for divide:");
scanf("%d%d",&dividend,&divizer);
result=dividend/divizer;
if(result>0)
{
result=result+1;
}

else
{
result=result-1;
}
printf("the result is %d\n",result);
}
return 0;
}

The result is supposed to be a rounded intijer if there is a fractional part, (Like 1.2 3.9 with the intiger rounded to 1 or 3, with 0.5 added to it.)

hope that clears things.

2019-10-15 13:36:32 (edited by pauliyobo 2019-10-15 13:37:59)

This should work

#include <stdio.h>
#include <math.h>

int main(void)
{
int i, n;
long dividend, divizer;
double  result;
printf("Enter the numbers of pairs which you wish to divide:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the numbers for divide:");
scanf("%d %d",&dividend,&divizer);
result = dividend/divizer;
if(result != (int)result && result > 0.0)
{
result = round(result+0.5);
}
else
{
result = round(result-0.5);
}
printf("the result is %d\n", result);
}
return 0;
}
I'm checking if result is equal to result casted to an int, because of course the fractional part will be truncated when converted to an integer.
Hope this helps.
If I done something wrong, please feel free to say so.

Paul

2019-10-15 14:52:20

Thanks for clearing that up -- I thought my solution was the one. smile

"On two occasions I have been asked [by members of Parliament!]: 'Pray, Mr. Babbage, if you put into the machine wrong figures, will the right answers come out ?' I am not able rightly to apprehend the kind of confusion of ideas that could provoke such a question."    — Charles Babbage.
My Github

2019-10-15 18:46:01 (edited by Dark Eagle 2019-10-15 18:51:08)

@pauliyobo
thanks for the answer. this will be the first time when I would use any other header file except for stdio. guess that is what happen when you move forward.

I ran your solution, and the compiler gives me the warning that the format string %d requires the argument of type int, but the result variable has the type double.

one more thing though, if it is not too much of a bother, would you mind explaining the condition below?
if(result != (int)result && result > 0.0)
I am asking because I want to understand whether it is exactly as it is I am thinking, or something different.

@Ethin:
you always take time to answer my questions. but would you mind taking the level down a little bit? I don't think that I can understand what you are trying to tell me sometimes.

hope that does not make you mad.

2019-10-15 18:55:26 (edited by Ethin 2019-10-15 18:56:21)

@61, appologies if I overwhelm you -- that is not my intent.
The expression

if(result != (int)result && result > 0.0)

determines if the floating point number has a fractional part. The fractional part is the number after the decimal point. So if we had a number like 2.5220, the fractional part would be 5220. (We could do that with strings, but that would be unnecessarily over complicated.) This expression, in particular, compares result to its integral version of itself. Naturally, a number with a fractioanl part and one without are entirely different. So, this translates to:

if result has a fractional part and result is greater than zero

.
HTH

"On two occasions I have been asked [by members of Parliament!]: 'Pray, Mr. Babbage, if you put into the machine wrong figures, will the right answers come out ?' I am not able rightly to apprehend the kind of confusion of ideas that could provoke such a question."    — Charles Babbage.
My Github

2019-10-15 19:10:56

@Ethin:
thanks for the explanation.

@pauliyobo:
I think I can handle the problem through typecast, since these are not the things with which I have a lot of practice, the experience will be good for me.

2019-10-15 19:54:18

Sorry. replace the printf statement with this one
printf("the result is %f\n", result);
@62 thanks for taking the time to explain this, I was in a hurry when I posted the code and didn't explain as detailed as I had to.

Paul

2019-10-15 21:08:02

@64, no problem. I understanding having too much to do and not enough time to do it (college, much?).

"On two occasions I have been asked [by members of Parliament!]: 'Pray, Mr. Babbage, if you put into the machine wrong figures, will the right answers come out ?' I am not able rightly to apprehend the kind of confusion of ideas that could provoke such a question."    — Charles Babbage.
My Github

2019-11-20 15:14:09

So, in a problem to count vowels within a string, I must test multiple strings, and count the vowels present within them.

The issue is, the code below does not tests the entire string, it exits after finding one vowel, and it only tests one string, doesn't matter whether I entered four or five strings which I wish to test.

#include <stdio.h>
int main()
{
int i, n, temp=0, vowels=0;
char string[100];
printf("How many strings do you wish to test?");
scanf("%d",&n);
for(i=0;i<n;i++)//This loop is for the number of strings which the user would like to test.
{
printf("Plese enter strings one by one:");
scanf("%s",string);
while(string[temp] !='\0')//this is where the condition to find the vowels is.
{
if(string[temp]=='a'||string[temp]=='e'||string[temp]=='i'||string[temp]=='o'||string[temp]=='u')
{
vowels++;
}
temp++;
}
printf("there are %d vowels within this string",vowels);
}
return 0;
}

2019-11-20 15:27:10 (edited by Hijacker 2019-11-20 15:30:13)

Hi,
you forgot to reset almost all variables on every for loop cycle. I'd recommend to always replay your algorithm on paper to see if it works or doesn't, and always just stick to the code you wrote, not how you'd like it to actually work. You'll notice, that temp will be 0 when beginning to check the first string. Imagine the first vowel to be at position 1, the second at 3, the third at 8, the fourth at e.g. 12... and so on. Temp will be increased until it finds the first \0, which can be e.g. at position 20.
It will print the amount of vowels correctly. Now you enter the next string, and the while loop will start at string[temp] again, but wait, temp is still 20. If the string isn't long enough, the while loop will already stop here, and continue to ask you for your next string. Your amount of vowels also doesn't reset, so it will actually accumulate all vowels found in all of your strings, not just the ones in one single string you entered.
What could also be a problem is that you don't reset your char array between fills. That means, if you first enter the string "this is a test" and right afterwards the string "hello", the char array will contain "hello\0s a test". Thats not big of a problem, but scanf() doesn't always append a \0 to the string you entered, which might end up in a mixed string. I'd recommend to use a method like memset(string, '\0', 100); to reset your char array before the user enters a new value.
And now the probably fixed code:

#include <stdio.h>
#include <string.h>

int main()
{
  int i, n, temp, vowels;
  char string[100];
  printf("How many strings do you wish to test?");
  scanf("%d",&n);

  for(i=0;i<n;i++)//This loop is for the number of strings which the user would like to test.
  {
    memset(string, '\0', 100);
    printf("Plese enter strings one by one:");
    scanf("%s",string);

    temp = 0;
    vowels = 0;

    while(string[temp] !='\0')//this is where the condition to find the vowels is.
    {
      if(string[temp] == 'a' ||
         string[temp] == 'e' ||
         string[temp] == 'i' ||
         string[temp] == 'o' ||
         string[temp] == 'u')
      {
        vowels++;
      }
      temp++;
    }
    printf("there are %d vowels within this string",vowels);
  }
  return 0;
}

Didn't test it though, should work I guess big_smile.

Note that I fixed the formatting a bit. I'd recommend to get used to properly formatting your code, that will drastically improve your skills when working together with sighted people.
Best Regards.
Hijacker

2019-11-21 04:47:17

Thanks Hijacker. strings is the topic which I have the least amount of knowledge, of course I am rectifying this. hope you guys would still be patient with me by the time I am done with strings.

Also, any tips for formatting my code? indentation and such are impossible, since  I have zero percent vision. but I am willing to learn other ways.

2019-11-21 04:55:22

@68, no, indentation is not impossible. Set your editor to convert tabs to spaces (or just use tabs). For each {, indent by one tab/x amount of spaces for each line within the block. For each }, remove one level of indentation. Maintain indentation levels as best you can (some IDEs and editors do this automatically for you).

"On two occasions I have been asked [by members of Parliament!]: 'Pray, Mr. Babbage, if you put into the machine wrong figures, will the right answers come out ?' I am not able rightly to apprehend the kind of confusion of ideas that could provoke such a question."    — Charles Babbage.
My Github

2019-11-21 09:21:31

Ethin is right, even though you're blind, indentation should become normal for you. Some programming languages like Python require you to indent properly, because they don't have blocks and the indentation decides upon the code execution for you. Its simply a matter of training and getting used to it.
Another thing is to prevent too long lines of code (70 to 80 characters a line, including indentation, should be the maximum. Developers tend to align their screens not vertically, but horizontally, which means that they'd have to scroll to read longer lines, which takes up much time, so keep your lines shorter and break it if possible, just as I did in your code example above.
Best Regards.
Hijacker

2019-11-21 18:04:36

Thanks. next time when I need help, and when I will put my code here, I will try to format it to best of my ability. just tell me whether I did it correctly or not.

As for ides, I haven't used an ide for my entire c learning. it has been always like this: type the code in notepad, compile it through the command line, check the program is performing is correctly or not, rinse and repeat as many times as necessary.

I used MinGW for compiling in the past, but I got sick of it when I couldn't find the documentation online. so I decided to switch over to visual studio.

Despite the c++ being the language of focus, I can write and compile the code through its command line, which has a nice documentation. so still, I am using notepad for this. though I think I should switch my editor in the future.

2019-11-21 18:14:06

Notepad is fine, In fact, I'm using it myself all the time, or at least a close alternative, Notepad2 right now. Some IDEs may be accessible and helpful, but I didn't find one I liked to use yet. The accessible ones like Eclipse tend to be rather slow compared to simple editors, and I don't like that. Most languages support CMD and thus you can stick with your way, but i'd recommend to format your code properly anyway smile.
Best Regards.
Hijacker

2019-11-21 19:23:54

I use notepad as well.
notepad2 might make you faster on code indentation as it has auto indenting, but that depends on the familiarity you have with indenting.
If I have to compile small  c projects I tend to use gcc or g++ if I am working with c++. If not I just use CMake to build the visualstudio solution and then build it.

Paul

2020-04-23 18:22:45

So I was trying to solve this problem about evaluating expressions on CodeWars, and I did actually managed to code the solution.

Except that the solution I coded is giving me an error with which I am unfamiliar with, (The error is described below,) and I am not sure how to look that up on the google.

As an experiment, I tested my solution with a full program, (CodeWars only gives you the functions to solve,) and my solution is working in my system without error, so I am not sure what is wrong.

Below I have given the entire program, with the line which is giving me error having a comment just after it describing what the error is.

#include <stdio.h>
int expression_matters(int, int, int);
int main(void)
{
int r, a, b, c;
printf("Enter three values:");
scanf("%d%d%d", &a, &b, &c);
r= expression_matters(a, b, c);
printf("%d is the largest value of this expression.", r);
return 0;
}
int expression_matters(int a, int b, int c)
{
int d, e, f, g;
d = a* (b+c);
// Above line gives the error called object type 'int' is not a function or function pointer.
e = a * b * c;
f = a * b +c;
g = (a + b) * c;
if(d > e &&
d > f &&
d > g)
{
return d;
}
if(e > d &&
e > f &&
e > g)
{
return e;
}
if(f > d&&
f > e &&
f > g)
{
return f;
}
if(g > d &&
g > e  &&
g > f)
{
return g;
}
}

2020-04-23 21:39:19

I think what is happening is that the compiler on their end could be trying to evaluate the B + C part as a pointer.  Perhaps try changing the offending line to something like this?
int temp = a;
temp *= (b+c);
d = temp;
Alternative way is to figure out the result of BNC combined together and then use that in your code. The parentheses are the issue here, As far as I can tell.