I have this code that the input is random for example :
33 32 65 55 44 pe *&44^ %123^
now I need to find which two digit number was repeaed most (and the number needs to contain digits from 1 to 9, which mean 10,30.. are not valid numbers), now what seperate between two digit number to another is every input exept for another number,
in this case I want the output to be 44 then I will print:
The winner couple is: 4 blue, 4 red.
now I thought the best way to do something like this is using 2D array, that when a input is valid I will apdate the array in the sutble place, and after that I will find the maximum place in the array.
here is my code so far :
#include <stdio.h>
#include <stdlib.h>
#define N 9
int is_digit(char c);
void update_array(int num[N][N]);
int find_max(int b[N][N]);
int main()
{
int i,j;
int num[N][N];
int maximum=0,a=0,b=0;
for(i=0;i<N;++i)
{
for(j=0;j<N;++j)
{
num[i][j]=0;
}
}
update_array(num);
maximum=find_max(num);
a=maximum/10;
b=maximum%10;
printf("The winner couple is: %d blue, 4%d red.",a,b);
return 0;
}
int is_digit(char c)
{
if(c<'0'&&c>'9')
return 1;
else
return 0;
}
void update_array(int num[N][N])
{
char c;
int digit = 0;
int digits = 0;
int redIndex = 0;
int blueIndex = 0;
while (scanf("%c", &c) != EOF)
{
if (is_digit(c))
{
digits++;
digit = c -'0';
if (digits == 1)
redIndex = digit;
else if (digits == 2)
blueIndex = digit;
}
else
{
if (digits == 2)
{
(num[redIndex][blueIndex]++);
}
digits = 0;
}
}
int find_max(int b[N][N])
{
int max = b[0][0];
int x,y;
for (x = 0; x < N; x++)
{
for (y = 0; y < N; y++)
{
if (max < b[x][y])
{
max = b[x][y];
}
}
}
}
return max;
}
the code gives me incorect output , i chicked all of the functions and they are good ,exept for update_array function i think there is something icorrect, basicly this function chicks where there is two digit number and update the suatble place in array, so i can then use fin_max function and find the maximum..
plz anyhelp of why it gives me incorect values, i know i should use debugg but i never knew about this untill now and i don't have the time to learn this now and use it cause i need to submit this in a couple of hours !
In your code you do if (isdigit(c)), but isdigit is a different (standard library) function! You have to #include <ctype.h> to use it.
Using continue; outside loop is illegal.
You didn't declare nor define w.
A semicolon is missing after what seems calling of function w.
Try this because is_digit is not used:
void is_digit(char c)
{
(void)c; /* avoid warning for unused variable */
}
Note that this is invaiid because the return type is void:
void is_digit(char c)
{
return (c>'0'&&c<='9');
}
Don't forget to add #include <ctype.h> to use isdigit().
Also, replace
if (isdigit(c))
with
if (isdigit((unsigned char)c) && c != '0')
to avoid undefined behavior for passing out-of-range value and reject digit 0.
You've declared the function with the name is_digit() and later you are using it with the name isdigit().
So, after changing the above mentioned error, your code would look like
#include <stdio.h>
#include <stdlib.h>
#define N 9
int is_digit(char c);
void update_array(int num[N][N]);
int find_max(int b[N][N]);
int main()
{
int i,j;
int num[N][N];
int maximum=0,a=0,b=0;
for(i=0;i<N;++i)
{
for(j=0;j<N;++j)
{
num[i][j]=0;
}
}
update_array(num);
maximum=find_max(num);
a=maximum/10;
b=maximum%10;
printf("The winner couple is: %d blue, 4%d red.",a,b);
return 0;
}
int is_digit(char c)
{
if(c<'0'&&c>'9')
return 1;
else if(c>'0'&&c<='9')
return 0;
}
void update_array(int num[N][N])
{
char c;
int digit = 0;
int digits = 0;
int redIndex = 0;
int blueIndex = 0;
while (scanf("%c", &c) != EOF)
{ // <= while started
if (is_digit(c))
{ // <= if started
digits++;
digit = c -'0';
if (digits == 1)
redIndex = digit;
else if (digits == 2)
blueIndex = digit;
} // <= If ended
else
{ // <= else started
if (digits == 2)
{
(num[redIndex][blueIndex]++);
}
digits = 0;
} // <= else ended
} // <= while ended
//where is the function ending?
} //hence another curly braces needed.
int find_max(int b[N][N])
{
int max = b[0][0];
int x,y;
for (x = 0; x < N; x++)
{
for (y = 0; y < N; y++)
{
if (max < b[x][y])
{
max = b[x][y];
}
}
}
return max;
}
Related
I'm very new to C and trying to create a counter for how many times the letter "a" appears in a string. I get it working by putting it directly into main, however when I put it into a function, my printf outputs 0.
#include <stdio.h>
#include <string.h>
#define STRING_LENGTH 50
void letter_counter(char input[STRING_LENGTH], int count, char letter ) {
int i;
for (i = 0; i < strlen(input); i++){
if (input[i] == letter) {
count++;
}
}
}
int main() {
int a1 = 0;
char a = 'a';
printf("Please write a word\n");
char input[STRING_LENGTH] = {0};
fgets(input,STRING_LENGTH,stdin);
input[strlen(input) - 1] = 0;
letter_counter(input, a1, a);
printf("%i\n", a1);
}
You are not returning the value of what you have counted. It looks like you think that a1 is going to contain the total, but it's not.
Your letter_counter function needs to return an int value, not void.
int letter_counter(char input[STRING_LENGTH], char letter ) {
int i;
int count = 0;
for (i = 0; i < strlen(input); i++){
if (input[i] == letter) {
count++;
}
return count;
}
Then you need to assign the return value of the function to a variable:
a1 = letter_counter(input, a);
I have to make a program in which I have to add the result of x dices with n faces plus or minus a constant(C). The input should be a string like this: "xDn+-C" (x, n and C must be a decimal number). For example: "4D5+6" or "6D9-5". The D just means "Dice".
I used a function to randomize the rolls but I don't know how to continue...
void initD6(void) {
srand((unsigned)time( NULL ) );
}
int D6(void) {
return ((rand()%6)+1);
}
int main(){
char Dice[4];
for(i=0; i<5; i++){
Dice[i] = D6();
return 0;
}
I don't know how should I take that input as a string and the adding or substracting, and also don't know what should I do next.
Add a struct:
struct rules
{
int dices;
int facesPerDice;
int offset;
};
Solve the dice problem:
int throwDice(int faces)
{
return (rand() % faces) + 1;
}
int playGame(struct rules rules)
{
int result = 0;
for (int i = 0; i < rules.dices; i++)
result += throwDice(rules.facesPerDice);
return result + rules.offset;
}
Solve the parsing problem:
/**
Converts a string to a unsigned int until an invalid character is found or a null character is found.
You should replace this with the function you normally use to convert a string to a integer.
*/
unsigned int stringToUInt(char *str)
{
unsigned int result = 0;
int charindex = 0;
char currentchar;
while ((currentchar = str[charindex++]) != '\0')
{
if (currentchar < '0' || currentchar > '9')
break;
result *= 10;
result += currentchar - '0';
}
return result;
}
/**
Reads a string and generates a struct rules based on it.
The string is expected to be given in the following format:
[uint]'D'[uint]['+' or '-'][uint]
where:
the first uint is the number of dices to roll
the second uint is the number of faces per dice
the third uint is the offset
Terminates the program if something goes wrong.
*/
struct rules parse(char *str)
{
struct rules result;
result.dices = stringToUInt(str);
while (*(str++) != 'D')
if (*str == '\0')
exit(1);
result.facesPerDice = stringToUInt(str);
while (*(str++) != '+' && *(str-1) != '-')
if (*str == '\0')
exit(1);
result.offset = stringToUInt(str);
result.offset *= (*(str-1) == '+' ? 1 : -1);
return result;
}
Put everything together:
int main(int argc, char *argv[])
{
srand(time(NULL));
char input[] = "3D6+9"; //You could use console input if you want
struct rules rules = parse(input);
int gameResult = playGame(rules);
printf("Game result: %d\n", gameResult);
return 0;
}
Assuming no errors in the input, a function which solves your task is:
int throw_dice(const char* s)
{
int num, sides, res;
sscanf(s,"%iD%i%i", &num, &sides, &res);
for (int i = 0; i < num; ++i) {
res += rand() % sides + 1;
}
return res;
}
For simple string parsing sscanf() is a pretty good function. For more complex tasks it's better to use a regular expression library.
As usual, don't relay on rand() for anything but the most simple dice games, with no money involved.
You can try it with the following full example:
#include <stdio.h>
int throw_dice(const char* s)
{
int num, sides, res;
sscanf(s,"%iD%i%i", &num, &sides, &res);
for (int i = 0; i < num; ++i) {
res += rand() % sides + 1;
}
return res;
}
void throw_multiple_times(const char* s, int times)
{
printf("%s: ", s);
for (int i = 0; i < times; ++i) {
printf("%i ", throw_dice(s));
}
printf("\n");
}
int main(void)
{
srand((unsigned)time(NULL));
const char* s;
throw_multiple_times("4D5+6", 100);
throw_multiple_times("6D9-5", 100);
return 0;
}
Test it here.
#include <stdio.h>
#include <string.h>
void mirror(char c[])
{
int l = strlen(c);
char s;
for (int i = 0; i < l/2;i++)
{
s = c[i];
c[i] = c[l-i-1];
c[l-i-1] = s;
}
}
void decimal_to_binary(unsigned int n,char binary_res[]){
char r = n%2;
unsigned int q = (n - r)/2;
int i = 0;
while (q != 0)
{
i++;
r = n%2;
q = (n - r)/2;
n = q;
printf("%d\n",q);
binary_res[i] = r+'0';
}
mirror(binary_res);
}
int main(){
int n = 34; char res[10];
printf("%d\n",n);
decimal_to_binary(n,res);
printf("%s\n",res);
return 0;
}
I wrote this code which is really simple and I wanted it to convert a decimal to a binary through some repeated divisions. But there is a problem I don't understand because if I remove the +'0' when I assign the rest to the ith value in the result array, it displays nothing when I call it printf but when I add the +'0' it adds some weird characters. But I think i cmes from the fact that it is not ascii encording but UTF-8 so 0 hasn't a value of 0 but of 48. But the 0 value is for a null string so '' but when I add it to the r with +'' it shows nothing !
I don't understand what I am doing wrong here but I think there is multiple things I do wrong.
Thanks in advance !
I see three bugs:
You use i++ too soon. You place the first bit at binary_res[1] when it should be placed at binary_res[0].
You don't add a terminating NUL to binary_res.
You don't modify the binary_res at all when the n parameter is zero.
I check this statement '(n%2)' with loop statement and I fill the array, then I use procedure mirror to reverse the string like this:
#include <stdio.h>
#include <string.h>
void mirror(char c[],int l);
void decimal_to_binary(unsigned int n,char binary_res[]);
int main()
{
int n = 40; char res[10];
printf("%d\n",n);
decimal_to_binary(n,res);
printf("The binary form of number %d is %s\n",n,res);
return 0;
}
void mirror(char c[],int l)
{
char s;
for (int i = 0; i < l/2;i++)
{
s = c[i];
c[i] = c[l-i-1];
c[l-i-1] = s;
}
}
void decimal_to_binary(unsigned int n,char binary_res[])
{
int i = 0;
while (n != 0)
{
switch(n%2)
{
case 1:
{
binary_res[i]='1';
i++;
}break;
case 0:
{
binary_res[i]='0';
i++;
}break;
}
n = n/2;
}
binary_res[i]='\0';
mirror(binary_res,i);
}
I keep getting the error message that my I have an undefined reference to the power function, but I'm not really sure where that is occurring or why my code is coming up with that error because I have used to power function before in this way. If anyone could help me figure out why it isn't working now I would really appreciate it.
#include "stdio.h"
#include "string.h" //Needed for strlen()
#include "math.h"
#define MAX_BITS 32
#define MAX_LENGTH 49
#define NUMBER_TWO 2
#define NUMBER_ONE 1
#define TERMINATOR '\0'
//Code to find the index of where the string ends
int last_index_of(char in_str[], char ch) {
for (int i = 0; i < MAX_LENGTH; i++) {
if(in_str[i] == ch) {
last_index_of == i;
}
}
return last_index_of;
}
//Code to find the start of the fractional aspect
void sub_string(char in_str[], char out_str[], int start, int end){
int i = 0;
while (i < 1) {
out_str[i] = in_str[start] + in_str[end-1];
i++;
}
}
int main()
{
//Declaration of variable
char input[MAX_LENGTH +1]; // +1 for '\0'
int number;
double exponent;
char output[MAX_BITS];
int fraction;
sub_string(input, output, 0, TERMINATOR);
//Input from the user
printf("Enter a floating point value in binary: ");
scanf("%s", input);
//Calculates the Decimal Part
for (int i = 0; i < last_index_of(input, TERMINATOR) ; i++) {
number = number + number + input[i];
}
printf("%d", number);
exponent = -1;
//Calculates the Fractional Part
for (int j = 0; j < last_index_of(input, TERMINATOR); j++) {
if (j == last_index_of) {
fraction = NUMBER_ONE/(pow(NUMBER_TWO, exponent));
printf("%d/n", fraction);
}
else {
fraction = NUMBER_ONE/(pow(NUMBER_TWO, exponent));
printf("%d + ", fraction);
exponent--;
}
}
return 0;
}
Some problems:
you need -lm option to linker to tell it where to find pow function
last_index_of is not correctly written, you use the function name as an internal variable, you can correct it this way:
//Code to find the index of where the string ends
int last_index_of(char in_str[], char ch) {
int ret = 0;
for (int i = 0; i < MAX_LENGTH; i++) {
if(in_str[i] == ch) {
ret = i;
}
}
return ret;
}
Note that you can replace your last_index_of() function by strlen()
as pointed in comment, sub_string() is not functionnal. A corrected version could be:
//Code to find the start of the fractional aspect
void sub_string(char in_str[], char out_str[], int start, int end){
int i = 0;
while (start != end) {
/* warning, bounds are still not tested...*/
out_str[i++] = in_str[start++];
}
out_str[i] = '\0'
}
Instead of calling last_index_of() in your exist for loop condition, you should take its value to re-use it:
for (int j = 0; j < last_index_of(input, TERMINATOR); j++) {
/* Error here: will never be TRUE */
if (j == last_index_of) {
/* ... */
}
else {
/* ... */
}
}
would become:
int last_index = last_index_of(input, TERMINATOR);
for (int j = 0; j < last_index; j++) {
if (j == last_index) {
/* ... */
}
else {
/* ... */
}
}
Another problem, you use number variable without initializing it, you should write int number = 0 instead of int number;
After that, there is also a problem with your logic.
You have some idea of what you want to do, but it is not clear in your code.
It seems that you want
the user to input some string in the form 10010.100111
to split this string into two parts 10010 and 100111
to convert the first part into integer part 10010 -> 18
to convert the second part into fractional part 100111 -> 0.609...
This decomposition may lead you to write this kind of code:
#include "stdio.h"
#include "string.h"
#define MAX_BITS 32
#define MAX_LENGTH 49
//Code to find the index of where the string ends
int last_index_of(char in_str[], char ch)
{
int ret = 0;
for (int i = 0; i < MAX_LENGTH; i++) {
if (in_str[i] == ch) {
ret = i;
}
}
return ret;
}
void sub_string(char in_str[], char out_str[], int start, int end)
{
int i = 0;
while (start != end) {
/* warning, bounds are still not tested... */
out_str[i++] = in_str[start++];
}
out_str[i] = '\0';
}
void split(char *input, char *first, char *second)
{
int idx = last_index_of(input, '.');
sub_string(input, first, 0, idx);
sub_string(input, second, idx + 1, strlen(input));
}
int main()
{
//Declaration of variable
char input[MAX_LENGTH + 1]; // +1 for '\0'
char first[MAX_BITS];
char second[MAX_BITS];
/* Input from the user */
printf("Enter a floating point value in binary: ");
scanf("%s", input);
/* split integer and fractionnal parts */
split(input, first, second);
/* decode integer part */
printf("integer part:\n");
for (int i = strlen(first) - 1, j = 1; i > -1; --i, j <<= 1) {
if (first[i] == '1') {
printf("%d ", j);
}
}
/* decode frac part */
printf("\nfractionnal part:\n");
for (int i = 0; i < strlen(second); ++i) {
if (second[i] == '1') {
printf("1/%d ", 2 << i);
}
}
return 0;
}
Whenever I run my program, I think that I am getting the wrong output using the included test strings, though I think my first function is working. Tthe files I have are xbits.c xbits.h and two versions of showxbits.c, one that is instructor provided and the other is the one I am trying to use scanf with. The program is supposed to convert an integer to a hex string and then a hex string to an integer. My main problem is, while I think that my code works with the instructor test input, I know it doesn't work with the scanf showxbits because it gives answers such as 0xS when 127 is inputed.
Here is the xbits.c
#include <stdio.h>
#include <math.h>
int hex_To_dec(int c) {
char hex_values[] = "aAbBcCdDeEfF";
int i;
int answer = 0;
for (i=0; answer == 0 && hex_values[i] != '\0'; i++) {
if (hex_values[i] == c) {
answer = 10 + (i/2);
}
}
return answer;
}
/* function represents the int n as a hexstring which it places in the
hexstring array */
void itox(char* s, int n)
{
char *digits = "0123456789ABCDEF";
int i=0,j;
char temp;
while(n > 0)
{
s[i] = digits[n % 16];
n /= 16;
i++;
}
s[i] = '\0'; // Add null terminator
i--;
// Now reverse it in place
for(j=0; j < i / 2; j++)
{
temp = s[j];
s[j] = s[i - j];
s[i - j] = temp;
}
}
/* function converts hexstring array to equivalent integer value */
int xtoi(char hexstring[]) {
//printf("in xtoi, processing %s\n", hexstring);
int answer = 0;
int i = 0;
int valid = 1;
int hexit;
if (hexstring[i] == '0') {
++i;
if (hexstring[i] == 'x' || hexstring[i] == 'X') {
++i;
}
}
while(valid && hexstring[i] != '\0') {
answer = answer * 16;
if(hexstring[i] >='0' && hexstring[i] <= '9') {
answer = answer + (hexstring[i] - '0');
}
else {
hexit = hex_To_dec(hexstring[i]);
if (hexit == 0) {
valid = 0;
}
else {
answer = answer + hexit;
}
}
++i;
}
if(!valid) {
answer = 0;
}
return answer;
}
Here is the showxbits.c provided by the instructor:
/*
* stub driver for functions to study integer-hex conversions
*
*/
#include <stdio.h>
#include <string.h>
#include "xbits.h"
#define ENOUGH_SPACE 1000 /* not really enough space */
int main() {
char hexstring[ENOUGH_SPACE];
int m=0, n = 0x79FEB220;
itox(hexstring, n);
/* for stub testing: create a fake input string */
strcpy(hexstring, "6BCD7890");
m = xtoi(hexstring);
printf("\t%12d %s %12d\n", n, hexstring, m);
return 0; /* everything is just fine */
}
And here is the showxbits that has scanf in it:
/*
* stub driver for functions to study integer-hex conversions
*
*/
#include <stdio.h>
#include <string.h>
#include "xbits.h"
#define ENOUGH_SPACE 100 /* not really enough space */
int main() {
char hexstring[ENOUGH_SPACE];
//int m=0, n = 0x79FEB220;
int n, m;
while ((scanf("%d", &n)) == 1) {
itox(hexstring, n);
m = xtoi( hexstring);
printf("%12d %s %12d\n", n, hexstring, m);
}
return 0; /* everything is just fine */
}
Like I said, I am getting weird outputs when using the scanf function. I am a complete beginner programmer and would really appreciate any help that can be offered. Thanks!
Because there is a mistake in the function itox , which would cause the wrong result when reverse string. Then, the wrong hexstring from itox will result in the abnormal output finally.
The quick fix is to replace j < i / 2 with j < i / 2 + 1
void itox(char* s, int n)
{
//......
// Now reverse it in place
for(j=0; j < i / 2 + 1 ; j++)
{
temp = s[j];
s[j] = s[i - j];
s[i - j] = temp;
}
}
You don't need to reverse the string to convert to hex ascii:
#include <stdio.h>
const char* hexlat="0123456789ABCDEF";
char *binaryToHex(unsigned int answer, char *result){
if(answer==0) return result;
else{
result=binaryToHex(answer>>4,result);
*result=hexlat[answer & 0x0F];
return result+1;
}
};
int main(void) {
unsigned int answer=0x12340ADF;
char hexAnswer[32];
*binaryToHex(answer,hexAnswer)='\0';
printf("%s",hexAnswer);
return 0;
}