Increasing a digit end of string value - c

I want to increase a value end of string with for loop in C.
You will see 2 for loop i actually wanted to increase i and x value simultaneously. I am new in C I moved from python and I am also open to your advice about C.
P.S: DL_ numbers actually is not static I increment them with external button so I should get their value dynamically
For example :
uint8_t DL_1=7;
uint8_t DL_2=4;
uint8_t DL_3=2;
uint8_t DL_4=1;
for(int i=0;i<=180;i+=16) {
for(int x=1;i<=4;i++) {
printf(i,DL_x)
}
}

for(int i=0;i<=180;i+=16) {
for(int x=1;i<=4;i++) {
printf(i,DL_x)
}
}
You're increasing i twice.
Maybe the second loop should use x everywhere: for(int x = 1; x <= 4; x++).
To print two integers separated by a space and terminated with a newline, printf() should be used as printf("%d %d\n", i, DL_1);
Consider using an array (and remember array indexes go from 0 to n - 1) rather than 4 separate variables
int DL[4] = {7, 4, 2, 1};
printf("%d\n", DL[1]); // prints 4

To increment x and i simultaneously, you can use just a single loop with comma separated statements:
for(int i = 0, x = 1; i <= 180 ; i += 16, x++)
{
printf(i,DL_x);
}
But there are other problems with your code, so it still will not compile, which I hope you understand.

Related

First number in array not transferring to new array correctly

I am writing a program to break numbers in an array into their digits then store those digits in a new array. I have two problems:
It does not display the first number in the array (2) when transferred to the second array, and I am not entirely sure why.
The array may contain 0's, which would break my current for loop. Is there another way to implement a for loop to only run for as many numbers are stored in a array without knowing how big the array is?
#include <cs50.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
// Setting an array equal to test variables
int sum[50] = { 2, 6, 3, 10, 32, 64 };
int i, l, k = 0, sumdig[10], dig = 0;
// Runs for every digit in array sum, increases size of separate variable k every time loop runs
for (i = 0; sum[i] > 0; i++ && k++)
{
sumdig[k] = sum[i] % 10;
dig++;
sum[i] /= 10;
// If statement checks to see if the number was two digits
if (sum[i] > 0)
{
// Advancing a place in the array
k++;
// Setting the new array position equal to the
sumdig[k] = sum[i] % 10;
dig++;
}
}
// For testing purposes - looking to see what digits have been stored
for (l = 0; l < dig; l++)
{
printf("%i\n", sumdig[l]);
}
}
This is the output:
6
3
0
1
2
3
4
6
0
Solution:
It does not display the first number in the array (2) when transferred to the second array
changes i++ && k++ into i++,k++
Is there another way to implement a for loop to only run for as many numbers are stored in an array
There are many different ways but here is some to illustrate it in a few different scenarios:
1. The array length is known and fixed:
Let the compiler automatically allocate the array for you. And then for(i=0; i<6; i++)
2. Able to calc the array length:
Then count the number of elements when initializing the array into a varible. Then just for(i=0; i<SizeCount; i++)
3. Not-able to know array size for some reason:
It is rare but, in that case, you can pre-set a stop criteria i.e. -1 or some other flag so that you can stop when it reaches the terminator i.e. set or pre-set all other values of sum to be -1. Then you can while(sum[i] != -1) This is how string lengths work in C, either with NULL termination (string end with the number 0 or value NULL) or, with input, the line break character \n indicating a termination.
DEMO
Here is a demo of full code with some explanation:
#include <stdio.h>
int main(void){
int sum[] = {2, 6, 3, 10, 32, 64}; // compiler is smart enough know the size
int i, k = 0, sumdig[10], dig = 0;
// Runs for every digit in array sum, increases size of seperate variable k everytime loop runs
for(i = 0; i < sizeof(sum)/sizeof(int); i++, k++){
sumdig[k] = sum[i] % 10;
dig++;
sum[i] /= 10;
// If statement checks to see if the number was two digits
if (sum[i] > 0)
{
// Advancing a place in the array
k++;
// Setting the new array position equal to the
sumdig[k] = sum[i] % 10;
dig++;
}
}
// For testing purposes - looking to see what digits have been stored
for(i = 0; i < dig; i++){
printf("%i\n", sumdig[i]);
}
}
Compile and run
gcc -Wall demo.c -o demo
./demo
Output
2
6
3
0
1
2
3
4
6

