Printf failing to print array of characters - c

My printf() function is continuously printing nothing to the terminal instead of the characters in the array that it is supposed to.
#include <stdio.h>
#include <cs50.h>
int main(void)
{
char s[4];
s[0] = '0';
s[1] = '0';
s[2] = '0';
s[3] = '\0';
int nums[3] = {0, 0, 0};
for (int i = 92; i < 110; i++)
{
// Number maxes at three digits
for (int j = 0; j < 3; j++)
{
nums[2 - j] = i % 10;
i /= 10;
}
for (int k = 0; k < 3; k++)
{
s[k] = (char) nums[k];
}
printf("%s\n", s);
}
}
I am trying to get the program to print out 3 number increasing every time the loop is completed. If the number is not 3 digits all of the not occupied spots should be 0's.

I was testing out your code as others were commenting on your code. As I found testing, the program did not print out anything and can running in an endless loop as a result of the issues noted in the comments. With those comments in mind, following is a refactored version of your program.
#include <stdio.h>
int main(void)
{
char s[4];
s[0] = '0';
s[1] = '0';
s[2] = '0';
s[3] = '\0';
int nums[3] = {0, 0, 0};
int x;
for (int i = 92; i < 110; i++)
{
x = i; /* Need to use a work variable - shouldn't be modifying the loop counter */
// Number maxes at three digits
for (int j = 0; j < 3; j++)
{
nums[2 - j] = x % 10;
x /= 10;
}
for (int k = 0; k < 3; k++)
{
s[k] = (char) nums[k] + '0'; /* As noted in the comments */
}
printf("%s\n", s);
}
}
Things to point out.
As noted, it is not a good idea to be modifying a variable used as a loop counter within a loop as noted in the endless loop behavior experienced, so the loop counter is placed into a work variable for use on the needed calculations.
As also noted in the comments, since an ASCII character value is wanted in the character array, the value of character "0" (zero) would need to be added to the integer value derived for each position in order to attain the equivalent character in the character array.
With those bits refactored, following is the terminal output from a test run.
#Vera:~/C_Programs/Console/PrintChars/bin/Release$ ./PrintChars
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
Give those tweaks a try and see if it meets the spirit of your project.

Related

How to convert each number in a num String to an int in C

I've been trying to do this problem on Project Euler
This is what I've done so far -
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(){
char nums[] = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450"
int64_t sum = 1, new_sum = 0;
int num;
for(int i = 0; i < 988; i+= 13){
sum = 1
for(int j = 0; j < 13; ++j){
//Converting nums[i] to int and storing it to num here
sum *= num;
}
if(sum > new_sum){
new_sum = sum;
}
}
printf("%lld", new_sum);
}
I don't know how to convert each charNum in the String to an integer, I've tried atoi and sscanf and both of them ask for a char pointer.
I get these errors respectively
passing argument to parameter here
int atoi(const char *); //sum *= atoi(nums[i])
format specifies type 'int *' but the argument has type 'int' [-Wformat]
sscanf(nums[i], "%d", num);
Any help is appreciated.
Just converting a character representing a digit to the digit itself is simply done by
int digit = nums[position] - '0';
C language guarantees for any character set that the digits 0-9 are succeeding one another in exactly that order (which is not necessarily the case for alphabetic characters, see e.g. (in-?) famous EBCDIC).
As I read the problem the maximum can be at any location, not only multiples of 13. For this speaks as well that the maximum of four subsequent digits is found at a location where the number of digits preceding is not a multiple of four.
Apart from, unless the number if digits is a multiple of 13, your loops would exceed array bounds of nums, so undefined behaviour (if not a multiple of 13, then for last iteration of i there are less than 13 digits left, but j still tries to iterate over all 13 digits).
Fixing both:
size_t sequenceLength = 13; // could be a function parameter
size_t len = strlen(nums); // sizeof would include the terminating 0 character!
if(len < sequenceLength)
{
return 0; // if within a function, else whatever appropriate error handling
}
uint64_t max = 1; // can't have negative values anyway...
for(size_t i = 0; i < sequenceLength; ++i)
{
max *= nums[i] - '0'; // see above
}
// now we found first possible maximum: the product of first 13 digits
uint64_t num = max;
for(size_t i = sequenceLength; i < len; ++i)
{
// for next product, we have already included the first 12 digits
// within the previous product!
// but there is one surplus digit contained we need to eliminate:
num /= nums[i - sequenceLength] - '0';
// now we can include the yet missing one:
num *= nums[i] - '0';
// or as a one-liner:
num = num / (nums[i - sequenceLength] - '0') * (nums[i] - '0');
// TODO: update maximum, if need be, just as in your code
}
Would you please try the following:
#include <stdio.h>
#include <stdlib.h>
#define N 13
int main() {
char nums[] = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450";
int64_t prod = 1, max_prod = 0;
int num;
int pos;
for (int i = 0; i < sizeof nums; i += N) {
prod = 1;
for (int j = 0; j < N; j++){
// Converting nums[i] to int and storing it to num here
num = nums[i + j] - '0';
prod *= num;
}
if (prod > max_prod) {
max_prod = prod;
pos = i;
}
}
printf("max product = %ld at %.*s\n", max_prod, N, nums + pos);
}
Output:
max product = 6270566400 at 4355766896648
BTW as the variable name sum is misleading, I've changed it to prod for product.
I assume that you want a nuber for each digit (i.e., range 0 to 9)
If yes, the below code should be not too far from what you need:
char nums[] = "73167176531330624919225119674426574742355349194934969835203... (so long)...";
char *p;
long lTheTotalCount, lTheNumber;
lTheTotalCount = 0;
for (p=nums ; *p ; p++) {
lTheNumber = (long)(*p - '0');
lTheTotalCount += lTheNumber;
};

