Pythagorean triplets program - c

I have written a program that should be rather simple but on execution, it is not giving the wanted results. Even when debugging the program, I guess I found the error (getting stuck in the first if condition) but I'm not able to solve it (my inexperience perhaps). Anyways, this program, which should have been frugal, took 3 days whereas I expected it to take mere hours. Please help me with guiding me where I'm going wrong and how to solve it.
Here is the code
/*WAP to read pre entered no. of ints. consider only +ve and print the pythagorean triplets in them.*/
#include <stdio.h>
int main(){
int c,p,pp,count=0,a;
printf("How many entries to accept?\n");
scanf("%d",&a);
printf("Enter the nos.\n");
for (int i = 0; i < a; i++)
{
scanf("%d",&c);
if (c<0) //skip -ve nos.
{
continue;
}
if (count==0)
{
pp=c;
count++;
}
else if (count==1)
{
p=c;
count++;
}
else if ((pp*pp)+(p*p)==(c*c)) //Tracking count not necesarry after first three
{
printf("Pythagorean triplet found\n");
printf("%d %d %d",pp,p,c);
pp=p;
p=c;
}
}
return 0;
}
The main objective is to first scan a no. to signify the inputs to be read. Then scan the inputs, separated by a space or enter, in a loop which will only accept the no. of inputs stated before. It should neglect any -ve entries. It should print out the Pythagorean triplet if it encounters one, in a consecutive manner i.e. the triplet should appear one after the other & not randomly. We have to do the task without using arrays.
sample input is (you can consider any)(all given through the terminal)
(no. of entries)
6
1 -1 3 4 -4 5
(Here it will ignore -1 & -4)
expected output will be
Pythagorean triplet found
3 4 5
I am still learning so sorry for the elaborate program.
Thank you in advance.

since I cant see the input file I dont know if the values are sorted, since we need to identify which is the hypotenuse, makes it a bit more fiddly.
Also not clear what 'skip negatives' means. Does it mean
that we might see 3 -6 4 5 and say 'yes 3,4,5' is a triple
that we might see 3 -4 5 and say yes 3 4 5
or that we might see 3 -4 5 and simply ignore the whole set
I have assumed the first one
#include <stdio.h>
int main() {
printf("How many entries to accept?\n");
int a;
if (scanf("%d", &a) != 1) {
printf("bad input\n");
return (-1);
}
printf("Enter the nos.\n");
for (int i = 0; i < a; i++)
{
int sides[3] = { 0 };
int max = 0; // longest side length -> hypot
for (int j = 0; j < 3; j++)
{
int c;
if (scanf("%d", &c) != 1) {
printf("bad input\n");
return (-1);
}
if (c < 0) //skip -ve nos.
j--; // try again
else {
if (c > max) {
max = c;
}
sides[j] = c;
}
}
int hyp = max * max; // hypotenuse squared
int adjTot = 0; // adj sides squared total
for (int j = 0; j < 3; j++)
{
if (sides[j] == max)
continue;
adjTot += sides[j] * sides[j];
}
if (adjTot == hyp)
printf("%d %d %d is py\n", sides[0], sides[1], sides[2]);
else
printf("%d %d %d isnt py\n", sides[0], sides[1], sides[2]);
}
return 0;
}
Since you say you are reading from a file it just exits if there is non numeric data

Related

