C Language Single char declaration error after char array - arrays

There seems to be an overflow phenomenon depending on the declaration of n before and the declaration of n after Can you tell me the detailed reason?
Operable code
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, sum=0;
char n, DNA[11]={};
printf("용의자의 DNA정보를 입력하세요. :");
scanf("%s", DNA);
for(i=0; i<10; i++)
{
n = DNA[i];
sum += atoi(&n);
}
if (sum%7 == 4)
printf("범인");
else
printf("일반인");
}
Inoperable code
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, sum=0;
char DNA[11]={}, n;
printf("용의자의 DNA정보를 입력하세요. :");
scanf("%s", DNA);
for(i=0; i<10; i++)
{
n = DNA[i];
sum += atoi(&n);
}
if (sum%7 == 4)
printf("범인");
else
printf("일반인");
*Input conditions are up to 10 characters

The both programs have undefined behavior.
For starters you may not use empty braces to initialize an array in C (opposite to C++).
char n, DNA[11]={};
Secondly, the function atoi expects a pointer to a string. However you are using a single character n
sum += atoi(&n);
If you want for example to add digits of the entered number then write
for(i=0; DNA[i] != '\0'; i++)
{
n = DNA[i];
sum += n - '0';
}
Also you need guarantee that the length of the entered string is not greater than 10
scanf("%10s", DNA);

Related

Why is my array saving and printing not the chars?

I want to print random chars and save them all in one array.
But the problem is, the array saves something - but not the chars printed/generated before.
Does anybody know how to fix this?
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
char get_symbol(int m);
int main()
{
srand(time(NULL));
char array[1][5];
char y;
int i;
for(i=0; i<5; i++){
y = get_symbol(rand()%3);
printf("%c", sym);
y = array[i];
}
printf("\n\n");
for(i=0; i<5; i++){
printf("%s", array[i]);
}
}
char get_symbol(int m){
char s;
switch(m){
case 0: s = 'A'; break;
case 1: s = 'B'; break;
case 2: s = 'C'; break;
default: break;
}
return s;
}
You probably want this, explanations are in the comments:
int main()
{
srand(time(NULL));
char array[5]; // you just want an array of 5 chars
char y;
int i;
for (i = 0; i < 5; i++) {
y = get_symbol(rand() % 3);
printf("%c", y); // sym is unknown, you probably wanted to print y
array[i] = y; // you have reversed the assignment
}
printf("\n\n");
for (i = 0; i < 5; i++) {
printf("%c", array[i]); // use %c here, you want to print 5 single chars
} // not 5 strings
fflush(stdout); // flush output buffer. maybe not necessary
}
Bonus:
Your get_symbol function is overly complicated: this does exactly the same:
char get_symbol(int m) {
return 'A' + m % 3;
}
It also does the modulo operation inside the function because (at least in your original function) calling get_symbol with values out side the interval [0..2] will lead to undefined behaviour.

Finding the factorial of odd number from the input value in C