A better approach to add big numbers, Project Euler #13 [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Project euler problem 13
For C program I tried the problem with practical approach, i.e. not defining the data in the code but rather using scanf for taking input.
But I cannot understand why the output is wrong! I get 1373762303 while it should be 5537376230.
It seems ok for 2-3 numbers.
#include <stdio.h>
#include <ctype.h>
#include <strings.h>
#define NUM 50
#define STRINGS 100
#define OUTPUT 10
int main(void) {
char str[STRINGS][NUM+1];
int answer[NUM+1] = {0};
int carry = 0, out_digits = OUTPUT;
for(int i = 0; i < STRINGS; i++){
scanf("%s", str[i]);
for(int j = NUM; j >=0; j--){
answer[j] += (str[i][j] - 48) + carry;
if(answer[j] > 9){
carry = answer[j] / 10;
answer[j] %= 10;
}else{
carry = 0;
}
}
}
printf("--------------------------------------------------\r\n");
printf("%d",carry);
for(int j = 0; j < OUTPUT-1; j++){
printf("%d",answer[j]);
}
printf("\r\n--------------------------------------------------");
return 0;
}
scanffills in the array you give it with a string constructed from the input including a null terminator byte. You allocate 51 bytes correctly but when you start adding the digits, you start at index 50 which is the index of the nul byte. The actual digits are from indexes 0 to 49.
This means that you will get a carry into the units digit of your answer at some point because the answer for that digit is calculated as
answer[50] += (str[i][50] - 48) + carry;
// ^^^^ correction applied for ASCII
Another issue is that you forget to reset carry to zero at the beginning of adding each new number.
This might work (not tested) but it still doesn't really handle overflows in the top digits
for(int i = 0; i < STRINGS; i++){
scanf("%s", str[i]);
carry = 0; // Reset the carry
for(int j = NUM - 1; j >=0; j--){
answer[j] += (str[i][j] - 48) + carry;
if(answer[j] > 9){
carry = answer[j] / 10;
answer[j] %= 10;
}else{
carry = 0;
}
}
}
I got the answer, it was the missing carry over when adding the two numbers. Following is the solution:
#include <stdio.h>
#include <ctype.h>
#include <strings.h>
#define NUM 50
#define STRINGS 100
#define OUTPUT 10
int main(void) {
char str[STRINGS][NUM+1];
int answer[NUM+1] = {0};
int carry = 0, out_digits = OUTPUT, intm_carry = 0;
for(int i = 0; i < STRINGS; i++){
scanf("%s", str[i]);
for(int j = NUM; j >=0; j--){
answer[j] += (str[i][j] - 48) + carry;
if(answer[j] > 9){
carry = answer[j] / 10;
answer[j] %= 10;
}else{
carry = 0;
}
}
intm_carry += carry;
carry = 0;
}
printf("--------------------------------------------------\r\n");
printf("%d", intm_carry);
for(int j = 0; j < OUTPUT-1; j++){
printf("%d",answer[j]);
}
printf("\r\n--------------------------------------------------");
return 0;
}

Convert int to bytes array in c

