Creating an evenly spaced array of double precision values - c

I'm a noob in C and I come from Matlab. I'm going crazy to do a very simple operation like creating an array of evenly spaced numbers.
What I want to do is have an array of 50 elements, starting from 0 with a constant increment of 0.1.
In matlab it would be as simple as:
n=50;
h=0.1;
t=0:h:(n-1)*h;
In C I am trying this:
#include<stdio.h>
int main() {
int n = 50;
double h = 0.1;
double t[n];
t[0] = 0;
int i;
for (i = 0; i <= n; i++){
t[i+1] = t[i] + h;
printf("%i %d\n",i, t[i]);
}
return 0;
}
And the output is something crazy like:
0 0
1 -1717986918
2 -1717986918
3 858993460
4 -1717986918
5 0
6 858993459
7 1717986918
8 -1717986919
9 -858993460
10 -1
...
And I really can't understand why.
Thanks for your help!

In printf("%i %d\n",i, t[i]), t[i] is a double, but %d requires that you pass an int. Use %g for a general format for printing double.

Related

Storing the right value in a two dimensional array in c. But when I tried to print the value it shows bigger value and even negative number

Problem:
In this question I tried to solve a bitwise operator problem. Giving two number as input
Input will be two number. Here is some input:
n = 3
k = 3
Then I need to construct "a" and "b" in some way(for instance when "a = 1" then b will be one past a to <= n. The results of the comparisons are below:
a b and or xor
1 2 0 3 3
1 3 1 3 2
2 3 2 3 1
Here is my code:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
//Complete the following function.
void calculate_the_maximum(int n, int k)
{
// Two dimentional array for storing the value of and or xor
int rowOfArray = 3;
int sets[rowOfArray][k];
//For loop for a
for (int i = 0; i < k; i++)
{
int a = i + 1;
//For loop for b
for (int j = a; j < n; j++)
{
int b = j;
b++;
printf("{%i, %i}\n", a, b);
//Storing and operation result to the array
sets[0][j - 1] = a&b;
printf("And: %i\n", sets[0][j - 1]);
//Storing or operation result to the array
sets[1][j] = a|b;
printf("Or: %i\n", sets[1][j]);
//Storing xor opertaion result to the array
sets[2][j + 1] = a^b;
printf("Xor: %i\n", sets[2][j + 1]);
}
}
//Find the biggest number in array
for (int i = 0; i < rowOfArray; i++)
{
int big;
for (int j = 0; j < k; j++)
{
big = 0;
printf("Big1: %i\n", big);
if (big < sets[i][j])
{
big = sets[i][j];
printf("Big2: %i\n", big);
}
}
printf("big3: %i\n", big);
if (big < k)
{
printf("%i\n", big);
}
else
{
printf("%i\n", 0);
}
}
}
int main() {
int n, k;
scanf("%d %d", &n, &k);
calculate_the_maximum(n, k);
return 0;
}
I used too many printf function to show that what have I done wrong. I stored the value as I expected but later in the for loop when I tried to print the specific position integer I didn't get the correct result even sometimes I got bigger and negative number too.
Here is the output:
3 3
{1, 2}
And: 0
Or: 3
Xor: 3
{1, 3}
And: 1
Or: 3
Xor: 2
{2, 3}
And: 2
Or: 3
Xor: 1
Big1: 0
Big1: 0
Big2: 2
Big1: 0
Big2: 120329728
big3: 120329728
0
Big1: 0
Big2: 1986993953
Big1: 0
Big2: 3
Big1: 0
Big2: 3
big3: 3
0
Big1: 0
Big1: 0
Big2: 32765
Big1: 0
Big2: 3
big3: 3
0
As is, for the input 3 3, j holds the values 1, 2, and 2, so clearly sets[2][j + 1] is Undefined Behaviour since it accesses the subarray at index 3, when valid indices are [0, 2].
Given the source problem, the issues are more clear.
k is simply a limit on output, and should not be used as a bound for iteration, or for calculating the storage required for the number of k-combinations.
It is unnecessary to store all the results at once. For each combination, each value of the operation a ? b (where ? is a bitwise operator) can be tested against the value k and the currently stored maximum value for the given operator.
Here is a quick solution. Compile with -DDEBUG to see additional output.
#include <stdio.h>
void setmax(int *dest, int value, int limit)
{
if (value < limit && value > *dest)
*dest = value;
}
void calc(int n, int k)
{
int and = 0;
int or = 0;
int xor = 0;
#ifdef DEBUG
printf("INFO: a b and or xor\n");
#endif
for (int a = 1; a < n; a++) {
for (int b = a + 1; b <= n; b++) {
setmax(&and, a & b, k);
setmax(&or, a | b, k);
setmax(&xor, a ^ b, k);
#ifdef DEBUG
printf("INFO: %-3d %-3d %-3d %-3d %-3d\n",
a, b, a & b, a | b, a ^ b);
#endif
}
}
printf("%d\n%d\n%d\n", and, or, xor);
}
int main(void)
{
int n, k;
if (2 != scanf("%d%d", &n, &k))
return 1;
calc(n, k);
}
Sample runs:
./a.out <<< "3 3"
2
0
2
./a.out <<< "5 4"
2
3
3
If you run the code, you'll get stack corruption error which is due to indexing the array beyond its allocated size. Accessing memory that's not for your program is undefined behavior. Anything might happen. The program may crash or it may not. For my specific compiler and the fact that I ran the code in debug mode and not release mode, the program crashed with the error I mentioned.
Now to fix the error, from what you explained, you have three columns for and, or and xor. So you need to reverse the dimensions of set (set[k][rowOfArray], better change the name to rowSize or n_columns or so). Also reverse the indexing, e.g. change set[0][j-1] to set[j-1][0] and so on. I'm not sure what you're trying to do in the second part, though.

Splitting a 2D array size to a smaller 2D Array size in C

Disclaimer: I'm not very good with words, I have included a sample of how will it look like below.
So I'm trying to reduce this 4x4 array into a bunch of 2x2 arrays. (See sample below)
int disp[4][4] = {{12,4,32,9}, {19,24,3,4},{1,26,3,8},{3,24,7,5} };
/*
12 4 32 9 12 4 | 32 9
19 24 3 4 into something like 19 24 | 3 4
1 26 3 8 =============
3 24 7 5 1 26 | 3 8
3 24 | 7 5
*/
Take note: it is splitting it into smaller sizes (bunch of 2D arrays)
I have tried splitting it using a for loop code but only getting the 2nd quadrant.
code below:
int i,j;
for(i=0;i<2;i++)
for(j=0;j<2;j++)
printf("%d\n",disp[i][j]);
see that this only gives me 12,4,19 and 24.
Is there a way to get the other quadrants? How would this work for bigger sizes? (Lets say 28x28 to 14x14) I would really appreciate the help. Thank you.
Let's consider a NXN matrix where N and quadrant_size be the required size of sub_matrix to be printed.
We first traverse to find the starting element to be printed in each sub_matrix.
i.e: From 0 to N incrementing by quadrant_size for row and 0 to N incrementing by quadrant_size for column.(First two loops in the below given code)
Let's say (x,y) index at any position. Now we print the matrix elements from (x,y) to (x+2,y+2)
The below code is generalized for any size of matrix NxN of required quadrant_size where N should be divisible by quadrant_size.
int quadrant_size=2;
//outer loop to traverse the starting elements of the sub array
for(int x=0 ; x<N ; x+=quadrant_size){
for(int y=0 ; y<N ; y+=quadrant_size){
//inner loop to print matrix
for(int i=x ; i<x+quadrant_size ; i++){
for(int j=y ; j<y+quadrant_size ; j++){
printf("%d ",disp[i][j]);
}
printf("\n");
}
printf("\n");
}
}
You need to add an offset to i and j depending on which quadrant you want to print.
For your specific case it could be:
int main() {
int disp[4][4] = {{12,4,32,9},
{19,24,3,4},
{1,26,3,8},
{3,24,7,5} };
// calculate quadrant size (it will be 2 in this case)
int qsize = sizeof disp[0] /sizeof disp[0][0] / 2;
int q = 3; // <--- The quadrant to print
int offset_i = 0; // Extra offsets for
int offset_j = 0; // the loop that prints
if (q == 1)
{
offset_j = qsize;
}
else if (q == 3)
{
offset_i = qsize;
}
else if (q == 4)
{
offset_i = qsize;
offset_j = qsize;
}
for(int i=0; i<qsize; i++)
{
for(int j=0; j<qsize; j++)
{
printf("%d ",disp[i + offset_i][j + offset_j]);
// Notice: ^^^^^^^^^^ ^^^^^^^^^^
}
printf("\n");
}
return 0;
}

how to print a table of even squares?

This program prompts the user a number and then outputs a table of even squares ranging from 2 to the number.
#include <stdio.h>
int main(void)
{
int i, n;
puts(This program prints a table of even squares.);
printf("Enter range of the squares square: ");
scanf("%d", &n);
for (i = 2; i * i <= n; i += 2)
printf("%d\n", i * i);
return 0;
}
for example:
Enter range of the squares: 123
2 4
4 16
6 36
8 64
10 100
The problem is did not print 121 (which is 11 * 11). I am new to C and not really good in using loops. Please help!
for (i = 2; i * i <= n; i += 2)
You're starting at 2 and incrementing by 2. i will never be 11.

A bug on bubble sorting

I want to sort a 2*n matrix, n is given in the input. Make a program to output a matrix. Here is the requirement:
the first column MUST be sorted in ASC, and
the second column in DESC if possible.
For example, let n = 5, and the matrix is
3 4
1 2
3 5
1 6
7 3
The result should be
1 6
1 2
3 5
3 4
7 3
So I write down the code like this. First line input the value n, and the following lines like above.
#include <stdio.h>
#define TWO_16 65536
#define TWO_15 32768
int v[100000][2];
int z[100000];
int vec[100000];
int n;
int main()
{
int i, j;
scanf ("%d", &n); // give the value of n;
for (i = 1; i <= n; i++) // filling the matrix;
{
scanf ("%d%d", &v[i][0], &v[i][1]);
z[i] = TWO_16 * v[i][0] + TWO_15 - v[i][1];
vec[i] = i;
}
for (i = 1; i <= n; i++)
for (j = 1; j <= i; j++)
{
if (z[j] > z[i])
{
int t = vec[i];
vec[i] = vec[j];
vec[j] = t;
}
}
for (i = 1; i <= n; i++) // output the matrix
printf("%d %d\n",v[vec[i]][0],v[vec[i]][1]);
return 0;
}
But in gcc, the output is
1 6
3 5
3 4
1 2
7 3
What's more, when the first line is changed to "1 2" and the second is changed to "3 4" in input, the result also changed.
What's the problem of my code?
Additional information:
I use z[] because I use a function that satisfy the requirement of this problem, so I can simply sort them. And vec[] stores the original index, because moving arrays may cost lots of time. So v[vec[i]][0] means the 'new' array's item i.
Note that v[0] is NOT used. n is less than 100000, not equal.
You are comparing values stored in z[], but swapping elements of vec.
So when in the begginig you have:
i vec z
------------------
1 1 z[1]
2 2 z[2]
3 3 z[3]
...
After for e.g. swapping 2 with 3
i vec z
------------------
1 1 z[1]
2 3 z[2]
3 2 z[3]
...
you will have improper mapping between vec and z.
So in another iteration you will again compare z[2] with z[3] and again you will have to swap elements of vec. That's why you should at least also swap elements of z or index elements of z using elements of vec
i vec z
------------------
1 1 z[vec[1]] = z[1]
2 3 z[vec[2]] = z[3]
3 2 z[vec[3]] = z[2]
...
Adding this should do the trick
...
int t = vec[i];
vec[i] = vec[j];
vec[j] = t;
//Add this also when swapping vec
t = z[i];
z[i] = z[j];
z[j] = t;
...
Array index start with 0, so your for cicles must start from 0
if (z[j] > z[i]): you want to sort v but you are comparing z and sorting vec. By sorting vec and comparing z bubble sort cannot work. You must use the same array.

Formatting help for command prompt output in C

#include <stdio.h>
#include <stdlib.h>
int power(int base, int power){
int result, i;
result = 1;
for (i=0; i < power; i++){
result *= base;
}/*for*/
return result;
}/*power*/
int main (){
int n = 0;
int exponent = 0;
while(n < 10){
int answer = power(2, n);
float neganswer = 1.0 / (power(2,n));
printf("%d %d %g\n", exponent, answer, neganswer);
exponent++;
n++;
}/*while*/
return EXIT_SUCCESS;
}/*main*/
When this program runs, the 2nd function goes from 1 to 512, which pushes the rest of the columns are moved 2 to the right. How would I go about lining up these columns? Thanks.
You can change your printf format to:
printf("%d %3d %10g\n", exponent, answer, neganswer);
This will format the argument to the specific width:
0 1 1
1 2 0.5
2 4 0.25
3 8 0.125
4 16 0.0625
5 32 0.03125
6 64 0.015625
7 128 0.0078125
8 256 0.00390625
9 512 0.00195312
Not to take away from the all ready provided fine 2 answers, but many options are available with printf().
// Nicely aligned with decimal point in the same place
// # : Alternate form always prints `.`
// - : Left justify the output.
// .* : Determine width from the next parameter which is `n`.
printf("%d %4d %#-.*f\n", exponent, answer, n, neganswer);
0 1 1.
1 2 0.5
2 4 0.25
3 8 0.125
4 16 0.0625
5 32 0.03125
6 64 0.015625
7 128 0.0078125
8 256 0.00390625
9 512 0.001953125
C string that contains the text to be written to stdout.
It can optionally contain embedded format specifiers that are replaced by the values specified in subsequent additional arguments and formatted as requested.
A format specifier follows this prototype: [see compatibility note below]
%[flags][width][.precision][length]specifier
int main (){
int n = 0;
int exponent = 0;
while(n < 10){
int answer = power(2, n);
float neganswer = 1.0 / (power(2,n));
//modify printf("%d %d %g\n", exponent, answer, neganswer);
printf("%d %4d %12g\n", exponent, answer, neganswer);
exponent++;
n++;
}/*while*/
return EXIT_SUCCESS;
}/*main*/
more about printf function, please refer to the following link
http://en.cppreference.com/w/c/io/fprintf
Take a look at my simple library: libtprint , the code there is quite easy to understand and you should get some basic ideas how to format columns with printf ().
Hope it helps !
Try this
float neganswer = 1.0f / (power(2,n));
printf("%d %3d %f\n", exponent, answer, neganswer);

Resources