The level is basic so bear with me. There are a few similar topics but didn't find my luck there. What I'm trying to do is to find max element in a row and then put it in the place of last element of the same row, while the last element to be put in the place of the max one the program found.
So I've got this code in C, it's supposed to print the original array, do the magic and then print the modified array. It does find the max element in 1st row, puts it in the last place of the same row, but doesn't do the switch - the last element doesn't hop in the place of max element's. I know I did something dumb and plain simple, but I just can't find where the mistake is. Any help highly appreciated!
int main()
{
int a[3][4]={23,32,45,12,53,75,38,72,14,37,42,82}, i, j, t, l, max=a[1][0];
for(i=0;i<3;i++){
printf("\n");
for(j=0;j<4;j++){
printf("%d ", a[i][j]);
}
}
for(l=0;l<4;l++){
if(a[1][l]>max){max=a[1][l];}
}
t=a[1][3];
a[1][3]=max;
max=t;
for(i=0;i<3;i++){
printf("\n");
for(j=0;j<4;j++){
printf("%d ", a[i][j]);
}
}
return 0;
}
And here is what it returns (original array):
23 32 45 12
53 75 38 72
14 37 42 82
(modified array):
23 32 45 12
53 75 38 75
14 37 42 82
You also need to store the position of max:
int max_pos = 0; //same as the initial max - a[1][0]
for(l=0;l<4;l++){
if(a[1][l]>max){max=a[1][l]; max_pos=l;}
}
Then when you switch them:
t=a[1][3];
a[1][3]=max;
a[1][max_pos] = t;
I assume you are aware this only happens for the second row. If you want to do it for all rows, you'll have to store the positions in an array.
Related
I'm working an assignment and I'm relatively new to C. If I were to be given an input file like this:
25 08 10 15 10
10 13 50 60 70
10 10 15 00 90
00 05 07 80 12
10 05 60 70 88
How would I correctly store these in an array such that it's displayed like a 2D array or is that not possible in the way I'm thinking with C.
The code I have below is a function for converting the input file into a 2d array. Assuming that I have already other functions error checking if the file is in the correct format.
void createMatrix(FILE *fp) {
int row = 5;
int col = 5;
char matrix[row][col];
int i, j;
char num[25];
rewind(fp);
for (i=0; i<row; i++) {
for(j=0; j<col; j++) {
fscanf(fp, "%s", name);
bingoCard[i][j] = name;
}
}
}
This would work if it was integers I'm looking for but I need to preserve the 0's in front of numbers like
00
or 08. I also later need to append to these numbers which is why I need to get them in an array in a string format. Would anyone be able to point me in the right direction?
I would then need to print the input file when making updates to it like this
25X 08 10 15 10
10 13 50 60 70
10 10 15 00 90
00 05 07 80 12
10 05 60 70 88
Make each element in the matrix a string (an array). E.g.
char matrix[row][col][10];
Then read into that string directly:
fscanf(fp, "%9s", matrix[i][j]);
But you could also create your matrix as a matrix of integers and then use printf formatting to include leading zeros:
int matrix[row][col];
// ...
fscanf(fp, "%d", &matrix[i][j]);
// ...
printf("%02d", matrix[i][j]); // Prints leading zero if value is only a single digit
I am working on an assignment but the code is doing some weird stuff. It is my 7th day "programming", so it might be just an obvious mistake, which I simply cannot see.
I want the program to sum all values stored in a same variable. I tried to replicate some code from here: https://stackoverflow.com/a/42166389, but it did not work as expected.
So, given a set of values -let's say 012345-, the program should take every other number -4, 2, and 0-, and sum them -giving back "6"-. And, although it does identify the digits, it does not sum them... at least properly.
I do not understand why, but it gives back 48.
I have tried different inputs, and while identifying the digits properly, in all cases the sum was wrong.
I would really appreciate any help.
Oh, and here is my code!:
#include <cs50.h>
#include <stdio.h>
#include <string.h>
int main(void) {
char c;
string number;
int length, i, sum = 0;
printf("Type card number: ");
number = get_string();
printf("Tell us how many characters long was your number: ");
length = get_int();
for (i = 1; i <= length / 2; i++) {
c = number[(strlen(number) - i * 2)];
sum = c;
printf("%c %i %s\n", c, sum, number);
}
}
Some examples:
For input 012345 and length=6, the output is:
4 52 012345
2 50 012345
0 48 012345
For input 9876543210 and length=10, the output is:
1 49 9876543210
3 51 9876543210
5 53 9876543210
7 55 9876543210
9 57 9876543210
And, just to summarize, what I want is a way of summing all the values in a same variable.
sum = c;
You are assigning ASCII value to sum.You should get the corresponding number and also add it to sum, not just assign.
4 52 012345 //52 is ASCII value of 4
2 50 012345 //50 is ASCII value of 2
0 48 012345 //48 is ASCII value of 0
Try this,
sum+=c-'0';
#include<stdio.h>
int main() {
int i;
int vector[5]={6,17,28,39,410},*r; //variables declaration
r=(int*)&vector; //pointer declaration
for (i = 0; i<5;i++){ //print the array in using a loop
printf("%d ",vector[i]);
}
printf("\n\n");
for(i=0;i<5;i++){ //print the array in reverse order using a loop
vector[i] = *(r+4-i); //it should be from the last to the first but it prints it
printf("%d ",vector[i]); //differently, see below
}
return 0;}
It should be:
6 17 28 39 410
410 39 28 17 6
but it results in:
6 17 28 39 410
410 39 28 39 410
the last two should be 17 6
You are overwriting the data you're trying to read, before reading it.
Just write out the steps your code is taking manually, and you'll see it.
To do reversal in-place, you must swap values around, to avoid overwriting.
Also note that the name of an array evaluates to a pointer to the first argument, in the proper context. So this:
r=(int*)&vector;
is much better written as just:
r = vector;
You should really avoid casts, and your cast is completely unnecessary.
try this:
#include<stdio.h>
int main() {
int i;
int vector[5]={6,17,28,39,410},*r; //variables declaration
r=(int*)&vector; //pointer declaration
for (i = 0; i<5;i++){ //print the array in using a loop
printf("%d ",vector[i]);
}
printf("\n\n");
for(i=0;i<5;i++){ //print the array in reverse order using a loop
//it should be from the last to the first but it prints it
printf("%d ",*(r+4-i)); //differently, see below
}
return ( 0 );
}
In your code you are changing the first two values. So first two steps Your array
will be like this.
410 39 28 39 410
After that loop continues it will get that replaced value. You can store the replaced value in the another array.
for(i=0,j=4;i<j;i++,j--){
temp=vector[i]; // storing the value in temporary variable
vector[i] = r[j];
r[j]=temp; // assigning the value .
}
for ( i=0; i < 5 ; i ++ )
printf("%d\n",vector[i]);
I'm having trouble with a function to check if a number is prime - it's returning that a number is prime when it isn't sometimes (even numbers sometimes, too!). Any idea why?
int isPrime(long x){
int i;
if(x==2||x==3) return 1; //if i = 2 or 3, return true
if(!(x&1)) return 0; //if x is even return false
for(i=3;i<=sqrt(x);i+=2) if (x%i == 0) return 0; //if x is divisible by i return false
return 1;
}
To everyone, thanks so much for the answers, I'd +1 them all if my rep was high enough :D
Sadly, my idiocy has reached new heights, and I found the error was within logic elsewhere in my program.
Possibly it because of the rounding of the sqrt(x) as result of this function call is floating point value. So it can be a little less than rounded to the closest integer.
In this case e.g. sqrt(25) could be rounded to 4 instead of 5.
EDIT
The fault number on 104730 tells that
if(!(x&1)) return 0; //if x is even return false
doesn't seem to work correctly... So, can you try the x&1L?
I am not sure, but id the size of the int and long is different, and (probably) 1 is implicitly caste to a shorter one type, so possibly it checks incorrect bit...
Also try just
if(!(x%2)) return 0; //if x is even return false
in order to avoid bit patterns usage and platform dependence.
I edited the for-loop to:
for(i=3;i<=x/2;i+=1) if (x%i == 0) return 0;
In the main i go through the first 100 Numbers.
int main()
{
long test=0;
int i = 2;
for( ; i < 100; i++)
{
test = isPrime(i);
if(test == 1) printf("%d ",i);
}
getchar();
return 0;
}
This is the ouput:
and this ist the ouput for the first 100 primes:
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 changed the i+=2 to i+=1, because in your code the skip every second number.
You are not checking whether x is divisble by 2.
Before that for loop add a return 0 if its is divisble by 2.
This is a sample code just to show a different output from the LLVM compiler and the GCC. I wonder why? The answer should be very simple, but I can't see it.
(Xcode 4.6.1)
The code:
#include <stdio.h>
#define MAX(a,b) ( (a) > (b) ? (a) : (b) )
int increment() {
static int i = 42;
i += 5;
printf("increment returns %d\n",i);
return i;
}
int main( int argc, char ** argv ) {
int x = 50;
printf("max of %d and %d is %d\n", x,increment(),MAX(x, increment()));
printf("max of %d and %d is %d\n", x,increment(),MAX(x, increment()));
return 0;
}
The LLVM Output:
increment returns 47
increment returns 52
increment returns 57
max of 50 and 47 is 57
increment returns 62
increment returns 67
increment returns 72
max of 50 and 62 is 72
GCC Output:
increment returns 47
increment returns 52
max of 50 and 52 is 50
increment returns 57
increment returns 62
increment returns 67
max of 50 and 67 is 62
The order of evaluation of the parameters is not defined specified. So this:
printf("max of %d and %d is %d\n", x,increment(),MAX(x, increment()));
causes undefined unspecified behavior . That's why you have different results on both compilers.
Another (potential) problem is: MAX - it could cause two calls to increment. Avoid using such macros.
The LLVM code produces the right results according to ANSI C. If you don't want increment to be called more than once per print statement, save the return value in a variable and use that. Mentally stepping through the code, the display should be
increment returns 47
increment returns 52
increment returns 57
max of 50 and 47 is 57
increment returns 62
increment returns 67
max of 50 and 62 is 72
So my initial reaction and study of the code was wrong, and the LLVM output is right. The reason for the LLVM result is that increment is called three times for each print statement in main. The way to make this code print sensible output is to save the value returned by increment in a variable and print the variable, not another call to increment. The difference in results doesn't depend on undefined behavior as far as I know, but on correct versus incorrect conformance to ANSI C.