I would like to convert an int to a char[4] where each byte in the char[4] contains a decimal value of 2. So in the following example:
int p = 2999999;
Convert p to the array that is identical to k where k is constructed via:
char k[4];
k[0] = 2;
k[1] = 99;
k[2] = 99;
k[3] = 99;
How can I do this in C?
Thanks in advance!
It's strange problem for me but OK. here's what I would have done:
Copy value of p so that it can be used later (I assume that this conversion doesn't intend to change its value).
Use modulo operation to get 2 last digits
cut down the copy of p to be able to read next two digits.
So complete answer is:
#include <stdio.h>
int main()
{
int p = 2999999;
char k[4];
int p_copy = p;
int i;
for(i = 3; i >=0; i--)
{
k[i] = p_copy % 100;
p_copy /= 100;
}
for(i = 0; i < 4; i++)
printf("k[%d]: %d\n",i, k[i]);
return 0;
}
And for sanity the output:
gonczor#wiktor-papu:~/tmp$ gcc test.c -o test
gonczor#wiktor-papu:~/tmp$ ./test
k[0]: 2
k[1]: 99
k[2]: 99
k[3]: 99
for (i =4; i--; k[i] = p % 100, p /= 100);

Generate array of unique characters in C

I'm trying to generate an array of 10 random but unique characters. Sometimes when I run the code, characters are not unique.
I would appreciate any help. Thank you.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL));
char letters[10];
for (int i = 0; i < 10; i++) {
letters[i] = 97 + rand() % (122-97);
for (int j = 1; j < i; j++) {
if (letters[i]==letters[j]) {
letters[i] = 97 + rand() % (122-97); // continue
}
}
printf("%c\n", letters[i]);
}
}
The problem is that random can give the same number. It doesn't know you want a different number every time.
This is how to solve this, I am telling you the way, you will need to program it.
Decide what characters are participating, then create an array that holds these characters.
Then roll the dice to give a number within the array range. The number you get is an index to the array, you then take the character in that index.
Then you take the last characters in the array and put in that index, and the next time you roll the dice you limit the max number to one less the original size of the array.
You continue with this algorithm until you get all the required amount of characters.
This algorithm ensures that you get different characters.
Your code checks only if the character you just generated is different from its predecessor in your array ; you should try with a flag like that :
srand(time(NULL));
char letters[10];
int is_unique = 1, i=0,j ;
while (i<10){
is_unique = true;
letters[i] = 'a' + rand() % 26;
for(j=0;j<i;j++){
if (letters[i]==letters[j])
is_unique = false;
}
if (is_unique)
i++;
}
BTW, it's better to replace rand() % (122-97) by simply 26, it's more clear for anyone reading your code.
Another way would be :
srand(time(NULL));
char letters[10];
int j;
for (int i = 0; i < 10; i++)
{
letters[i] = 'a' + rand() % 26;
j=0;
while (j<i) {
if (letters[i]==letters[j]){
letters[i] = 'a' + rand() % 26;
j = 1;
} else
j++;
}
printf("%c\n", letters[i]);
}

Printing alphabet pyramid in C

I'm trying to write a program in C that gives a 13 row pyramid with the following output (notice the pattern of the letters i.e BCB):
A
BCB
DEFED
GHIJIHG
KLMNONMLK
PQRSTUTSRQP
VWXYZABAZYXWV
CDEFGHIJIHGFEDC
KLMNOPQRSRQPONMLK
TUVWXYZABCBAZYXWVUT
DEFGHIJKLMNMLKJIHGFED
OPQRSTUVWXYZYXWVUTSRQPO
ABCDEFGHIJKLMLKJIHGFEDCBA
Here is my attempt at the solution:
#include <stdio.h>
#include <stdlib.h>
int main(void){
char c = 'A';
int height = 13;
int max = 1;
for (int i = 1; i <= height; i++){
//int j = 1;
for (int k = 0; k < height - i; k++)
printf(" "); // print space on left
for (int j = 1; j <= max; j++){
if (j <= max / 2){ // print left side of pyramid
printf ("%c", c);
c = (c - 'A' + 1) % 26 + 'A';
}
else{ // print right side of pyramid
printf ("%c", c);
c = (c -'A' + 25) % 26 + 'A';
}
}
printf("\n");
max += 2;
}
}
However it gives the following incorrect output:
A
ZAZ
YZAZY
XYZAZYX
WXYZAZYXW
VWXYZAZYXWV
UVWXYZAZYXWVU
TUVWXYZAZYXWVUT
STUVWXYZAZYXWVUTS
RSTUVWXYZAZYXWVUTSR
QRSTUVWXYZAZYXWVUTSRQ
PQRSTUVWXYZAZYXWVUTSRQP
OPQRSTUVWXYZAZYXWVUTSRQPO
if I remove the the if/else statement which splits the pyramid in to two sides and simply have only c = (c - 'A' + 1) % 26 + 'A';, I get the following output:
A
BCD
EFGHI
JKLMNOP
QRSTUVWXY
ZABCDEFGHIJ
KLMNOPQRSTUVW
XYZABCDEFGHIJKL
MNOPQRSTUVWXYZABC
DEFGHIJKLMNOPQRSTUV
WXYZABCDEFGHIJKLMNOPQ
RSTUVWXYZABCDEFGHIJKLMN
OPQRSTUVWXYZABCDEFGHIJKLM
Any ideas?
The problem is that you're forgetting to increment the actual overall character. For each line, you need to add characters until you get to the value that you should start at for the next line. Thankfully, this is pretty easy to do:
...
max += 2;
c = (c - 'A' + max / 2 + 1) % 26 + 'A'; // Add this line
}
Here's a short version:
#include <stdio.h>
#define HEIGHT 6
int main(void) {
char* f = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char* b = "ZYXWVUTSRQPONMLKJIHGFEDCBA";
int c = 0;
for(int i=0; i<HEIGHT; ++i)
{
printf("%*.*s%.*s\n", 10, i+1, f+i+c, i, b+strlen(b)-(c+2*i));
c+=i;
}
return 0;
}
IDEOne Link
Output:
Success #stdin #stdout 0s 9424KB
A
BCB
DEFED
GHIJIHG
KLMNONMLK
PQRSTUTSRQP

Resources