I need to write a program which prints the conversion table from feet and inches to centimetres. The numbers printed in row i (counting from zero), column j (counting from zero) of the table should be the cm equivalent of i feet and j inches. i should go from 0 to 7, and j from 0 to 11. Each column should be five characters wide, and the cm figures should be rounded to the nearest integer.
The example of required output is given below:
0 3 5 8 10 13
30 33 36 38 41
61 64 66 69 71
91 94 97 99 102
The code I have prints only one row of inches and column of feet but I don't know how to make into table without producing lots of irrelevant repetitions.
The code is:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int i,j;
int cm,p;
for (i=0; i<= 11; i++) {
cm =round(i * 2.54);
printf ("%5d",cm);
}
for (j=0; j<=7; j++) {
p =round(j* 12.0 * 2.54);
printf ("%5d\n",p);
}
return 0;
}
This produces:
0 3 5 8 10 13 15 18 20 23 25 28 0
30
61
91
122
152
183
213
What am I doing wrong?
You have one loop after the other. What you need to do is run through the inches loop every iteration of your feet loop. What you get is nested loops:
#include <stdio.h>
int main()
{
for (int feet = 0; feet <= 7; ++feet) {
for (int inches = 0; inches < 12; ++inches) {
int microns = (feet * 12 + inches) * 25400;
int rounded_cm = (microns + 5000) / 10000;
printf("%5d", rounded_cm);
}
puts("");
}
}
I've made some other changes in my version; you're encouraged to study it and understand why it does what it does (read the man page for puts(), for example). Don't just copy it and hand it in - it will be obvious it isn't your code.
An alternative approach is to use a single loop (in inches), and insert a newline when we reach the 11th inch in each foot:
#include <stdio.h>
int main()
{
for (int i = 0; i < 96; ++i) {
printf("%4d%s",
(i * 25400 + 5000) / 10000,
i%12==11 ? "\n" : " ");
}
}
(You'll want to give meaningful names to your constants; the above is written in a "code-golf" style).
Whatever you do, don't be tempted to avoid multiplying by instead adding 2.54 repeatedly in the loop. Floating-point numbers are not exact, and addition will accumulate the error.
OP needs to put the "inches" loop inside the "foot" loop as well answered by others. #Toby Speight #VHS
Code could do its "round to nearest" via the printf() statement by using "%5.0f" to control the output width and rounding.
Let code use foot/inch instead of i/j #KevinDTimm for clarity.
#include <stdio.h>
#define INCH_PER_FOOT 12
#define CM_PER_INCH 2.54
int main(void) {
// go from 0 to 7, and ...
for (int foot = 0; foot <= 7; foot++) {
// from 0 to 11
// for (int inch = 0; inch < INCH_PER_FOOT; inch++) { is more idiomatic
for (int inch = 0; inch <= 11; inch++) {
printf("%5.0f", (foot * INCH_PER_FOOT + inch) * CM_PER_INCH);
}
puts("");
}
}
Output
0 3 5 8 10 13 15 18 20 23 25 28
...
213 216 218 221 224 226 229 231 234 236 239 241
You are running your loops backwards. First you need to run through feet and then through inches. But you are having it the other way round. Check the following snipped and compare it with your code and try to understand what's wrong.
#include <stdio.h>
#include <stdlib.h>
#include <math.h> // for rounding of a number
int main()
{
int i,j;
int cm,p;
for(i=0; i<=7;i++) {
for(j=0;j<=11;j++) {
cm = round(i*30.48 + j*2.54);
printf ("%5d",cm);
}
printf("\n");
}
return 0;
}
Related
I am trying to create a program outputting the pascal's triangle, using C in OnlineGDB and repl.it using a 2x2 array asking how many lines the user wants to print. The main problem is that the program works, but only until printing for 7 rows in onlinegdb, and only 3 rows in repl.it.
There is no error in OnlineGDB, and repl.it says "signal: segmentation fault (core dumped)"
Additionally, I added 3 "PASS" print lines to see where the error occurs, and when reaching the 8th line in onlineGDB it passes all 3 of the for statements filling the array. When reaching the 4th line in repl.it passes all 3 of the for statements filling the array, but both of them doesn't print out the correct numbers. Again, inputted numbers below these values show that all of the code works.
Is there a fix for this, or is it an error with websites handling arrays?
#include <stdio.h>
int main(void){
int intCount;
int intCount1;
int intRows;
int intColumns;
printf("HOW MANY ROWS DO YOU WANT?? ");
scanf("%i", &intRows);
intColumns = intRows;
int intNum[intRows][intColumns];
printf("PASS ");
// FIRST FILL ARRAY WITH 0
for(intCount = 0; intCount <= intRows+1; ++intCount){
for(intCount1 = 0; intCount1 <= intColumns+1; ++intCount1){
intNum[intCount][intCount1] = 0;
}
}
printf("PASS ");
// SET STARTING POINT (1)
intNum[0][0] = 1;
// NOW FILL ARRAY WITH PASCAL TRIANGLE
for(intCount = 0; intCount <= intRows; ++intCount){
for(intCount1 = 0; intCount1 <= intColumns; ++intCount1){
intNum[intCount+1][intCount1+1] = ((intNum[intCount][intCount1+1])+ (intNum[intCount][intCount1]));
}
}
printf("PASS\n");
// NOW PRINT ARRAY
for(intCount = 0; intCount <= intRows; ++intCount){
for(intCount1 = 0; intCount1 <= intColumns; ++intCount1){
// WITHOUT ZEROES:
/*if(intNum[intCount][intCount1] != 0){
printf("%5i",intNum[intCount][intCount1]);
}*/
// WITH ZEROES:
printf("%4i",intNum[intCount][intCount1]);
}
printf("\n");
}
return 0;
}
Logic: In the code above I created a 2 x 2 array with height and width dimensions one larger than the user asks for. I then fill the array with zeroes, and start with a 1 in the top left corner. From there I can use the pascals triangle formula by adding the two numbers above it
I tried changing the counting variables of arrays to make sure everything was correct, but it did not help. I originally coded on onlineGDB but used repl.it to see if there was any further errors, to which there was none. Additionally checked other questions on stack.
Desired Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
OnlineGDB Output: (limited to 7 rows in the input)
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
repl.it Output: (limited to 3 rows in the input)
1
1 1
1 2 1
Note: In the output, my code also prints the 0s at the moment and the whole array so that I can visualize it. I am also 100% sure it's the same code uploaded to both
This could be something simple, but I appreciate all the help I can get. I'm more curious why the outputs are different on separate websites with the same code.
Why are you using loops like
for (intCount = 0; intCount <= intRows+1; ++intCount)
{
for (intCount1 = 0; intCount1 <= intColumns+1; ++intCount1)
{
intNum[intCount][intCount1] = 0;
}
}
when you allocated intNum[intRows][intColumns]? You are trampling way out of bounds. That's why your code crashes. That's why you get different behaviours in different systems.
Use:
for (int i = 0; i < intRows; i++)
{
for (int j = 0; j < int columns; j++)
intNum[i][j] = 0;
}
or an equivalent. Note that you use < and not <=; you use the declared limit, not that limit plus one.
Here is some working code, printing without the zeros. Your algorithm for generating the values in Pascal's Triangle was flawed on at least two counts. As before, it trampled way out of bounds of the array, and it also produced two rows with a single 1 in the output (when zeros were not printed). This code avoids those flaws. It also uses i and j as the loop counters — old Fortran programmers die hard.
/* SO 7549-7765 */
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int intRows;
int intColumns;
printf("How many rows do you want? ");
if (scanf("%i", &intRows) != 1)
{
fprintf(stderr, "failed to read an integer\n");
exit(1);
}
if (intRows < 1 || intRows > 64)
{
fprintf(stderr, "value %d is outside the range 1..64\n", intRows);
exit(1);
}
printf("Rows: %d\n", intRows);
intColumns = intRows;
int intNum[intRows][intColumns];
printf("PASS\n");
// First, fill array with zeros
for (int i = 0; i < intRows; i++)
{
for (int j = 0; j < intColumns; j++)
{
intNum[i][j] = 0;
}
}
printf("PASS\n");
// Set starting point (1)
intNum[0][0] = 1;
// Now fill array with Pascal's Triangle
for (int i = 1; i < intRows; i++)
{
intNum[i][0] = intNum[i-1][0];
for (int j = 1; j <= i; j++)
{
intNum[i][j] = intNum[i-1][j-1] + intNum[i-1][j];
}
}
printf("PASS\n");
// Now print array
for (int i = 0; i < intRows; i++)
{
for (int j = 0; j < intColumns; j++)
{
// Without zeros:
if (intNum[i][j] != 0)
printf(" %5d", intNum[i][j]);
// With zeros:
// printf(" %5d", intNum[i][j]);
}
printf("\n");
}
return 0;
}
Note the use of " %5d" in the printing format. That space ensures that the numbers remain separate even if there are 6 or more digits in the values (which first happens with 21 rows requested).
Sample output:
How many rows do you want? 15
Rows: 15
PASS
PASS
PASS
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
1 11 55 165 330 462 462 330 165 55 11 1
1 12 66 220 495 792 924 792 495 220 66 12 1
1 13 78 286 715 1287 1716 1716 1287 715 286 78 13 1
1 14 91 364 1001 2002 3003 3432 3003 2002 1001 364 91 14 1
I am trying to delete first 20 columns from each of the slices of my 3D dynamic array. I guessed trying to write a function for 2D dynamic array would solve the problem which I would iterate over each of the levels of 3D array. I got an example in stackoverflow which I am trying to make work.
But the problem is the function can not delete the whole column. Instead it only delete one element. Can anyone give me idea how to delete whole column from a 2D dynamic array?
void removeColumn(int** matrix, int col){
MATRIX_WIDTH--;
for(int i=0;i<MATRIX_HEIGHT; i++) {
while(col<MATRIX_WIDTH)
{
//move data to the left
matrix[i][col]=matrix[i][col+1];
col++;
} matrix[i] = realloc(matrix[i], sizeof(double)*MATRIX_WIDHT); }
My expected ouput is like
Sample input:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
sample output:
1 3 4
5 7 8
9 11 12
13 15 16
Update: here is the code which delete the column completely after using #frslm advice
but matrix is not resizing.
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
int** fill(size_t rows, size_t cols, int input[][cols])
{
int i,j,count=1;
int** result;
result = malloc((rows)*sizeof(int*));
for(i=0;i<rows;i++)
{
result[i]=malloc(cols*sizeof(int));
for(j=0;j<cols;j++)
{
result[i][j]=count++;
}
}
return result;
}
void printArray2D(size_t rows, size_t cols,int** input)
{
int i,j;
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{
printf(" %4d",input[i][j]);
}
printf("\n");
}
}
void removeColumn(int** matrix, int col2del , int rows, int cols){
int MATRIX_WIDTH = cols;
int MATRIX_HEIGHT = rows;
MATRIX_WIDTH--;
for(int i=0;i<MATRIX_HEIGHT; i++) {
int curr_col = col2del;
while(curr_col<MATRIX_WIDTH)
{
//move data to the left
matrix[i][curr_col]=matrix[i][curr_col+1];
curr_col++;
}
//matrix[i] = realloc(matrix[i], sizeof(int)*MATRIX_WIDTH); // <- int, not double
matrix[i] = realloc(matrix[i], sizeof (matrix[i][0])*MATRIX_WIDTH);
}
}
int main()
{
int arRow,arCol;
arRow =8;
arCol = 9;
int ar[arRow][arCol];
int **filled;
filled = fill(arRow, arCol, ar);
printArray2D(arRow,arCol,filled);
removeColumn(filled, 3,arRow,arCol);
printf("After 3rd Column Delete.......\n");
printArray2D(arRow,arCol,filled);
return(0);
}
Output: last column duplicates
1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18
19 20 21 22 23 24 25 26 27
28 29 30 31 32 33 34 35 36
37 38 39 40 41 42 43 44 45
46 47 48 49 50 51 52 53 54
55 56 57 58 59 60 61 62 63
64 65 66 67 68 69 70 71 72
After 3rd Column Delete.......
1 2 3 5 6 7 8 9 9
10 11 12 14 15 16 17 18 18
19 20 21 23 24 25 26 27 27
28 29 30 32 33 34 35 36 36
37 38 39 41 42 43 44 45 45
46 47 48 50 51 52 53 54 54
55 56 57 59 60 61 62 63 63
64 65 66 68 69 70 71 72 72
You increment col until it reaches the end of the first row, but you never reset it for subsequent rows, which is why you end up removing only the first row's column.
Make sure you reset col at the start of each iteration:
void removeColumn(int** matrix, int col){
MATRIX_WIDTH--;
for(int i=0;i<MATRIX_HEIGHT; i++) {
int curr_col = col; // <- use a temporary `col` variable for each row
while(curr_col<MATRIX_WIDTH)
{
//move data to the left
matrix[i][curr_col]=matrix[i][curr_col+1];
curr_col++;
}
matrix[i] = realloc(matrix[i], sizeof(int)*MATRIX_WIDTH); // <- int, not double
}
}
Edit (in response to OP's edit):
Ensure that removeColumn() updates the number of columns (cols) after resizing the matrix; one way to do that is by using a pointer: int *cols as a parameter instead of int cols (don't forget to pass in an address, &arCol, when calling this function). Also, I suggest getting rid of the unnecessary MATRIX_HEIGHT variable:
void removeColumn(int** matrix, int col2del, int rows, int *cols){
int MATRIX_WIDTH = --(*cols);
for(int i=0;i<rows; i++) {
int curr_col = col2del;
while(curr_col<MATRIX_WIDTH)
{
//move data to the left
matrix[i][curr_col]=matrix[i][curr_col+1];
curr_col++;
}
matrix[i] = realloc(matrix[i], sizeof(matrix[i][0])*MATRIX_WIDTH);
}
}
It's easier if you pass the width and height, and update the width:
void removeColumn(int** matrix, int col, int* width, int height)
{
int j, i;
for (j = 0; j < height; ++j) {
if (col == *width-1) {
continue;
}
for (i = col; i < *width; ++i) {
matrix[j][i] = matrix[j][i+1];
}
// this is not necessary, but I'm adding as requested
matrix[j] = realloc(
matrix[j],
sizeof(int) * (*width - 1)
);
}
--(*width);
}
You could also avoid dynamic memory allocations, avoiding memory defragmentation:
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int max_width, max_height;
int width, height;
int* values;
} matrix;
void removeColumn(matrix* matrix, int col)
{
int y, i;
for (y = 0; y < matrix->height; ++y) {
if (col == matrix->width-1) {
continue;
}
i = col + matrix->height * y;
while (i < matrix->width) {
matrix->values[i] = matrix->values[++i];
}
}
--matrix->width;
}
void printMatrix(matrix* matrix)
{
int y, x;
for (y = 0; y < matrix->height; ++y) {
for (x = 0; x < matrix->width; ++x) {
printf("%d ", matrix->values[x + matrix->width * y]);
}
printf("\n");
}
}
int main ()
{
int y, x = 0;
matrix matrix;
matrix.max_width = 4;
matrix.max_height = 4;
matrix.width = 4;
matrix.height = 4;
int values[4][4];
matrix.values = &values;
for (y = 0; y < matrix.height; ++y) {
for (x = 0; x < matrix.width; ++x) {
int i = x + matrix.width * y;
matrix.values[i] = i % 10;
}
}
printMatrix(&matrix);
removeColumn(&matrix, 1);
printf("===\n");
printMatrix(&matrix);
}
Tested using: https://www.tutorialspoint.com/compile_c_online.php
ADDED
But when the array size is too big then do we have any other option
but using dynamic array
If you want to make a resizable array, you could use a single malloc when allocating the array and use a realloc when the width will be greater than max_width or the height will be greater than max_height.
Nevertheless, I believe we should try to avoid lots of dynamic allocations using malloc or realloc, because they're slow (though most of the time you won't notice), they can severely defragment memory and the way you did it generates lots of unnecessary cache misses.
You should also grow them more than required, for instance, exponentially, if you don't know that you will need to resize the array several times. That's how hashes and dynamic arrays are usually implemented (properly).
You may find, for instance, several JSON, XML and HTML C libraries without dynamic memory to avoid its pitfalls, and in many professional video games, a huge malloc might be used to avoid lots of them and simple arrays are used liberally.
Why is realloc eating tons of memory?
https://blog.mozilla.org/nnethercote/2014/11/04/please-grow-your-buffers-exponentially/
http://gameprogrammingpatterns.com/data-locality.html
https://codefreakr.com/how-is-c-stl-implemented-internally/
http://gamesfromwithin.com/start-pre-allocating-and-stop-worrying
CppCon 2014: Mike Acton "Data-Oriented Design and C++"
Of course, you can use dynamic memory, but it's better to understand its pitfalls for better decisions.
I'm trying to submit the solution for Spoj - Prime Intervals problem. But I'm getting a runtime error SIGXFSZ. It is given that, it occurs due to exceeded file size. I have used the Sieve of Eratosthenes algorithm to find the prime numbers. I don't understand what's wrong with my code and this is bugging me from last the 2 days. Please help me with the submission. Here is my code...
#include<stdio.h>
#include<string.h>
#include<stdbool.h>
#include<math.h>
int main(){
int t, turn;
long i, l,u,k,j;
scanf("%d", &t);
/*Looping for t test cases*/
for(turn=0; turn<t; turn++){
scanf("%ld %ld", &l, &u);
bool arr[u-l+1];
/*Assigning whole array with true*/
memset(arr, true, u-l+1);
/*Sieve of Eratosthenes logic for assigning false to composite values*/
for(i=0; i<=(int)sqrt(u)-l; i++){
k=0;
j = i+l;
if(arr[i]==true){
while((j*j + k*j) <= u){
arr[(j*j + k*j) - l] = false;
k++;
}
}
}
/*Printing all the primes in the interval*/
for(i=0; i<u-l; i++){
if(arr[i]==true){
printf("%ld\n", i+l);
}
}
}
return 0;
}
Test Input:
2
2 10
2 100
Output:
2
3
5
7
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
I ran the posted code. the results were far from correct.
Most of the numbers output are not primes and fails to check the last number is the range, as shown in the second set of results
Here are the results:
1 <-- 1 test case
20 100 <-- range 20...100
20 <-- the outputs
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
Note: using 1 as the low end of the range usually results with no output produced
here is another run
The output should have been 5 7 11
1 <-- test cases
5 11 <-- range
5 <-- outputs
6
7
8
9
10
The following code does not try to minimize the size of the arr[] array, and if the upper end of the range is less than 16k then could declare the arr[] as short rather than unsigned int
The lowest valid value for the low end of the input is 2, but the code is not checking for that low limit, you might want to add that check.
The code makes no effort to minimize the number of loops executed by checking for the square root of the upper limit, you might want to add that check.
The code compiles cleanly, handles the case when the upper limit is a prime and when the lower limit is a prime as well as when the limit values are not primes.
#include <stdio.h>
#include <string.h>
#include <math.h>
int main()
{
int numTestCases, testCase;
size_t i; // index
size_t lowLimit;
size_t upperLimit;
size_t k; // offset multiplier
scanf("%d", &numTestCases);
/*Looping for t test cases*/
for(testCase=0; testCase<numTestCases; testCase++)
{
scanf("%lu %lu", (unsigned long*)&lowLimit, (unsigned long*)&upperLimit);
unsigned arr[upperLimit+1];
/*Assigning whole array to indicate entry is a prime*/
memset(arr, 0x01, upperLimit+1);
/*Sieve of Eratosthenes logic for assigning false to composite values*/
//size_t sqrtUpperLimit = (size_t)ceil(sqrt(upperLimit));
for(i=2; i<= upperLimit; i++)
{
if(arr[i])
{
if( i >= lowLimit )
{
printf("%ld\n", i);
}
for( k=2; (i*k) <= upperLimit; k++)
{
arr[(i*k)] = 0;
}
}
}
}
return 0;
} // end function; main
here is an edited version of the code, with the addition of some instrumentation in the way of prompts to the user via calls to printf()
#include <stdio.h>
#include <string.h>
#include <math.h>
int main()
{
int numTestCases, testCase;
size_t i; // index
size_t lowLimit;
size_t upperLimit;
size_t k; // offset multiplier
printf("enter number of test cases\n");
scanf("%d", &numTestCases);
/*Looping for t test cases*/
for(testCase=0; testCase<numTestCases; testCase++)
{
printf( "enter lower limit upper limit limits\n");
scanf("%lu %lu", (unsigned long*)&lowLimit, (unsigned long*)&upperLimit);
unsigned arr[upperLimit+1];
/*Assigning whole array to indicate entry is a prime*/
memset(arr, 0x01, upperLimit+1);
/*Sieve of Eratosthenes logic for assigning false to composite values*/
//size_t sqrtUpperLimit = (size_t)ceil(sqrt(upperLimit));
for(i=2; i<= upperLimit; i++)
{
if(arr[i])
{
if( i >= lowLimit )
{
printf("%ld\n", i);
}
for( k=2; (i*k) <= upperLimit; k++)
{
arr[(i*k)] = 0;
}
}
}
}
return 0;
} // end function; main
Using the above instrumented code and the input of:
5 2 3 30 31 20 27 2 3 4 5
it worked perfectly.
This was the output:
enter number of test cases
5
enter upper/lower limits
2 3
sizeof arr[]: 4
2
3
enter upper/lower limits
30 31
sizeof arr[]: 32
31
enter upper/lower limits
20 27
sizeof arr[]: 28
23
enter upper/lower limits
2 3
sizeof arr[]: 4
2
3
enter upper/lower limits
4 5
sizeof arr[]: 6
5
I have a program that outputs a huge array of integers to stdout, each integer in a line. Ex:
103
104
105
107
I need to write another program that reads in that array and fill up the spaces where the number isn't an increment of 1 of the previous number. The only different between numbers is going to be 2 (105,107), which makes it easier.
This is my code to do that logic:
printf("d",num1);
if ((num2-num1) != 1)
numbetween = num1 + 1;
printf("%d", numbetween);
printf("%d", num2);
else(
printf("%d",num2);
)
So the output of this program will now be:
103
104
105
106
107
My issue is reading the numbers. I know I can do while (scanf("%hd", &num) != EOF) to read all the lines one at a time. But to do the logic that I want, I'm going to need to read two lines at a time and do computation with them, and I don't know how.
You could always just read the first and last numbers from the file, and then print everything in between.
int main( void )
{
// get the first value in the file
int start;
if ( scanf( "%d", &start ) != 1 )
exit( 1 );
// get the last value in the file
int end = start;
while ( scanf( "%d", &end ) == 1 )
;
// print the list of numbers
for ( int i = start; i <= end; i++ )
printf( "%d\n", i );
}
Read first num then add missing if needed when you read next int
#include <stdio.h>
#include <stdlib.h>
int main()
{
int previous = 0;
int num;
scanf("%hd", &previous);
while (scanf("%hd", &num) != EOF) {
for (int i = previous; i < num; i++) {
printf("%d\n" , i);
}
previous = num;
}
printf("%d\n" , previous);
return 0;
}
this input
100
102
103
105
107
110
returns this output
100
101
102
103
104
105
106
107
108
109
110
While you can read the first and last, to fill the range, what you are really doing is finding the min and max and printing all values between them inclusively. Below the names are left first and last, but they represent min and max and will cover your range regardless whether the values are entered in order. Taking that into consideration, another approach insuring you cover the limits of the range of int would be:
#include <stdio.h>
int main (void) {
int num = 0;
int first = (1U << 31) - 1; /* INT_MAX */
int last = (-first - 1); /* INT_MIN */
/* read all values saving only first (min) and last (max) */
while (scanf (" %d", &num) != EOF) {
first = num < first ? num : first;
last = num > last ? num : last;
}
/* print all values first -> last */
for (num = first; num <= last; num++)
printf ("%d\n", num);
return 0;
}
Input
$ cat dat/firstlast.txt
21
25
29
33
37
41
45
49
53
57
61
65
69
73
77
81
85
89
93
97
101
Output
$ ./bin/firstlast < dat/firstlast.txt
21
22
23
24
25
26
27
28
29
<snip>
94
95
96
97
98
99
100
101
Note: you can change the types to conform to your expected range of data.
The problem is about saving James Bond. My code gets the right answer only in some special occasions. I spent so much time but I didn't find any mistake in my algorithm. I need your help. Thanks.
Here is the request of the problem.
.......................................
This time let us consider the situation in the movie "Live and Let Die" in which James Bond, the world's most famous spy, was captured by a group of drug dealers. He was sent to a small piece of land at the center of a lake filled with crocodiles. There he performed the most daring action to escape -- he jumped onto the head of the nearest crocodile! Before the animal realized what was happening, James jumped again onto the next big head... Finally he reached the bank before the last crocodile could bite him (actually the stunt man was caught by the big mouth and barely escaped with his extra thick boot).
Assume that the lake is a 100 by 100 square one. Assume that the center of the lake is at (0,0) and the northeast corner at (50,50). The central island is a disk centered at (0,0) with the diameter of 15. A number of crocodiles are in the lake at various positions. Given the coordinates of each crocodile and the distance that James could jump, you must tell him whether or not he can escape.
Input Specification:
Each input file contains one test case. Each case starts with a line containing two positive integers N (<=100), the number of crocodiles, and D, the maximum distance that James could jump. Then N lines follow, each containing the (x, y) location of a crocodile. Note that no two crocodiles are staying at the same position.
Output Specification:
For each test case, print in a line "Yes" if James can escape, or "No" if not.
Sample Input 1:
14 20
25 -15
-25 28
8 49
29 15
-35 -2
5 28
27 -29
-8 -28
-20 -35
-25 -20
-13 29
-30 15
-35 40
12 12
Sample Output 1:
Yes
Sample Input 2:
4 13
-12 12
12 12
-12 -12
12 -12
Sample Output 2:
No
.......................................
Here is my code.
#include <stdio.h>
#include <malloc.h>
#include <math.h>
typedef struct Node{
int x;
int y;
} Position;
int result;
Position beast[1000];
int visited[1000];
int NumOfB, JumpAb;
void dfs(int i){
int j;
if (Available(i)){
visited[i]=1;
if (Save(i)) {
result = 1;
printf("Yes");
}
}
for(j = 0;j<NumOfB;j++)
if(!visited[j])
dfs(j);
}
int Available(int i){
int j;
double d_x,d_y;
for (j=0;j<NumOfB;j++){
d_x = beast[i].x - beast[j].x;
d_y = beast[i].y - beast[j].y;
if (((d_x*d_x+d_y*d_y)<JumpAb*JumpAb)&& visited[j]==1){
return 1;
}
}
return 0;
}
int Save(int i){
if ((abs(50-abs(beast[i].x))<=JumpAb)||((abs(50-abs(beast[i].y)))<=JumpAb))
return 1;
else
return 0;
}
int FirstJump(int i){
if (((beast[i].x*beast[i].x)+(beast[i].y*beast[i].y))<=JumpAb*JumpAb){
return 1;
} else {
return 0;
}
}
int main(){
result = 0;
scanf("%d %d",&NumOfB,&JumpAb);
int i;
Position* p =NULL;
for (i=0;i<NumOfB;i++){
p = (Position*)malloc(sizeof(Position));
scanf("%d %d",&p->x,&p->y);
}
for (i=0;i<NumOfB;i++){
visited[i] = 0;
}
for(i = 0;i<NumOfB;i++){
if(!visited[i] && FirstJump(i)){
visited[i] = 1;
dfs(i);
}
}
if (result==0){
printf("No");
}
return 0;
}