#include <stdio.h>
int main()
{
int input;
int result = 1;
printf("Enter the integer number : ");
scanf("%d", &input);
printf("n:!\n\n");
for(int i = 1; i <= input; i = i + 2)
{
for(int k = 1; k <= i; k++)
{
result *= k;
}
printf("%d:%d\n", i, result);
}
return 0;
}
I have created such code to determine the factorial of input's odd number. During the testing, I have found out that beyond the factorial of 5, the value gets wrong. Seems like the calculation is going wrong but I don't know what is the problem in my code.
your problem is you are multiplying result with the old value it has in each inner loop. to solve this before the start of inner loop reset result to 1 by :
result = 1;
and this is not related to the question but I prefer to avoid this algorithm as it is O(n^2 /2) we can consider it O(n^2), rather you can use this one it is O(n) :
#include <stdio.h>
int main()
{
int input;
long double result = 1;
printf("Enter the integer number : ");
scanf("%d", &input);
printf("n:!\n\n");
for(int i = 1; i <= input; i++)
{
result *= i;
if(i%2==1){ printf("%d:%Le\n", i, result); } //note that im using %Le for long double type
}
also be careful with int type you are using for result, int is limited you should use long double because fact operation's result will be big
Firstly, it's probably best not to use scanf for ill defined data such as user input. In fact, the rule "don't use scanf" very often valid. A program such as this might be better off using a command line argument instead.
Technically in C main should be int main(void) or some variation of int main(int argc, char *argv[].
As others have mentioned, it would be more reasonable to use unsigned integers for a calculation like this where negative numbers are impossible. For something like a factorial it would make sense to use a larger integer type too.
Anyway, on topic: why don't you do it more simply? The factorial function can be iterated in one loop. If you only want to print the result when i is odd, just check whether it's odd.
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
static unsigned get_input(void);
static unsigned interpret_string(const char *str);
int
main(int argc, char *argv[])
{
unsigned input;
uint64_t result = 1;
if (argc == 1) {
printf("Enter the integer number : ");
input = get_input();
putchar('\n');
} else {
input = interpret_string(argv[1]);
}
for (unsigned i = 1; i <= input; ++i) {
result *= i;
if (i & 1)
printf("%-2d = %"PRIu64"\n", (int)i, result);
}
return 0;
}
static unsigned
interpret_string(const char *str)
{
char *endp = NULL;
unsigned ret = strtoll(str, &endp, 10);
if (endp == str) {
fprintf(stderr, "Invalid input \"%s\"\n", str);
exit(1);
}
return ret;
}
static unsigned
get_input(void)
{
char buf[1024];
fgets(buf, 1024, stdin);
return interpret_string(buf);
}

Can I put a for loop inside scanf?

I want to have unknown amount of inputs in a single line. For example, user can input:
"ans: 1 2 3 4 5"
and scanf() will store these five numbers to an array. The problem is that the program don't know how many input will there be.
#include <stdio.h>
int main()
{
int i;
int input[4];
scanf("ans: " for(i = 0, i < 3,i++){scanf(" %d", &input[i]);};
return 0;
}
Sorry I'am totally new to coding, what will be the proper way to write this? Or is this impossible?
Thanks :)
Use fgets() and sscanf() with "%n"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char input[100];
int arr[10];
//fgets(input, sizeof input, stdin);
strcpy(input, "1 2 42 56 -3 0 2018\n"); // fgets
char *pi = input;
int tmp, pp, i = 0;
while (sscanf(pi, "%d%n", &tmp, &pp) == 1) {
if (i == 10) { fprintf(stderr, "array too small\n"); exit(EXIT_FAILURE); }
pi += pp;
arr[i++] = tmp;
}
printf("got this ==>");
for (int k = 0; k < i; k++) printf(" %d", arr[k]);
puts("");
}
You asked this question way round.
You can achieve what you expect by putting scanf inside of a loop.Even you can ask user to give how many inputs he want to enter.
#include <stdio.h>
int main()
{
int i;
int input[4];
printf("Enter the number of inputs you want to give : ");
scanf("%d", &n);
for(i = 0; i < n;i++)
{
printf("Enter the input number %d : ",i);
scanf("%d", &input[i]);
}
return 0;
}

How to replace a character at random in a string?

I've printed a string of "+" symbols based on two given values(N, M). Now I'm trying to figure out how to replace characters at random in said string based on a third given value(K). The characters are stored in a string(l). I think I have to use the replace function but I don't know how(hence why it's in a comment for now). Any help is appreciated.
#include <stdio.h>
unsigned int randaux()
{
static long seed=1;
return(((seed = seed * 214013L + 2531011L) >> 16) & 0x7fff);
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
char s[1000];
int N, M, K, l;
printf("N: ");
scanf("%d",&N);
printf("M: ");
scanf("%d",&M);
printf("K: ");
scanf("%d",&K);
printf("\n");
gets(s);
l=strlen(s);
/* Mostre um tabuleiro de N linhas e M colunas */
if(N*M<K){
printf("Not enough room.");
}else if(N>40){
printf("Min size 1, max size 40.");
}else if(M>40){
printf("Min size 1, max size 40.");
}else{
for(int i=0; i<N; i++)
{
for(int j=0; j<M; j++)
{
printf("+", s[j]);
}
printf("\n", s[i]);
}
for(int l=0; l<K; l++)
{
/*s.replace();*/
}
}
return 0;
}
There is too much unexplained complexity and unknowns in your program to enable a corrective answer. But this shows how to replace a textual string's character at random, with a numeral.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int main(void)
{
char str[] = "----------";
int len = strlen(str);
int index;
int num;
srand((unsigned)time(NULL)); // randomise once only in the program
printf("%s\n", str); // original string
index = rand() % len; // get random index to replace, in length range
num = '0' + rand() % 10; // get random number, in decimal digit range
str[index] = num; // overwrite string character
printf("%s\n", str); // altered string
return 0;
}
Program sessions:
----------
-3--------
----------
-----0----
----------
--------6-
Arguably it would be better to use size_t types, but for the limited range of the example, will suffice.