How to make this program more efficient at expressing its purpose? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I wrote a simple program to find greatest among three numbers. But it seems that I wrote it in a way that makes it slightly confusing - hard to understand. What would be the way to improve this program to make it better at expressing its purpose and operation, and to remove the obvious repetition?
main()
{
int a,b,c;
printf("Enter three numbers: ");
scanf("%d %d %d",&a,&b,&c);
if (a==b && b==c)
printf("all are equal....:)");
else if(a>b)
{
if(a>c)
printf("%d is greatest among all",a);
else
printf("%d is greatest among all",c);
}
else
{
if(b>c)
printf("%d is the greatest among all",b);
else
printf("%d is the greatest among all",c);
}
getch();
}
#include <stdio.h>
int max(int a, int b)
{
return (a > b) ? a : b;
}
int main(void)
{
int a, b, c;
printf("Enter three number: ");
scanf("%d %d %d", &a, &b, &c);
if ((a == b) && (b == c))
{
printf("all are equal.");
}
else
{
printf("%d is the greatest among all", max(a, max(b, c)));
}
return 0;
}
I'd like to offer an example of the development process that could lead to figuring it out. I've linked relevant documentation to fill in the likely gaps in knowledge, and attempted to explain what led me to that documentation. Variants of such thought process are common among developers, yet the process is regrettably often not explained in educational settings, and must be acquired by "sweat and tears". I figure: let's shed some light on it!
A decent reference to the C language and standard library is https://en.cppreference.com/w/c (yes, it's cppreference, but it's not just for C++!).
The clarity of this program matters, and it certainly could be improved.
But people also interpret efficiency to mean speed. But: The speed of this particular program is irrelevant. The slowest element is the human, by more than 6 orders of magnitude vs. the machine. If you wished for this code to be faster when e.g. working on a large array of triples of numbers, then you could edit the question and instead provide an example that works through a big array of triples. As it stands, the program could be written in a shell script file and you wouldn't be able to tell the difference. It's a good idea to optimize what matters - and maintainability often matters more than raw performance :)
Output Skeleton
You only need to print the largest number - so let's start with a way to print it, and assume that the selection of the largest number, and the detection whether they are all equal, has been taken care of:
#include <stdio.h>
int main() {
char all_equal;
int max;
// to be done
if (all_equal) printf("All numbers are equal.\n");
else printf("%d is the greatest among the numbers entered.\n", max);
}
Thus, we have a skeleton for the output of the program. That's our goal. It helps to start with the goal expressed in the language of the problem domain - here in C - for it can focus and guide the implementation. We know exactly where we're going now: we have to get the input, and then process it to obtain the max value, and the all_equal predicate (a boolean: zero means falseness, anything else means truth).
We could actually turn this goal into a functional program by providing some "fake" data. Such data could be called test data, or mock data, depending on who you ask :)
#include <stdio.h>
int main() {
char all_equal = 0;
int max = 10;
if (all_equal) printf("All numbers are equal to %d.\n", max);
else printf("%d is the greatest among the numbers entered.\n", max);
}
We can run this, then change all_equal to 1 and see how the output is changed. So - we have some idea about what results should be fed into the output section of the program.
Processing
Getting the input from the user is on the opposite end of the goal, so let's work on something that builds up directly on the goal: let's compute those all_equal and max values! The processing code should replace the mock char all_equal = 0; int max = 10; section.
First, we need some numbers - we'll use mock data again, and from them we need to select the largest number:
int numbers[3] = {-50, 1, 30}; // mock data
char all_equal = 0; // mock data
int max = numbers[0];
for (int i = 1; i < 3; i++) {
if (numbers[i] > max) max = numbers[i];
}
Modern compilers will usually unroll this loop, and the resulting code will be very compact. The i loop variable won't even appear in the output, I'd expect.
We can foresee a potential for mistakes: if we ever decide to change the quantity of numbers, we can easily miss a place where such quantity is hardcoded (here as the literal 3). It'd be good to factor it out:
#define N 3
int numbers[N] = {-50, 1, 30}; // mock data
char all_equal = 0; // mock data
int max = numbers[0];
for (int i = 1; i < N; i++) {
if (numbers[i] > max) max = numbers[i];
}
You'll run into such #define-heavy code. It has its place back when C compilers were poor at optimizing code. Those times are now thankfully well over, but people continue doing this - without quite understanding why it is that they do it.
For numeric constants, it's usually unnecessary and counterproductive: the preprocessor does string substitution, so it has no idea what the code it modifies actually means. Preprocessor definitions "pollute" the global context - they leak out from wherever we define them, unless we explicitly #undef-ine them (How many people do that? You'll find that not many do.)
Instead, let's express it as a constant. We try:
const int N = 3;
int numbers[N];
But: this doesn't compile on some compilers. Huh? We read up on array declarations, and it seems that iff variable-length arrays (VLAs) are not supported by our compiler, then the number of elements must be a [constant expression][constexpr]. C doesn't consider a const int to be a constant expression (how silly, I know!). We have to kludge a bit, and use an enumeration constant to get the constant expression we need:
enum { N = 3 };
int numbers[N] = {-50, 1, 30}; // mock data
char all_equal = 0; // mock data
int max = numbers[0];
for (int i = 1; i < n; i++) {
if (numbers[i] > max) max = numbers[i];
}
We start by assigning the value of the first number in the list (index 0!) to max. Then we loop over subsequent numbers (starting with index 1!), compare each to the maximum, and update the maximum if a number happens to be greater than the maximum.
That's half of the goal: we got max, but we also need all_equal! The check for quality can be done in the same loop as the selection of the maximum (greatest number), thus:
enum { N = 3 };
int numbers[N] = {-50, 1, 30}; // mock data
char all_equal = 1;
int max = numbers[0];
for (int i = 1; i < N; i++) {
all_equal = all_equal && numbers[i] == max;
if (numbers[i] > max) max = numbers[i];
}
// here we have valid all_equal and max
We start with the assumption that the numbers are all equal (all_equal = 1). Then, for each subsequent number (indices 1 onwards), we check if the number is equal to the maximum, and we use a logical conjunction (logical and - &&) to update the all_equal proposition. Proposition is what we call a boolean: simply a statement that can be either true (here: non-zero) of false (zero). The conjunction applied repeatedly to all_equal has the effect of a one-way valve: once all_equal goes false, it will stay false.
Logicians would state it as ∀ p ∈ ℙ : (false ∧ p) = false. Read: for all ℙropositions p, false and p is false.
We merge this into our skeleton, and get a slightly more useful program. It still uses mock data, but it performs all the "interesting" parts of the problem.
#include <stdio.h>
int main() {
enum { N = 3 };
int numbers[N] = {-50, 1, 30}; // mock data
char all_equal = 1;
int max = numbers[0];
for (int i = 1; i < N; i++) {
all_equal = all_equal && numbers[i] == max;
if (numbers[i] > max) max = numbers[i];
}
if (all_equal) printf("All numbers are equal.\n");
else printf("%d is the greatest among the numbers entered.\n", max);
}
We can run this code, tweak the mock data, and verify that it appears to do what we want it to! Yay!
Input
Finally, we should get those numbers from the user, to get rid of the final bit of mock data:
#include <stdio.h>
int main() {
enum { N = 3 };
int numbers[N];
printf("Enter %d numbers:\n", N);
for (int i = 0; i < N; i++) scanf("%d", &numbers[i]);
char all_equal = 1;
int max = numbers[0];
for (int i = 1; i < N; i++) {
all_equal = all_equal && numbers[i] == max;
if (numbers[i] > max) max = numbers[i];
}
if (all_equal) printf("All numbers are equal.\n");
else printf("%d is the greatest among the numbers entered.\n", max);
}
We run it, and hey! It seems to work! This program is equivalent to the one you wrote. But. There's always a "but".
Handling Invalid Input
Software testing now begins in earnest. We "play" some more with the program (we "exercise" it), and notice that the program doesn't react any differently when a non-number is entered. It sometimes seems to ignore the invalid number and still provide sensible result based on other, correct, numbers, but sometimes it just spits out a random value. Random value - hmm. Could perhaps one of the numbers be uninitialized?
We read the documentation of scanf() and notice that it won't modify its output argument if it fails! Thus the program has undefined behavior: here it results in "random" output.
Reading on, we find that the return value of scanf() can be used to check if it was successful. We'd like to handle invalid input and provide some feedback:
int main() {
enum { N = 3 };
int numbers[N];
printf("Enter %d numbers.\n", N);
for (int i = 0; i < N; /*empty!*/) {
printf("#%d: ", i+1);
if (scanf("%d", &numbers[i]) != 1)
printf("Sorry, invalid input. Try again.\n");
else
i++;
}
...
}
We [try again][run4], and the program goes into an infinite loop as soon as invalid input is provided. Hmm. Something weird is going on. We read up on the issue of parsing user input in C, and realize that scanf() alone won't work correctly if any input errors are present, since the input remains in the input buffer - it will keep "tripping" subsequent scanf's. We must remove that input before retrying.
To find a function that may do that, we read up on the C input/output library and find the getchar() function. We use it:
int main() {
enum { N = 3 };
int numbers[N];
printf("Enter %d numbers.\n", N);
for (int i = 0; i < N; /*empty*/) {
printf("#%d: ", i+1);
if (scanf("%d", &numbers[i]) != 1) {
printf("Sorry, invalid input. Try again.\n");
char c;
while ((c = getchar()) != '\n'); // remove input until end of line
} else
i++;
}
...
}
We try it again, and things seem to work. But! We can do something else: let's try closing the input stream (^Z,Enter on Windows, ^D on Unix). The program goes into an infinite loop - again.
Aha! End of input - EOF! We must explicitly handle the EOF (end of file/read error) condition, and the best we can do then is to stop the program. How? We read up about C program utilities, and find a perfect function that would abort the program: abort(). Program utilities are utilities that used to manage "other" tasks that a program might do - tasks that don't fall under other categories (are not I/O, math, etc.).
#include <stdlib.h> // added for abort()
int main() {
enum { N = 3 };
int numbers[N];
printf("Enter %d numbers.\n", N);
for (int i = 0; i < N; /*empty*/) {
int c;
printf("#%d: ", i);
c = scanf("%d", &numbers[i]);
if (c == EOF) abort();
if (c != 1) {
printf("Sorry, invalid input. Try again.\n");
while ((c = getchar()) != EOF && c != '\n');
if (c == EOF) abort();
} else
i++;
}
...
}
We try yet again, and this time things really seem to work fine. No matter what we throw at the program, it behaves reasonably: if the input is still available, it asks the user to enter the number again. If the input won't be available anymore (EOF indicates that), we abort().
In even more deviousness, we try to surround the numbers with spaces and tabs in our input - after all, it's just whitespace, and to a human it'd look like valid input in spite of the spaces. We try it, and no problem: scanf() seems to do the "right thing". Hah. But why? We read into the scanf() documentation, and discover that [emphasis mine]:
All conversion specifiers other than [, c, and n consume and discard
all leading whitespace characters (determined as if by calling
isspace) before attempting to parse the input. These consumed
characters do not count towards the specified maximum field width.
Complete Program
We now got all the pieces. Put them together, and the complete program is:
#include <stdio.h>
#include <stdlib.h>
int main() {
enum { N = 3 };
int numbers[N];
printf("Enter %d numbers.\n", N);
for (int i = 0; i < N; /*empty*/) {
printf("#%d: ", i+1);
int c = scanf("%d", &numbers[i]);
if (c == EOF) abort();
if (c != 1) {
printf("Sorry, invalid input. Try again.\n");
while ((c = getchar()) != EOF && c != '\n');
if (c == EOF) abort();
} else
i++;
}
char all_equal = 1;
int max = numbers[0];
for (int i = 1; i < N; i++) {
all_equal = all_equal && numbers[i] == max;
if (numbers[i] > max) max = numbers[i];
}
if (all_equal) printf("All numbers are equal.\n");
else printf("%d is the greatest among the numbers entered.\n", max);
}
Try it out!.
Useful Refactoring
This works fine, but the input processing dominates over main, and seems to obscure the data processing and output. Let's factor out the input, to clearly expose the part of the program that does "real work".
We decide to factor out the following function:
void read_numbers(int *dst, int count);
This function would read a given count of numbers into the dst array. We think a bit about the function and decide that a zero or negative count doesn't make sense: why would someone call read_numbers if they didn't want to get any input?
We read up on error handling in C, and discover that assert() seems a good candidate to make sure that the function was not called with incorrect parameters, due to a programming bug. Note that assert() must not be used to detect invalid program input!!. It is only meant to aid in finding program bugs, i.e. the mistakes of the developer of the program, not mistakes of the user. If user input had to be checked, it has to be done explicitly using e.g. the conditional statement (if), or a custom function that checks the input - but never assert!
Note how assert is used:
It tells you, the human reader of the program, that at the given point in the program, count must be greater than zero. It helps reasoning about the subsequent code.
The compiler generates the code that checks the asserted condition, and aborts if it doesn't hold (is false). The checks usually are only performed in the debug build of the program, and are not performed in the release version.
To keep the program flow clear, we forward-declare read_numbers(), use it in main(), and define (implement) the function last, so that it doesn't obscure things:
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
void read_numbers(int *dst, int count);
int main() {
enum { N = 3 };
int numbers[N];
read_numbers(numbers, N);
char all_equal = 1;
int max = numbers[0];
for (int i = 1; i < N; i++) {
all_equal = all_equal && numbers[i] == max;
if (numbers[i] > max) max = numbers[i];
}
if (all_equal) printf("All numbers are equal.\n");
else printf("%d is the greatest among the numbers entered.\n", max);
}
void read_numbers(int *dst, int count) {
assert(count > 0);
printf("Enter %d numbers.\n", count);
for (int i = 0; i < count; /*empty*/) {
printf("#%d: ", i+1);
int c = scanf("%d", &dst[i]);
if (c == EOF) abort();
if (c != 1) {
printf("Sorry, invalid input. Try again.\n");
while ((c = getchar()) != EOF && c != '\n');
if (c == EOF) abort();
} else
i++;
}
}
You can try this program out in onlinegdb.com - just click this link!
In my opinion, main() looks very clear now. The input function stands on its own and can be analyzed in isolation: note how it's a pure function, and has no global state. Its output only acts on the arguments passed in. There are no global variables! There shouldn't ever be, really.
That's where I'd stop. We have a clear program that handles both valid and invalid input.
Moar Refactoring !!111!!
But you could say: how about we factor out data processing and final output as well? We can do that, sure. Yet, in a simple program like ours, it perhaps will slightly obscure what's going on. But at least let's see how it could look then, play with it and decide for ourselves :)
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char all_equal; // true if all numbers were equal
int max; // the greatest number
} Result;
void read_numbers(int *dst, int count);
Result find_greatest(int *numbers, int count);
void output_result(const Result *r);
int main() {
enum { N = 3 };
int numbers[N];
read_numbers(numbers, N);
const Result r = find_greatest(numbers, N);
output_result(&r);
}
void read_numbers(int *dst, int count) {
assert(count > 0);
printf("Enter %d numbers.\n", count);
for (int i = 0; i < count; /*empty*/) {
printf("#%d: ", i+1);
int c = scanf("%d", &dst[i]);
if (c == EOF) abort();
if (c != 1) {
printf("Sorry, invalid input. Try again.\n");
while ((c = getchar()) != EOF && c != '\n');
if (c == EOF) abort();
} else
i++;
}
}
Result find_greatest(int *numbers, int count) {
assert(count > 0);
Result r = {.all_equal = 1, .max = numbers[0]};
for (int i = 1; i < count; i++) {
r.all_equal = r.all_equal && numbers[i] == r.max;
if (numbers[i] > r.max) r.max = numbers[i];
}
return r;
}
void output_result(const Result *r) {
if (r->all_equal) printf("All numbers are equal.\n");
else printf("%d is the greatest among the numbers entered.\n", r->max);
}
Note how the Result local variable is initialized using struct initialization with designated initializers:
Result r = {.all_equal = 1, .max = numbers[0]};
If you needed to perform the initialization independently of the declaration of the variable, you would wish to use compound literals - a lesser known, but very important notational shortcut in modern C:
Result r;
// some intervening code
r = (Result){.all_equal = 1, .max = numbers[0]};
or perhaps:
void function(Result r);
void example(void) {
function((Result){.all_equal = 1, .max = numbers[0]});
}
Your code is fine; in fact, Bentley, McIlroy, Engineering a sort function, 1993, realised by, among others, BSD qsort, employs the same sort of mechanism in the inner loop for finding the median of three values. Except,
If all values are the same, it doesn't, "find the greatest among three numbers," but rather short-circuits and finds how many times the maximal value occurs, (three.) This is a separate problem.
It generally pays to separate one's logic from the output.
I've taken your code and put it in a function, stripped the output, and stripped of the equality.
#include <assert.h>
static int hi3(const int a, const int b, const int c) {
/* Same as `return a > b ? a > c ? a : c : b > c ? b : c;`. */
if(a > b) {
if(a > c) {
return a;
} else {
return c;
}
} else {
if(b > c) {
return b;
} else {
return c;
}
}
}
int main(void) {
/* Permutations of 3 distinct values. */
assert(hi3(1, 2, 3) == 3
&& hi3(1, 3, 2) == 3
&& hi3(2, 1, 3) == 3
&& hi3(2, 3, 1) == 3
&& hi3(3, 1, 2) == 3
&& hi3(3, 2, 1) == 3);
/* Permutation of 2 distinct values. */
assert(hi3(1, 2, 2) == 2
&& hi3(2, 1, 2) == 2
&& hi3(2, 2, 1) == 2);
assert(hi3(1, 1, 2) == 2
&& hi3(1, 2, 1) == 2
&& hi3(2, 1, 1) == 2);
/* All the same value. */
assert(hi3(1, 1, 1) == 1);
return 0;
}
Your code tests all the combinations of relative magnitudes successfully.