Iterate through an array with nonconsecutive integers

I'm writing a code that will call a function repeatedly for each value in the Fibonacci sequence. For instance, let's say I want to print the sequence number each iteration, but I also want to print it in iteration-number times in that particular iteration. I'll want my output to be
1 1 22 333 55555 88888888 ... and so on.
Currently, I have a for-loop set up that creates an array with the Fibonacci sequence:
for(index = 0; index < 10; index++)
{
fibonacci[index] = fibonacci[index] + fibonacci[index-1]+fibonacci[index-2];
}
I'm not sure where to proceed from here. I've experimented with adding additional for-loops both inside and outside this one, but I'm coming up short. Primarily the problem lies within the fact that the loop can't take on the sequene's nonconsecutive values.
You need to have a nested for loop, this means a for loop within your for loop for the repetitive display of characters.
int a = 0;
int b = 1;
int c = 0;
for (int i = 0; i < 10; i++){
c = a + b;
a = b;
b = c;
for(int x = 0; x < c; x++) {
System.out.print(c);
}
System.out.print(" ");
}

Sorting gives inconsistent results, due to loop bound

Program Design, our first homework assignment was to take 4 integer values, add the 2 highest together and subtract the lowest two and square that result. Finally, compare the 2 values together to see if they are equal or not.
For example, if you were to enter: 20 10 60 40
You'd get
60 + 40 = 100
and
20 - 10 = 10 --> 10^2 = 100
So, 100 == 100
I wrote my program and tested it for various values which all returned correct results. My professor told me my program failed for all 10 test inputs and he sent me the results he got. The results he got aren't the same as mine, and I don't know what's going on. I emailed him, and he told me one of my for loops has incorrect bounds. He's right, but I still get the right results, so...?
Here's the code, any help would be appreciated!
/*
// Author: Jesse W
// Assignment 1
// Desciption:
// This program inputs four integer numbers a, b, c and d and
// determines if the sum of the two largest numbers is the same
// as the squared difference of the two smallest numbers
*/
#include <stdio.h>
/* Complete the code for this program below */
int main()
{
int a, b, c, d, f, k, swap;
int array_size = 4;
int return_val;
int sum, difference, square;
int small_1, small_2, large_1, large_2;
int array[array_size];
//Gather input
//printf("Enter integer values for a, b, c and d.\n");
return_val = scanf("%d %d %d %d", &a, &b, &c, &d);
//Validate input
if (return_val != 4)
{
printf("INVALID INPUT\n");
}
else
{
//Assign values to array
array[0] = a;
array[1] = b;
array[2] = c;
array[3] = d;
//Sort array
for (k = 0 ; k < ( array_size - 1 ); k++)
{
for (f = 0 ; f < array_size ; f++)
{
if (array[f] > array[f+1]) /* For decreasing order use < */
{
swap = array[f];
array[f] = array[f+1];
array[f+1] = swap;
}
}
}
//Assign sorted values to new variables
small_1 = array[0];
small_2 = array[1];
large_1 = array[2];
large_2 = array[3];
//Compute math
sum = large_1 + large_2;
difference = small_1 - small_2;
square = difference * difference;
//Compute logic
if(sum == square)
{
printf("%d equals %d.\n", sum, square);
}
else
{
printf("%d does not equal %d.\n", sum, square);
}
return 0;
}
}
f ranges up to array_size - 1
for (f = 0 ; f < array_size ; f++)
but in that case you access array[ f + 1 ] which is array[ array_size ]
array[f] = array[f+1];
array[f+1] = swap;
This results in undefined behavior. Since the value one past the end is effectively sorted as part of the array, whether the program works or not depends whether the uninitialized value is larger than all the input values.
The problem is indeed the upper bound on your inner for loop; it's causing you to read past the end of your array, which causes undefined behaviour.
It's entirely possible that the resulting program still prints the correct results on your machine, but there is no guarantee that it will work on anyone else's. Hence undefined.
Your inner loop will end up accessing array[4], which triggers undefined behavior. As soon as you trigger undefined behavior, you can't guarantee anything about the program after that point.
What's likely actually happening, though, is that on your computer, array[4] just happens to be larger than array[3] and you keep those in the same order. On your professor's computer, you swap them (probably corrupting some other variable), making array[3] be that undefined value.
Since your program's output depends totally on the value of array[4], where array is an array of length 4, its behavior is completely unpredictable: there's no way, from the source, to guess what value will happen to be in memory at location array + 4.
(In fact, it's even worse than that — your program invokes undefined behavior, which means that it's allowed to do absolutely anything at all, up to including sending your professor a vulgar and insulting e-mail that looks like it's from you. But in practice, it's likely to print one of its expected outputs, there's just really no way to guess which one.)
Change your sort loop to this
for (k = 0 ; k < array_size ; k++)
{
for (f = 0 ; f < (array_size -1) ; f++)
{
if (array[f] > array[f+1]) /* For decreasing order use < */
{
swap = array[f];
array[f] = array[f+1];
array[f+1] = swap;
}
}
}

For loop output in C

I am trying to understand the for loop better. I have the following variables:
x = 1
y = 10
I want to increment x and double it ten times with a for loop to have the following output: 1, 2, 4, 8, 16, etc.
This is what I have, but it is not quite doing the trick:
int x = 1;
int y = 10;
for (int i = 0; i < y; i++)
{
x *= 2;
}
printf("%d\n", x);
Do I need another variable to do this?
It looks fine to me. If you want it to print at each iteration, you need to move the printf into the loop.
Also, your code will only work in C99 or with GCC's default extensions since you have int i inside the for loop.
If you want it to display a running count then you should place printf inside the for-loop, so it gets executed with each iteration.
Do I need another variable to do this?
No. You could actually remove a variable - y. It is unneeded and you can specify 10 directly in the loop's conditional:
int i = 0;
int x = 1;
for (i = 0; i < 10; i++)
{
x *= 2;
printf("%d\n", x);
}
I want to increment x and double it ten times with a for loop to have the following output: 1, 2, 4, 8, 16, etc.
Your example contradicts your requirement. Incrementing an integer and doubling it would look produce 1, 4, 6, 8, 10, 12, 14...n. They are simply multiples of two. Your example produces powers of two, i.e.,
int x;
for( x = 0; x < 10; ++x )
{
printf("%d\n", pow(2, x) );
}
for (int i = 0; i < y; i++)
{
x *= 2;
printf("%d\n", x);
}
Think you want the printf statement inside the for loop... between the { and the }.
int x = 1;
int y = 10;
int i = 0;
int main() {
for(i = 0; i < y; i++) {
x *= 2;
printf("%d\n", x);
}
return 0;
}
Output:
2
4
8
16
32
64
128
256
512
1024
your answer contradict with your source code,if you want to print 1,2,4,8,16,... you will get first element 2, because you are multiplying every iteration 2 times than its value, you do not need to use extra variable,moreover you can remove y,put directly 10 and use printf statement inside {}.hope it will help
if you know that you have to increment it for only 10 times. Then why to use extra variable ? use this....
for(x = 1; x<=1024; x*=2)
{
printf("%d ",x);
}

For C Language: How to do you Display a growing Series of Numbers using the For Loop per line?

How do you make C use the For Loop Statement and generate this:
1
12
123
1234
12345
123456
1234567
12345678
I know this requires that the value "1" to be continuously be multiplied with "10" and added with "1".
since the sequence ended with 12345678, this loop only goes to 8, if wanted otherwise, the constraints should be changed approriately
int result = 0;
int i;
for(i = 1; i < 9; i++)
{
result = result * 10 + i;
printf("%d\n", result);
}
As an alternative to using integers to contain the result, you might want to use a character buffer, appending the loop index. If you need 10+, you could mod the index and continue with a repeating sequence for the desired length.
No code given, as it is homework!
Is this homework?
Use a variable to keep track of the current number. On the next iteration, multiply by ten and add the next number in the series.
#include "stdio.h"
int main() {
int current = 0;
int i;
for (i = 1; i < 10; i++) {
current = current * 10 + i;
printf("%d\n", current);
}
}

Resources