How to concat integer and string inside recursive function in C - c

guys, I want to make a program to generate all combination elements. for example if user input (n) = 3, so the output must be like this :
1
12
123
13
2
23
3
I have a problem to concat integer and string inside recursive function..
Code :
#include <stdio.h>
void rekursif(int m, int n, char angka[100]){
int i;
for(i=m; i<=n; i++){
sprintf(angka, "%s %d", angka, i);
printf("%s \n", angka);
rekursif(i+1,n,angka);
}
}
int main(){
rekursif(1,5,"");
return 0;
}
when I run the program, command prompt is not responding. I guess, the problem is in concation ( sprintf(angka, "%s %d", angka, i); )
please help me to solve this problem. thank you :)

By passing "" as the function argument, you are trying to modify a string literal, which is undefined behavior. Instead, do:
int main(){
char str[100];
rekursif(1, 5, str);
return 0;
}
Be careful with buffer overflow in practice.

Related

Why am I getting a character in output when my input is 5 or more than 5? It is pure mathematical equation. If anything is wrong please tell me

I have compiled this code and it works just fine up to value 4 then it starts returning character instead of integer. I am talking about first equation => x= num*2; Here when I enter num value as 5 the output returns a.
#include <stdio.h>
int main(void)
{
int num;
int x; This right here is an integer still it returns a character
char s[10] = "helloworld";
char f[10];
scanf("%d", &num); //
//printf("%d\n", num);
x = num * 2 ;
printf("%x\n", x);
scanf("%c", &f[10]);
if(s[10] = f[10]){
printf("helloworld");
}
}
please tell me if there is a mistake I am a newbie to coding.
As I see you are learning C language, and after reading your explanation, I feel that you want to print the integer value of variable x.
Kindly replace %x with %d in the print statement of variable x,
and you will be successfully able to print the value.
#include <stdio.h>
int main(void)
{
int num;
int x; // This right here is an integer still it returns a character
char s[10] = "helloworld";
char f[10];
scanf("%d", &num);
x = num * 2 ;
printf("%d\n", x); // %d for integer and %x for hexadecimal values
scanf("%c", &f[10]);
if(s[10] = f[10]){
printf("helloworld");
}
return 0;
}
Finally, do read more about format specifiers in scanf and
printf statements.

C for loop iteration

I have a problem writing code which does the following: declare a struct{char c; int x; } array and load it with scanf via a loop. After it's loaded, a call to function f will be made which will replace every occurrence of digits in the struct's component c with 0, and will return the sum of the digits replaced by zero.
Code and output are below and I have problem that the loop in the function f seems to iterate one time, and it gives out some really weird values.
This is an exam question so I have to use printf, scanf etc. Also I have that exam in an hour so any quick help is appreciated :)
CODE:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX 2
struct par {
char c;
int x;
};
int f(struct par *niz) {
int i;
int n=0;
for(i=0; i<MAX; i++) {
if(isdigit(niz[i].c)) {
niz[i].c = niz[i].c-'0';
printf("niz[i].c = %d\n i = %d", niz[i].c, i);
n=n+niz[i].c;
niz[i].c='0';
}
}
return n;
}
void main() {
int n;
int i;
struct par niz[MAX];
printf("enter\n");
for(i=0; i<MAX; i++) {
scanf("%c", &niz[i].c);
scanf("%d", &niz[i].x);
}
n=f(niz);
for(int i=0; i<MAX; i++) {
printf("%d\n", niz[i].c);
printf("%d\n", niz[i].x);
}
printf("n = %d\n", n);
}
OUTPUT:
enter
2
2
2
niz[i].c = 2
i = 048
2
10
2
n = 2
When you press enter after the first input, the newline is not scanned by scanf and is left in the input buffer. When you then try to read the number scanf sees the newline and not a number so doesn't scan anything.
The simple solution to that is to add a leading space in front of the formats:
scanf(" %c", &niz[i].c);
scanf(" %d", &niz[i].x);
/* ^ */
This tells scanf to skip whitespace.
Use
niz[i].c = getchar();
instead of
scanf("%c", &niz[i].c);
or, you can use other better methods for getting char input discussed at SO,
Now,
You see second time you provided input only once, that is because the Enter you pressed after giving 2 as input to first char remained in input buffer, and was read on second iteration.
You are getting 10 as output, because, it is ASCII for \r, the Enter. It is not a digit, so not replaced to be '0'.
I am looking at your code (i am not using console for a decade, but ) here are some insights:
try to rename MAX with something else
do not know your IDE but sometimes MAX is reserved
and using it as macro can cause problems on some compilers
change scanf("%c", &niz[i].c) to scanf("%c", &(niz[i].c))
just to be shore that correct adsress is send to scanf
change scanf("%d", &niz[i].x) to scanf("%i", &(niz[i].x))
change "%d" to the correct value (this is main your problem)
"%c" for char
"%i" for int
Try to trace line by line and watch for improper variables change if above points does not help
weird values?
because you forgot "\n" after the line, so next print is behind the line "i = %d".
And, check return value of every function except ones that return void.

Two Dimensional Array of Characters in C