My C program to find closest pair of numbers from user input is not printing the right output?

I am trying to find the closest pair of numbers entered by the user. My C code isn't working right and I can't figure out what's wrong. I think it might have something to do with storing the values but I don't know where to go from here.
#include <stdio.h>
#include <math.h>
int main()
{
int i, j,arr[50], first,second;
//loop input
for(i=0;i<50;i++) //loop 50 times
{
scanf("%d", &i); //scan
//break if i=-1
if (i==-1)
break;
//if not print
}
//2nd num - 1st num < 3rd num-1st num, closest = 1st and 2nd num
//i[0]=num1, j[0+i]=2nd num, i= 4 , 5, 7, ans=arr,
//if j[0+i]-i[0]= ans < j[0+i]-i[i]=ans
//arr[i]=8,2,17,4,25
for(i=0;i<50;i++)
{
for(j=i+1;j<50;j++)
{
if(arr[j]-arr[i]<arr[j+1]-arr[i])
{
first = arr[i];//3
second = arr[j+1];//5
}
}
}
printf("%d %d\n", first, second);
return 0;
}
Don't post it as answer, prefer editing your code instead. Anyway, the problem is here :
for (j = i + 1; j < len; j++)//j<i <-why is it wrong?
How isn't it wrong? You've initialised j with the value i+1. How's it supposed to be ever less than i? And due to that, it's picking up values from outside the array and providing you with unexpected results.
The correct form is :
for (j = 0; j < i; j++)
The problem is with this chunk of code. You're scanning in the counter variable i instead of array. And then you're manipulating stuff using array arr. Why should that work in any scenario?
for(i=0;i<50;i++) //loop 50 times
{
scanf("%d", &i); //scan
//break if i=-1
if (i==-1)
break;
//if not print
}
And i can never be -1 unless it's a miracle.

