I have an assignment to write code that printing all combinations of N char. For example, if the input is 3, the expected output must be "aaa aab aac aba ... ccc". But my code looping over and over again. Here's my code.
#include <stdio.h>
#ifndef MAX
#define MAX 5
#endif
void comb(char kar[], int size, int index) {
// string = aaa
// lim = 'd'
char lim = 'a' + size;
while (index != -1) {
if (kar[size-1] != lim) { // != c
for (int i = 0; i < size; i++) {
printf("%s ", kar);
kar[size-1]+=1;
}
return comb(kar, size, index);
} else {
while (kar[index-1] == lim && index != -1) {
kar[index-1]='a';
index--;
}
kar[index-1] += 1;
return comb(kar, size, size);
}
}
}
int main(int argc, char const *argv[]) {
int n;
char kar[MAX];
printf("Input N char : ");
scanf(" %d", &n);
for (int j = 0; j < n; j++) {
kar[j] = 'a';
}
comb(kar, n, n);
return 0;
}
I'm a little bit confused and I have no idea where is the mistake. Thank you.
The problem has been solved. I changed some elements in the comb() and added the pow() function to define the recursion limit.
int comb(char kar[], int size, int index, int limit) {
char lim = 97 + size;
int limit_value = pow(size,size);
if(limit == limit_value){
return 1;
} else {
if (index < size-1) {
printf("%s ", kar);
kar[size-1]+=1;
return comb(kar, size, index+1, limit+1);
} else {
int cek = index;
printf("%s ", kar);
while (kar[cek] == lim-1 ) {
kar[cek]=97;
cek-=1;
}
kar[cek] += 1;
return comb(kar, size, 0, limit+1);
}
}
}
Related
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;
}
Hey I'm trying to figure out why the following code gets invalid write of size error from Valgrind at the line: array[i-1] = I;
I really don't now why my allocate_array function doesn't work. I tried so many things.
There are couple errors more but I just wanted to check first why this line is false or why my array isn't allocated.
Hope you can help me to figure out my error.
#include<stdio.h>
#include<stdlib.h>
//Programm to check Gaussian function
int read_number_from_stdin(int* value) {
printf("Number for the Gaussian Function: ");
int return_value = scanf("%d", value);
if (return_value == 0) {
while (fgetc(stdin) != '\n')
;
}
if (return_value == EOF) {
return_value = 0;
}
return return_value;
}
int read_number_from_string(char* string, int* value) {
printf("Reading input...\n");
int return_value = sscanf(string, "%d", value);
if (return_value == 0 || return_value == EOF) {
printf("\t... Error your input is not a Number!\n");
return_value = 0;
} else {
printf("\t... Number %d read and saved.\n", *value);
}
return return_value;
}
int* allocate_array(int* size) //allocating memory for the array
{
int* result = (int*) malloc(sizeof(int) * (*size));
return result;
}
void initialize_array(int array[], int size) {
for (int i = 0; i < size; i++) {
array[i] = i+1;
}
}
int compute_sum_and_place_in_first_elem(int array[], int* size) {
int sum_array = 0;
for (int i = 0; i < *size; i++) {
sum_array += array[i];
}
return sum_array;
}
void free_memory(int array[], int* N) {
free(array);
free(N);
}
int main(int argc, char* argv[]) {
int* N = malloc(sizeof(int));
if (argc == 1) {
while (read_number_from_stdin(N) != 1)
;
} else if (argc == 2) {
if (read_number_from_string(argv[1], N) == 0) {
printf("Error: No valid number!\n", argv[1]);
return -1;
}
} else {
printf("No valid number!\n");
return -1;
}
int* array = allocate_array(N); //allocate via function
initialize_array(array, *N); //initialize the array up to n
int result = compute_sum_and_place_in_first_elem(array, N);
int result_gauss = ((*N + 1) * (*N) / 2);
if (result == result_gauss) {
printf("Gauss was right your calculations match with his function");
} else {
printf(
"\nGauss was not right!\n"
"The summ of %d is %d and therefore not equal to(%d+1)*%d/2\n\n",
*N, result, *N, *N);
}
//free memory
free_memory(array, N);
}
As I can see, for the initialize_array() function, for the for loop, very first iteration, i is 0, and you're executing
array[i-1] = i;
which translates to
array [-1] = ....
which is illegal.
You can fix that using the default C-array property of 0-based indexing scheme. Something like
for(int i = 0; i < size; ++i)
{
array[i] = i;
}
I am trying to make permutations of strings with up to 8 characters. The problem is it must be done with recursion and it must be in lexicographical order. I found one solution with the recursion but it only works for 4 characters max. After that, it starts to mess up again.
void swap(char* a, char* b){
char temp = *a;
*a = *b;
*b = temp;
}
void recursion(char* arr, int start, int n){
if (start == (n-1)){
printf("%s\n", arr);
return;
}
for (int i = start; i < n; i++){
recursion(arr, start+1, n);
swap(arr+start+1, arr+n-1);
int j = start+1;
while (j < n && arr[start] > arr[j]){
j++;
}
if (j >= n){
continue;
}
swap(arr+start, arr+j);
}
swap(arr+start+1, arr+n-1);
}
int main(int argc, char *argv[]) {
char arr[9];
char charakter;
int m = 0;
while (scanf("%c", &charakter) != EOF){
if (charakter == '\n'){
break;
}
else if (isalpha(charakter) || isdigit(charakter)){
arr[m] = charakter;
m++;
}
else{
fprintf(stderr, "Error!\n");
return 100;
}
}
arr[m] = '\0';
int n = strlen(arr);
int start = 0;
recursion(arr, start, n);
return 0;
}
Any idea how to fix the recursion function?
Your solution is strange, have a look here and here a fix:
void recursion(char *arr, int start, int n) {
if (start == n) {
printf("%s\n", arr);
return;
}
for (int i = start; i < n; i++) {
swap(arr + start, arr + i);
recursion(arr, start + 1, n);
swap(arr + start, arr + i);
}
}
here a proper solution:
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
static void recursion(char *str, size_t n, size_t max) {
if (n < max) {
recursion(str, n + 1, max);
for (size_t i = n + 1; i < max; i++) {
char tmp = str[i];
str[i] = str[n];
str[n] = tmp;
recursion(str, n + 1, max);
str[n] = str[i];
str[i] = tmp;
}
} else {
printf("%s\n", str);
}
}
int main(void) {
char str[42];
errno = 0;
if (scanf("%41s", str) != 1) {
if (errno != 0) {
perror("scanf()");
} else {
fprintf(stderr, "no input");
}
return 1;
}
recursion(str, 0, strlen(str));
}
I have char* pointer and trying to count the length of each word. but I am not getting any result in debugger (just empty space). whatever I change , I dont get any result. the code :
void wordsLen(char* text, int* words, int n)
{
int i, count = 0, s = 0;
//words[countWords(text)]; // not important
for (i=0; i < n; i++)
{
if (text[i] != ' ')
{
count++;
}
else
{
printf("%d",count);
}
printf("%d",count);//if I add this it types the count from 1 to the end
}
}
I try to insert this array :
#include <stdio.h>
#include <string.h>
#include <conio.h>
#define N 100
void main()
{
char t[] = "hello my name is.";
int cum[N];
wordsLen(t, cum, strlen(t));
getch();
}
Since am not getting any result , I would like to know why , and is there any problem with the code for counting the length of words? like is it good for counting the length of word or do I need to change something.
Here is a little modification of your function.
void wordsLen(char* text, int* words, int n)
{
int i, count = 0, s = 0;
for (i=0; i < n; i++)
{
if (text[i] != ' ')
{
count++;
}
else
{
printf("%d",count);
count = 0;
}
}
printf("%d", count);
}
Here some code for counting the words and there length:
void addWord(int* numberOfWords, int* count) {
*numberOfWords = *numberOfWords + 1;
*count = 0;
}
void print(int numberOfWords, int count) {
printf("number of words %d \n", numberOfWords);
printf("word length %d \n", count);
}
void wordsLen(char* text, int* words, int n)
{
int i = 0;
int count = 0;
int numberOfWords = 0;
//words[countWords(text)]; // dynamicly set the length
for (i = 0; i < n; i++)
{
char ch = text[i];
if (ch != ' ')
{
count++;
}
if (count > 0 && (ch == ' ' || (i == n - 1)))
{
print(numberOfWords + 1, count);
addWord(&numberOfWords, &count);
}
}
}
Try this:
void wordsLen(char* text, int* words, int n)
{
int i, count = 0, s = 0;
//words[countWords(text)]; // not important
for (i=0; i <= n; i++)
{
if (text[i] != ' ' && text[i] != '\0')
{
count++;
}
else
{
printf("%d ",count);
count = 0;
}
//printf("%d",count);
}
}
I'm trying to make a palindrome finder in C and I don't know where it is going wrong, no matter what I get the output false on the 2 different ways that I have tried to code this. I have only just started C (in the past week) so if you could explain things simply that'd be great, thanks!
//way1
#include <stdio.h>
int read_char() { return getchar(); }
void read_string(char* s, int size) { fgets(s, size, stdin); }
void print_char(int c) { putchar(c); }
void print_string(char* s) { printf("%s", s); }
int is_palin(char word[]) {
int m = 0;
int arr_len = sizeof(word) / sizeof(char); //change to char_index
int n = arr_len;
int t = 1;
if(n % 2 != 0) {
for (m=0; m < ((n-1)/2); m++) {
if(word[m] != word[n-m-2]) {
t = 0;
}
else {
t = 1;
}
}
}
else {
for (m=0; m < (n/2)-1; m++) {
if(word[m] != word[n-m-2]) {
t = 0;
}
else {
t = 1;
}
}
}
if(t == 1) {
return 1;
}
else {
return 0;
}
}
int main(void) {
char word[6] = "civic";
int arr_len = sizeof(word)/sizeof(char);
if (is_palin(word) == 1) {
printf("is palin\n");
}
else {
printf("is not palin\n");
}
printf(word);
printf("\n");
printf("%d\n", arr_len);
return 0;
}
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//way2
#include <stdio.h>
int read_char() { return getchar(); }
void read_string(char* s, int size) { fgets(s, size, stdin); }
void print_char(int c) { putchar(c); }
void print_string(char* s) { printf("%s", s); }
int is_palin(char word[]) {
int m = 1;
int input_length = sizeof(word);
int j = input_length-1;
int i = 0;
for(i=0; i <= j; i++) {
if(word[i] != word[j]) {
m = 0;
j--;
}
}
if(m == 1) {
return 1;
}
else {
return 0;
}
}
int main(void) {
char word[6] = "civic";
int input_length = sizeof(word);
if (is_palin(word) == 1) {
printf("is palin\n");
}
else {
printf("is not palin\n");
}
printf(word);
printf("\n");
printf("%d\n", input_length);
return 0;
}
Please try this, it works fine.
#include <stdio.h>
int main( )
{
int flag = 0;
int length = 0;
int len2 = 0;
int i = 0;
char name[130];
char p[130];
char q[130];
printf( "please enter a name or sentence\n" );
scanf( "%[^\n]", name );
length = strlen( name );
len2 = length;
strcpy( p, name );
memset( q, '.', length ); // handy to debug comparaison
q[length] = '\0';
for ( i = 0; i < length; i++ )
{
q[--len2] = p[i];
}
printf( "\n p==%s", p );
printf( "\n q==%s", q );
getchar( );
if ( !strcmp( p, q ) )
flag = 1;
if ( flag == 1 )
printf( "\npalindrome\n" );
else
printf( "\nnot a palindrome\n" );
return 0;
}
Take a look at this code, that's how I have implemented it (remember to #include <stdbool.h> or it will not work):
for(i = 0; i < string_length; i++)
{
if(sentence[i] == sentence[string_lenght-1-i])
palindrome = true;
else
{
palindrome = false;
break;
}
}
Doing that it will check if your sentence is palindrome and, at the first occurence this is not true it will break the for loop. You can use something like
if(palindrome)
printf(..);
else
printf(..);
for a simple prompt for the user.
Example :
radar is palindrome
abba is palindrome
abcabc is not palindrome
Please , pay attention to the fact that
Abba
is not recognized as a palindrome due to the fact that ' A ' and 'a' have different ASCII codes :
'A' has the value of 65
'a' has the value of 97
according to the ASCII table. You can find out more here.
You can avoid this issue trasforming all the characters of the string to lower case characters.
You can do this including the <ctype.h> library and calling the function int tolower(int c); like that :
for ( ; *p; ++p) *p = tolower(*p);
or
for(int i = 0; str[i]; i++){
str[i] = tolower(str[i]);
}
Code by Earlz, take a look at this Q&A to look deeper into that.
EDIT : I made a simple program to do this, see if it can help you
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
#include <ctype.h>
void LowerCharacters(char *word, int word_lenth);
int main(void){
char *word = (char *) malloc(10);
bool palindrome = false;
if(word == 0)
{
printf("\nERROR : Out of memory.\n\n");
return 1;
}
printf("\nEnter a word to check if it is palindrome or not : ");
scanf("%s", word);
int word_length = strlen(word);
LowerCharacters(word,word_length);
for(int i = 0; i < word_length; i++)
{
if(word[i] == word[word_length-1-i])
palindrome = true;
else
{
palindrome = false;
break;
}
}
palindrome ? printf("\nThe word %s is palindrome.\n\n", word) : printf("\nThe word %s is not palindrome.\n\n", word);
free(word);
return 0;
}
void LowerCharacters(char *word, int word_length){
for(int i = 0; i < word_length; i++)
word[i] = tolower(word[i]);
}
Input :
Enter a word to check if it is palindrome or not : RadaR
Output :
The word radar is palindrome.