Help me to get out of this problem. I'm using GCC on ubuntu12.04. While I write this program to get 5 strings from keyboard n then print these strings on screen. Program is compiled but during execution it takes strings from keyboard but print only last string. The program which I have written is below:
void main()
{
char names[10];
int i,j;
for(i=0;i<5;i++)
{
printf(" Enter a name which you want to register\n");
scanf("%s",names);
}
for(i=0;i<5;i++)
printf(" the names you enter are %s\n", names);
}
1) you can use 2D char array in this way
char names[5][100];
each line in the 2D array is an array of char with size = 100
for(i=0;i<5;i++)
{
printf(" Enter a name which you want to register\n");
scanf("%99s",names[i]);
}
2) You can use array of pointers in this way
char *names[5];
each element in the array is a pointer to a string (char array). you have to assign each pointer in the array to a memory space before you call scanf()
for(i=0;i<5;i++)
{
names[i]=malloc(100);
printf(" Enter a name which you want to register\n");
scanf("%99s",names[i]);
}
3) if you compile with gcc version >2.7 then your scanf() can allocate memory by using "%ms" instead of "%s"
char *names[5];
for(i=0;i<5;i++)
{
printf(" Enter a name which you want to register\n");
scanf("%ms",&names[i]);
}
There is a simple example about reading and keeping string in the char array.
#include <stdio.h>
const int MACRO = 6;
int main() {
printf("Hello Admin Please Enter the Items:\n");
char items[MACRO][20];
for (int i = 0; i < MACRO; ++i) {
scanf("%19s", items[i]);
}
for (int i = 0; i < MACRO; ++i) {
printf("%s ", items[i]);
}
return 0;
}
In your program the mistake is that you have not putted '&'address of operator int the first for loop . names in your case is an array if you store %s string in names and not &names[0] or &names[1] or so on then as array itself acts as a pointer therefore the array "names" is pointing to the address of its first elements i.e. names[0] . so if you are writing scanf("%s",names); that is similar to scanf("%s",&names[0]); so as you are storing the names in one element only and that too for 5 iterations for only the last string you have entered will be stored and previous strings will be gone . so onlye last string is printed in your program .
in your code, you only declare char data type to be one dimensional and thus it will always overwrite the previous input,that's why the result is the last input printed 5 times.
char names[10];
the above declaration means that you declare a char type variable only with 10 character size without an extra array,it means you only declare a single variable for 5 input.
to make a two dimensional char, you will need to declare it like this :
char names[5][10];
in the code above, it means that you declare a char type variable with 10 character size in an array of 5.
Here is the code I wrote using pointer.
#include <stdio.h>
void main()
{
char *string[100];
int ln;
printf("Enter numbar of lines: ");
scanf("%d",&ln);
printf("\n");
for(int x=0;x<ln;x++)
{
printf("Enter line no - %d ",(x+1));
scanf("%ms",&string[x]); // I am using gcc to compile file, that's why using %ms to allocate memory.
}
printf("\n\n");
for(int x=0;x<ln;x++)
{
printf("Line No %d - %s \n",(x+1),string[x]);
}
}
Another code using two dimensional Array
#include <stdio.h>
void main()
{
int ln;
printf("Enter numbar of lines: ");
scanf("%d",&ln);
printf("\n");
char string[ln][10];
for(int x=0;x<ln;x++){
printf("Enter line no - %d ",(x+1));
scanf("%s",&string[x][0]);
}
for(int x=0;x<ln;x++)
{
printf("Line No %d - %s \n",(x+1),string[x]);
}
}

segmentation fault while passing local array`s element as pass-by-value to another function

#include<stdio.h>
void gradescounter(int[], int);
int main(void){
int indexnum;
int grade[indexnum];
/* processing phase */
printf( "Please enter the index number: ");
scanf( "%d", &indexnum);
gradescounter(grade[indexnum], indexnum);
}
When I enter the number, I encounter the segmentation fault error. Could somebody tell me where I was wrong? Also, when I used gcc to compile, there is a warning that passing argument 1 of 'gradescounter' makes pointer from integer without a cast, why is it? Thank you for everyone could help
indexnum isn't initialized when you use it to create the grade array. You should probably use a known value there instead.
You are passing an int to a function that expects int[] (which is just syntactic sugar for int *). That's the problem - either pass grade, or change the function to take just int, whichever is correct.
main should probably have a return statement somewhere.
I agree with Carl Norum
See the code below
#include <stdio.h>
void gradescounter(int*, int);
int main(void){
int indexnum;
int grade[]={1,2,3,4,5,6,7,8,9};
/* processing phase */
printf( "Please enter the index number: ");
scanf( "%d", &indexnum);
gradescounter(grade, indexnum);
return 0;
}
void gradescounter(int *array, int index){
if(index > -1 && index < 9)
printf("The number entered is : %d\n",array[index]);
else
printf("Please enter the index number in the range of 0 and 8\n");
}

C program crashes on printing array

I am learning C at the moment, and am trying to build a simple interpreter. It takes one character and one number. The program below only uses 'r' for the char. The 'r' stands for the range (of the natural numbers) and the digit after it specifies the length of the range.
Example Execution:
Enter:
r 9
0 1 2 3 4 5 6 7 8
What happens instead:
Enter:
r 9
And here the program crashes. So I believe the error lies in the printing of the array.
The code in question is here:
#include <stdio.h>
#include <stdlib.h>
int* range(int i) {
int *a=(int*) malloc(i * sizeof(int));
int j;
for(j=0;j<i;j++)
a[j]=j;
return a;
}
void printArray(int a[], int length) {
int i;
printf("\n");
for(i=0;i<length;i++)
printf("%d ", a[i]);
}
int main() {
char c;
int n = 1;
while(n>=0){
printf("\nEnter:\n\t");
scanf("%c %d", c, n);
if(c='r')
printArray(range(n), n);
}
return 0;
}
So what is causing the program to crash?
Your arguments to scanf are wrong, you need
scanf("%c %d",&c, &n);
Your fundamental problem here is that you have no evidence about where the crash is happening, as it happens I bet it's in scanf().
I recommend you adopt two debugging techniques:
a). Add print statements in your code so you know what's happening
b). Use an interactive debugger so you can step through and see what's going on.

Resources