I have an integer array
int number[] = {1,2,3,4};
What can I do to get int x = 1234?
I need to have a c version of it.
x = 1000*number[0] + 100*number[1] + 10*number[2] + number[3];
This is basically how decimal numbers work. A more general version (when you don't know how long 'number' is) would be:
int x = 0;
int base = 10;
for(int ii = 0; ii < sizeof(number); ii++) x = base*x + number[ii];
Note - if base is something other than 10, the above code will still work. Of course, if you printed out x with the usual cout<<x, you would get a confusing answer. But it might serve you at some other time. Of course you would really want to check that number[ii] is between 0 and 9, inclusive - but that's pretty much implied by your question. Still - good programming requires checking, checking, and checking. I'm sure you can add that bit yourself, though.
You can think of how to "shift over" a number to the left by multiplying by ten. You can think of appending a digit by adding after a shift.
So you effectively end up with a loop where you do total *= 10 and then total += number[i]
Of course this only works if your array is digits, if it is characters you'll want to do number[i] - '0' and if it is in a different base you'll want to multiply by a different number (8 for instance if it is octal).
int i = 0, x = 0;
for(; i < arrSize; i++)
x = x * 10 + number[i];
x is the result.
int i;
int x = 0;
for ( i = 0; i < 4; i++ )
x = ( 10 * x + number[i] );
int number[]={1,2,3,4}
int x=0,temp;
temp=10;
for(i=0;i<number.length;i++)
{
x=x*temp+number[i];
}
cout>>x;
You could do something with a for loop and powers of 10
int tens = 1;
int final = 0;
for (int i = arrSize - 1; i <= 0; ++i)
{
final += tens*number[i];
tens*=10;
}
return final;
Answer is quite easy.Just list a complete function here.
int toNumber(int number[],arraySize)
{
int i;
int value = 0;
for(i = 0;i < arraySize;i++)
{
value *=10;
value += number[i];
}
return value;
}
Related
I am writing a program in which a certain for-loop gets iterated over many many times.
One single iteration doesn't take to long but since the program iterates the loop so often it takes quite some time to compute.
In an effort to get more information on the progress of the program without slowing it down to much I would like to print the progress every xth step.
Is there a different way to do this, than a conditional with a modulo like so:
for(int i = 0; i < some_large_number; i++){
if(i % x == 0)
printf("%f%%\r", percent);
//some other code
.
.
.
}
?
Thanks is advance
This code:
for(int i = 0; i < some_large_number; i++){
if(i % x == 0)
printf("%f%%\r", percent);
//some other code
.
.
.
}
can be restructured as:
/* Partition the execution into blocks of x iterations, possibly including a
final fragmentary block. The expression (some_large_number+(x-1))/x
calculates some_large_number/x with any fraction rounded up.
*/
for (int block = 0, i = 0; block < (some_large_number+(x-1))/x; ++block)
{
printf("%f%%\r", percent);
// Set limit to the lesser of the end of the current block or some_large_number.
int limit = (block+1) * x;
if (some_large_number < limit) limit = some_large_number;
// Iterate the original code.
for (; i < limit; ++i)
{
//some other code
}
}
With the following caveats and properties:
The inner loop has no more work than the original loop (it has no extra variable to count or test) and has the i % x == 0 test completely removed. This is optimal for the inner loop in the sense it reduces the nominal amount of work as much as possible, although real-world hardware sometimes has finicky behaviors that can result in more compute time for less actual work.
New identifiers block and limit are introduced but can be changed to avoid any conflicts with uses in the original code.
Other than the above, the inner loop operates identically to the original code: It sees the same values of i in the same order as the original code, so no changes are needed in that code.
some_large_number+(x-1) could overflow int.
I would do it like this:
int j = x;
for (int i = 0; i < some_large_number; i++){
if(--j == 0) {
printf("%f%%\r", percent);
j = x;
}
//some other code
.
.
.
}
Divide the some_large_number by x. Now loop for x times and nest it with the new integer and then print the percent. I meant this:
int temp = some_large_number/x;
for (int i = 0; i < x; i++){
for (int j = 0; j < temp; j++){
//some code
}
printf("%f%%\r", percent);
}
The fastest approach regarding your performance concern would be to use a nested loop:
unsigned int x = 6;
unsigned int segments = some_large_number / x;
unsigned int y;
for ( unsigned int i = 0; i < segments; i++ ) {
printf("%f%%\r", percent);
for ( unsigned int j = 0; j < x; j++ ) {
/* some code here */
}
}
// If some_large_number canĀ“t be divided evenly through `x`:
if (( y = (some_large_number % x)) != 0 )
{
for ( unsigned int i = 0; i < y; i++ ) {
/* same code as inside of the former inner loop. */
}
}
Another example would be to use a different counting variable for the check to execute the print process by comparing that to x - 1 and reset the variable to -1 if it matches:
unsigned int x = 6;
unsigned int some_large_number = 100000000;
for ( unsigned int i = 0, int j = 0; i < some_large_number; i++, j++ ) {
if(j == (x - 1))
{
printf("%f%%\r", percent);
j = -1;
}
/* some code here */
}
I'm facing problems in writing a program in C that calculates S, being S = {1/50 - 3/48 + 5/46...} with 9 elements. I don't know how to use the DIFFERENCE operator followed by a SUM operator, and I MUST use the for structure.
Here's the program I wrote:
#include <stdio.h>
#include <stdlib.h>
int main (void) {
int n, d, S, i;
i = 0;
n = 1;
d = 50;
S = n / ((double)d);
for (i = 0; i < 4; i++) {
n += 2;
n -= 2;
S = S + (n / ((double)d));
S = S - (n / ((double)d));
}
printf("%d", S);
return 0;
}
I know that the variable declarations may be wrong and that's exactly where I get confused. I decalred S as an integer but put d (denominator) to double 'cause the result must be a decimal number, of course.
Can anybody help me??
The output I'm getting is: 0
Perhaps like this. The most important point, is to use the double type, because the int type can only hold whole numbers.
#include <stdio.h>
int main (void) {
int i;
double sign = 1.0; // sign
double num = 1.0; // numerator
double div = 50.0; // divisor
double sum = 0.0; // series sum
for (i = 0; i < 9; i++) {
sum += sign * num / div; // accumulate the term
num += 2.0; // numerator +2
div -= 2.0; // divisor -2
sign *= -1.0; // alternate the sign
printf("%f\n", sum); // show double result
}
return 0;
}
Program output:
0.020000
-0.042500
0.066196
-0.092895
0.121390
-0.153610
0.188496
-0.228171
0.271829
Different things to say about your code.
First you cannot use an integer for your sum since you want a floating point result.
Then as mentioned in comments you are using successive operations that result in not changing the variable
n+=2; n-=2;
You could simply do something like :
double S = 0.0; int N=9;
for(i=0; i < N; ++i) {
S += ( (i % 2 == 0)?(1.0):(-1.0) ) * (2.0*i+1)/(50-(2.0*i+1));
}
The instruction (i % 2 == 0)?(1.0):(-1.0) pick 1 if 'i' is even and -1 if 'i' is odd.
Finally if S is no longer an int you must change your printf with a floating point format like for example '%f'.
Check if what you're looking for is the following code:
#include <stdio.h>
#include <stdlib.h>
void main () {
int n = 1, d = 50, i = 0, signal = 1;
double S = n / (double) d;
for (i = 0; i < 8; i++) {
n += 2;
d -= 2;
signal = -signal;
S += signal * n/(double)d;
}
printf("%f", S);
}
I think you're missing S is a double number. int/double = double, but youre assign this math in a int variable.
I'm trying to separate integers stored in array into their separate digits and then add all the separated digits up. The following code is throwing back an expression result unused for the j / 10 portion of my for loop and I'm not sure why. j should be set to the ith variable in the array and as long as j is still above 1, should divide by 10 and execute the following code. Can anyone explain what's wrong here.
int sum = 0;
int digit;
int number;
for (int i = 0; i < cclen / 2; i++) {
for (int j = cc2nd[i]; j > 1; j / 10) {
number = cc2nd[i];
digit = number % 10;
number = number / 10;
sum = sum + digit;
}
}
j / 10
doesn't change j at all, you keep testing the same expression all over again, and the compiler probably even optimizes out the test. Do you mean
j /= 10
instead?
int main(void)
{
const char * attributeNames = "StrDexConIntWisCha";
int characterValues[7] = {0};
int characterBonuses[7] = {0};
characterStats(characterValues);
}
void characterStats(int * characterValues)
{
int numberOfDice = 4; int diceType = 6;
int x = 1;//because characterValues[0] is level.
printf("What is your level? > ");
scanf("%d",&characterValues[0]);
printf("Current Level [%d]", characterValues[0]);
printf("Rolling stats.\n");
for(x; x <= numberOfDice; x++)
{
characterValues[x] = diceRoll(diceType);//rolling a d6
}
}
int diceRoll(int diceType)
{
int numberOfDice = 4;
int x,y,z = 0;
int diceResult, finalValue, lowestResult = 0;
int diceRoll[4] = {0};
for(x; x <= numberOfDice; x++)
{
printf("%d", diceRoll[x]);
}
}
I'm trying to create a function that will roll a 6-sided dice, 4 times, for a character generator for dungeons and dragons. The last for loop in diceRoll, doesn't appear to execute, it just skips it over and I don't understand why. At the moment, I'm just testing to see if everything works before adding in the rand().
int x,y,z = 0;
Here you only initialized z to 0, leaving x and y uninitialized, and then in the for loop:
for(x; x <= numberOfDice; x++)
Again, x is not initialized.
You should always initialize your loop counter in the for loop:
for(x=0; x<numberOfDice; x++)
and too, notice I used < not <=; a loop from 0 will always do n iterations from 0 for <n (using <= will do n+1). Looping from 0 to n-1 is idiomatic in all C-like languages since it tends to match things like indexes an an array being iterated, or pointer manipulations, which are all 0-based.
either make
int x=0,y,z=0;
or make
for(x = 0; x <= numberOfDice; x++)
I saw an interview question which asked to
Interchange arr[i] and i for i=[0,n-1]
EXAMPLE :
input : 1 2 4 5 3 0
answer :5 0 1 4 2 3
explaination : a[1]=2 in input , so a[2]=1 in answer so on
I attempted this but not getting correct answer.
what i am able to do is : for a pair of numbers p and q , a[p]=q and a[q]=p .
any thoughts how to improve it are welcome.
FOR(j,0,n-1)
{
i=j;
do{
temp=a[i];
next=a[temp];
a[temp]=i;
i=next;
}while(i>j);
}
print_array(a,i,n);
It would be easier for me to to understand your answer if it contains a pseudocode with some explaination.
EDIT : I came to knpw it is cyclic permutation so changed the question title.
Below is what I came up with (Java code).
For each value x in a, it sets a[x] to x, and sets x to the overridden value (to be used for a[a[x]]), and repeats until it gets back to the original x.
I use negative values as a flag to indicate that the value's already been processed.
Running time:
Since it only processes each value once, the running time is O(n).
Code:
int[] a = {1,2,4,5,3,0};
for (int i = 0; i < a.length; i++)
{
if (a[i] < 0)
continue;
int j = a[i];
int last = i;
do
{
int temp = a[j];
a[j] = -last-1;
last = j;
j = temp;
}
while (i != j);
a[j] = -last-1;
}
for (int i = 0; i < a.length; i++)
a[i] = -a[i]-1;
System.out.println(Arrays.toString(a));
Here's my suggestion, O(n) time, O(1) space:
void OrderArray(int[] A)
{
int X = A.Max() + 1;
for (int i = 0; i < A.Length; i++)
A[i] *= X;
for (int i = 0; i < A.Length; i++)
A[A[i] / X] += i;
for (int i = 0; i < A.Length; i++)
A[i] = A[i] % X;
}
A short explanation:
We use X as a basic unit for values in the original array (we multiply each value in the original array by X, which is larger than any number in A- basically the length of A + 1). so at any point we can retrieve the number that was in a certain cell of the original array by array by doing A[i] / X, as long as we didn't add more than X to that cell.
This lets us have two layers of values, where A[i] % X represents the value of the cell after the ordering. these two layers don't intersect through the process.
When we finished, we clean A from the original values multiplied by X by performing A[i] = A[i] % X.
Hopes that's clean enough.
Perhaps it is possible by using the images of the input permutation as indices:
void inverse( unsigned int* input, unsigned int* output, unsigned int n )
{
for ( unsigned int i = 0; i < n; i++ )
output[ input[ i ] ] = i;
}