C - scanf has gone ROGUE

I have this c program where I am inputing a number N followed by N more numbers. For example, I'll enter 100 followed by 100 more numbers. For some reason, after so many inputs the scanf function will stop working properly. It's as if it has stopped taking input and will just continue one with whatever value is in size.
The use case I came up with is 100 1 2 3 4 5 6 7 8 9 10... (repeated ten times). then after three or four times of that I'll type in 100 10 9 8 7 6 5 4 3 2 1... (repeated ten times) and then there will be an infinite loop of print statements.
int main(int argc, const char * argv[]) {
int histogram[10000];
int i;
while (1) {
int *rectPtr = histogram;
int size;
scanf("%d", &size);
if (!size) return 0;
for (i = 0; i < size; ++i) {
scanf("%d", rectPtr);
rectPtr++;
}
printf("%d", 1);
printf("\n");
}
return 0;
}
Distrust infinite loops.
In a series of comments, I said:
You're not testing the return value from scanf(), so you don't know whether it is working. The pair of printf() statements is odd; why not write printf("%d\n", 1); or even puts("1");?
Your code does not test or capture the return value from scanf(), so you do not know whether scanf() is reporting a problem. As a general rule, test the return value of input functions to make sure what you thought happened did in fact happen. You could also print out the values read just after you read them:
if (scanf("%d", rectPtr) != 1)
{
fprintf(stderr, "scanf() failed\n");
return 1;
}
printf("--> %d\n", *rectPtr);
rectPtr++;
Similarly when inputting size. Also consider if (size <= 0) return 0;. And using fgets() plus `sscanf() can make reporting errors easier.
j.will commented:
It is great to know if scanf fails, but I want to know why it fails and prevent it from failing. How do I do that?
I responded:
I understand you'd like to know. With scanf(), the best you can do after a failure is usually to read all the characters that follow up to a newline or EOF, and if you want to know what went wrong, then you print those characters too, because scanf() leaves the last character that it read in the input buffer ready for the next input operation.
void gobble(void)
{
printf("Error at: <<");
int c;
while ((c = getchar()) != EOF && c != '\n')
putchar(c);
puts(">>");
if (c == EOF)
puts("<<EOF>>");
}
The first character in the output is what caused the failure.
See also How to use sscanf() in loops?
Hacking your code to match this:
#include <stdio.h>
static void gobble(void)
{
printf("Error at: <<");
int c;
while ((c = getchar()) != EOF && c != '\n')
putchar(c);
puts(">>");
if (c == EOF)
puts("<<EOF>>");
}
int main(void)
{
enum { MAX_VALUES = 10000 };
int histogram[MAX_VALUES];
int size;
while (printf("Number of items: ") > 0 && scanf("%d", &size) == 1 &&
size > 0 && size <= MAX_VALUES)
{
int *rectPtr = histogram;
for (int i = 0; i < size; ++i)
{
if (scanf("%d", rectPtr) != 1)
{
gobble();
return 1;
}
rectPtr++;
}
printf("size %d items read\n", size);
}
return 0;
}
IMO, you need to check the return value of scanf() for proper operation. Please check the below code. I have added some modifications.
To exit from the program, you need to press CTRL+ D which will generate the EOF. Alternatively, upon entering some invalid input [like a char instead of int] wiil also cause the program to beak out of while() llop and terminate.
I have put the sequence to check first scanf(). All others need to be checked, too.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, const char * argv[]) {
int histogram[10000] = {0};
int i;
int *rectPtr = histogram;
int size = 0;
int retval = 0;
printf("Enter the number of elements \n");
while ( (retval = scanf("%d", &size)) != EOF && (retval == 1)) {
rectPtr = histogram;
if (!size) return 0;
printf("Enter %d elements\n", size);
for (i = 0; i < size; ++i) {
scanf("%d", rectPtr); //check in a simmilar way to above
rectPtr++;
}
printf("%d\n", 1111111);
printf("Enter the number of elements: \n");
}
return 0;
}
The output of a sample run
[sourav#broadsword temp]$ ./a.out
Enter the number of elements: 2
Enter 2 elements
1
2
1111111
Enter the number of elements: 3
Enter 3 elements
1
2
3
1111111
Enter the number of elements: 9
Enter 9 elements
0
9
8
7
6
5
4
3
2
1111111
Enter the number of elements: r
[sourav#broadsword temp]$
histogram is declared to have size 10000. You say you do 100 1 2 3 ... repeated 10 times. If I correctly understand that uses 1000 slots in histogram.
If you repeat the test more than 10 times, you exhaust histogram and begin to write past the end of array causing undefined behaviour.
So you must either :
reset recPtr = histogram at each iteration
control recPtr - histogram + size <= sizeof(histogram) after reading size (IMHO better)
And as other said, you should always control input operations : anything can happen outside of your program ...

WA in IITKWPCO SPOJ

This is a question from SPOJ
Little Feluda likes to play very much. As you know he only plays with numbers. So he is given n numbers. Now tries to group the numbers into disjoint collections each containing two numbers. He can form the collection containing two numbers iff small number in the collection is exactly half of large number.
Given n numbers, Find out how many maximum number of collections he can form ?
Input
T: number of test cases. (1 <= T <= 100).
For each test case:
First line will contain n : (1 <= n <= 100)
Then next line will contain n numbers single space seperated. Range of each number will be between 1 and 10^6.
Output
For each test case, output maximum number of collections that can be formed.
Example
Input:
2
2
1 2
3
1 2 4
Output:
1
1
my code::
#include <stdio.h>
#include <math.h>
#include <string.h>
int main()
{
int t;
scanf("%d", &t);
while (t--) {
int n, i, j;
scanf("%d", &n);
long int arr[n], mini, maxi;
char str[105];
for (i = 0;i < n;i++) {
str[i] = '0';
scanf("%ld", &arr[i]);
}
for (i = 0;i < n;i++) {
for (j = 0;j < n;j++) {
mini = fmin(arr[i], arr[j]);
maxi = fmax(arr[i], arr[j]);
if ((maxi == 2 * mini) && (str[i] == '0' && str[j] == '0')) {
str[i] = str[j] = '1';
break;
}
}
}
long int cnt = 0;
for (i = 0;i < n;i++) {
if (str[i] == '1') {
cnt++;
}
}
printf("%ld\n", cnt / 2);
}
return 0;
}
can someone plz point out where i am going wrong or any corner test case that i am missing??
There is a flaw in your logic.
Consider the case where the input array is {2,4,1,8}
The answer for this should be 2, since the collections {1,2} and {4,8} can be formed. However, your code will output 1 for this case (it will pair 2 with 4, and be able to create only one collection).
I have solved this problem by sorting the array, then for each element, check whether two times that element exists or not. If yes, mark it as used and increment the count of collections.
(pseudo-code):
sort(array)
count = 0;
for(i=0;i<size;i++){
if(used[i]) continue; //used elements should not be re-considered
for(j=i+1;j<size;j++){
if(array[j]==2*array[i] && !used[j]){
used[j] = true;.
count++;
}
}
}
The variable count will now have the maximum possible number of collections.
Note that searching for 2*array[i] in the array can also be implemented by binary search, but that would be unnecessary since the array is really small (size <=100)
Here's my C++ code for the problem. ( I have used the c++ standard library for sorting, you may use any sorting algorithm of your choice ).
Hope this helps.
Cheers.
Check out this easy solution:
#include<iostream>
#include<algorithm>
#include<stdio.h>
using namespace std;
int main()
{
int t=0;
scanf("%d",&t);
while(t>0)
{
t=t-1;
int num=0;
long long int n[10001];
int count=0;
scanf("%d",&num);
for(int k=0;k<num;k++)
scanf("%lld",&n[k]);
sort(n,n+num);
for(int i=0;i<num;i++)
{
if(n[i]==-1)continue;
for(int j=i+1;j<num;j++)
{
if(n[j]==n[i]*2 &&n[i]!=-1 &&n[j]!=-1 )
{
count=count+1;
n[i]=-1;
n[j]=-1;
break;
}
}
}
printf("%d\n",count);
}
// getchar();
return 0;
}

linear searches in 2d arrays

#define NUMLEG 7
int Search_type(char leg_type[6][10], int travel_int[6][15], int trip_num);
c = Search_type(type,leg_type, travel_int, trip_num);
if (c == -1)
printf("Destination not found.\n");
else
printf("Destination Found \nDestination Name:%s", travel_name[c]);
int Search_type( char type, char leg_type[6][10], int travel_int[6][15], int trip_num)
{
int i, n;
char target;
getchar();
printf("Please enter travel type you wish to search by:");
scanf("%c", &target);
for (i =0; i <trip_num; i++)
{
for ( n = 0; n < travel_int[i][NUMLEG]; n++)
{
if( leg_type[i][n] == target)
{
return i;
}
}
return -1;
}
}
This is a rip out of a function I'm currently working on from a project and for some strange reason I can't seem to get it to search properly, I know that its not the rest of the code but this area since all the other function works properly. So I decided to break this out of the code and test it.
I can't seem to get it to search after 1 row:
travel_int[i][NUMLEG] contains the number of legs
leg_type is where i store the char of each leg
I want it to search through the leg_type till it finds the specified character. Without pointers.
EDIT
For example
Trip#:1
Destination Name:Austin
Leg(#1):A
Leg(#2):T
Trip#:2
Destination Name:Florida
Leg(#1):S
Leg(#2):F
so
trip number = 2
travel_int stores 2 trips and each trip has 2 legs
leg type stores in the 2 leg types at the trip number
When I put in A or T it prints out Austin like it should but when I input S or F it return destination not found =/. Am I doing the search wrong, or is it the print statement that is wrong. Or is it where I'm place my return -1;.
(I would put up the code but its a bit long..)
In your nested loops you are returning -1 without doing complete search in the entire arrays.
Place return -1 outside all the for() loops.
for (i =0; i <trip_num; i++)
{
for ( n = 0; n < travel_int[i][NUMLEG]; n++)
{
if( leg_type[i][n] == target)
{
return i;
break;
}
}
} return -1
This would definitely make your program run correctly.And this is the only reason why you get the correct results when you search for trip #01.

Resources