C : Array of strings - Can input only n-1 strings for an input size of n

I have to sort strings in a lexicographical order using the Bubble Sort technique without using any library functions. I have written the following code which is working fine in sorting the strings.
But the problem is that if I give n as the input (say n = 4), I can enter only n-1 strings (only 3 strings).
The problem can be solved by running the for loops from 0 to n, but that isn't a logical solution.
What am I doing wrong here?
#include <stdio.h>
#include <string.h>
#include <malloc.h>
void swap(int indx[], int j)
{
int temp;
temp = indx[j];
indx[j] = indx[j+1];
indx[j+1] = temp;
}
void sort(char **str, int indx[], int n)
{
int i, j, k;
for(i=0; i<n; i++)
{
for(j=0; j<n-i-1; j++)
{
k = 0;
while(str[j][k] != '\0')
{
if((str[indx[j]][k]) > (str[indx[j+1]][k]))
{
swap(indx, j);
break;
}
else if((str[indx[j]][k]) < (str[indx[j+1]][k]))
break;
else
k++;
}
}
}
}
void display(char **str, int indx[], int n)
{
int i;
printf("Sorted strings : ");
for(i=0; i<n; i++)
printf("%s\n", str[indx[i]]);
}
int main(void)
{
char **str;
int n, i, j, *indx;
printf("Enter no. of strings : ");
scanf("%d", &n);
str = (char **) malloc (n * (sizeof(char *)));
indx = (int *) malloc (n * sizeof(int));
for(i=0; i<n; i++)
str[i] = (char *)malloc(10 * sizeof(char));
printf("Enter the strings : ");
for(i=0; i<n; i++)
{
gets(str[i]);
indx[i] = i;
}
sort(str, indx, n);
display(str, indx, n);
}
The problem is your use of scanf(). When you do scanf("%d", &n), the scanf() function reads input until it finds an integer, and puts the value into n. However, when you entered that integer, you didn't just type '4', you typed '4' and pressed Enter. And the newline is still in the input buffer. The gets() function, on the other hand, reads input up to and including the first newline, and the newline character is discarded. So when you're reading the input strings, the gets call to gets() reads the newline, and returns immediately. And then, the first string that you enter is read by the second call to gets()...
Incidentally, The gets() function should never, ever, under any circumstances, ever be used for real programs, because it doesn't allow you to limit input. Better would be to use fgets(). fgets(str[i], BUFFERSIZE-1, stdin).
int main(void)
{
char **str;
int n=4, i, j, *indx;
printf("Enter no. of strings : ");
//scanf("%d", &n);
str = (char **) malloc (n * (sizeof(char *)));
indx = (int *) malloc (n * sizeof(int));
for(i=0; i<n; i++)
str[i] = (char *)malloc(10 * sizeof(char));
printf("Enter the strings : ");
for(i=0; i<n; i++)
{
gets(str[i]);
indx[i] = i;
}
sort(str, indx, n);
display(str, indx, n);
}
//if i comment out scanf and give int the value it works fine //
so the problem is use of fgets just after scanf as scanf leave a newline character in the buffer// so consume it before using fgets
Try this at the line where you have to input the string. Instead of:
gets(str[i]);
type:
scanf("%s",str[i]);

Resources