Removing `else` condition suddenly makes the code work, what gives? [closed] - c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
This code doesn't do as intended - it should print out all of plaintext. I'm guessing there's something at work under the hood, but that logic escapes me. If you remove the else condition with underlying statement, it suddenly works.
#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
int main() {
string plaintext = get_string("plaintext: ");
int i;
for(i = 0; plaintext[i] != '\0'; i++)
if(isalpha(plaintext[i] != 0))
printf("%c", plaintext[i]);
//I intend to do stuff with alphabetic characters, but that code isn't relevant, so it's not included
else
printf("%c", 'a');
}
I'll be honest, this looks like magic to me. Why would adding an else condition affect whether the condition for the original if statement was met or not (if that's the case)?
Is it somehow because of using string in cs50.h?

for(i = 0; plaintext[i] != '\0'; i++)
if(isalpha(plaintext[i] != 0))
printf("%c", plaintext[i]);
else
printf("%c", plaintext[i]);
is the same as :
for(i = 0; plaintext[i] != '\0'; i++)
printf("%c", plaintext[i]);
because any logical operation may have two results: true and false. If in both cases you do exactly the same, why do you check the condition?
another problem :
if(isalpha(plaintext[i] != 0))
it should be
if(isalpha(plaintext[i]) != 0)

Related

Trouble with C program blank output [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
int i=0,j=0;
char string[100], string2[100];
scanf("%s",&string);
while (string[i]!='\0'){
if(string[i]=='a' || string[i]=='e' || string[i]=='i' || string[i]=='o' || string[i]=='u' || string[i]=='A' || string[i]=='E' || string[i]=='I' || string[i]=='O' || string[i]=='U'){
string[i]=string2[j];
}
string[i] = tolower(string[i]);
string[i] = string2[j];
string2[j-1]='.';
}
printf("%s", string2);
return 0;
The question is entering a word and then removing all vowels, adding '.' after every constant and making all upper case letters lower case.
Since string is an array, you don't use & when passing it to scanf(), this gives you a double pointer and is an error. Any time you find yourself with a 10 clause if statement, you're just asking for problems (e.g. easy to get tripped up by typos.) You can simplify this test with index() and a string containing all the vowels. It wouldn't hurt to comment as you write your code to indicate which of the requirements each section implements. The i variable needs to be incremented every time through the loop, the j variable needs to be incremented every time a new character is added to string2. After the scanf(), you shouldn't be assigning into string, treat it as readonly, only assign into string2. And j-1 shouldn't happen. Finally, since string2 isn't intialized, there may be garbage in it and you haven't null terminated it. Putting it all together:
#include <ctype.h>
#include <stdio.h>
#include <strings.h>
#define VOWELS "AEIOUaeiou"
int main()
{
char string[100], new_string[100] = { 0 };
// enter a word
scanf("%s", string);
for (int i = 0, j = 0; string[i] != '\0'; i++)
{
// remove all vowels
if (index(VOWELS, string[i]) == NULL)
{
// make all upper case letters lower case
new_string[j++] = tolower(string[i]);
if (isalpha(string[i]))
{
new_string[j++] = '.'; // add '.' after every consonant
}
}
}
printf("%s\n", new_string);
return 0;
}
I'm assuming "after every constant" was meant to read "after every consonant", otherwise please clarify what you mean by constant.

string palindrome in c [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 7 years ago.
Improve this question
I am writing a program of string pallindrome, code is compiling successfully but on running it accepting the string but nothing after that, the output window stays on hold with cursor blinking, help me what is wrong with this code.
I am using dev-c++
gets(ch); // the program stops here
p=ch;
while(ch!='\0')
{ p++;
size++;
}
for(i=0;i<20;i++)
{
if(c[i]==c[j])
printf("string is pallindrome");
else printf("string is not pallindrome");
}
getch();
return 0;
}
Here is the problem:
while(ch!='\0')
ch is a char array, and you are comparing it with a single char.
Also, size is not initialised.
I would suggest something like this:
size=0;
while(ch[size]!='\0')
{ p++;
size++;
}
or, using the pointer method:
while(*p!=0)
{
p++;
size++;
}
Also, instead of printing inside the for loop (which would make it print several times), use a flag variable.
You only need one loop, for example while (i < i).
Look at this example that will do the job:
#include <stdio.h>
#include <string.h>
/* in c99 use <stdbool.h> instead*/
typedef int bool;
#define true 1;
#define false 0;
int main(void)
{
char ch[20];
puts("enter the string: ");
gets(ch);
size_t size = strlen(ch);
bool pallindrome = true;
int j = size-1;
int i = 0;
while (i < j)
{
if(ch[i] != ch[j]) {
pallindrome = false;
break;
}
++i;
--j;
}
if (pallindrome)
printf("\"%s\" is pallindrome\n", ch);
else
printf("\"%s\" is not pallindrome\n", ch);
getch();
return 0;
}

rubbish instead of string display [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
The task is to be sure that phrases are can be readed vise versa or not (without spaces ' ').
So I got the point and made some code. But when I made
printf("%s", str_1)
I found a lot of same russian letters.
For example my inputs are: '123' '321', but displayed rubbish
My str_1[i] is going to be like 123321 and then checked first and last and so on members.
After that I added in if condition if(str[i] != 'М') and now everything nice.
Please tell me what I did wrong and what is going on with "M".
I hope my question is clear.
#include "stdio.h"
#include "locale.h"
int main(){
char str[100];
char str_1[100];
int i, j, k, l;
j = 0;
l = 0;
fgets(str, 100, stdin); //we got array
//how many chars before '\0'
for(i = 0; i < 100; i++)
{
if(str[i] != ' ' && str[i] != '\n' && str[i] != 'М')
{
str_1[j] = str[i]; //made new array without spaces between words or whatever
j++;
}
}
j--;
for(k = 0; k < j; k++)
{
if(str_1[k] == str_1[j - 1 - k])
{
l++;
}
}
if( l == k)
{
printf(";) YES! good job!\n");
}
else
{
printf(";) NOT! I'm sorry!\n");
}
return 0;
}
As it seems, you skip over the end of the string, as you never check where it ends.
At least, this is my suspicion; I am not sure if it is the right reason.
You should check for str[i] == '\0' as well and then break the whole loop.
As I see, you even made this consideration in
//how many chars before '\0'
but didn't include it in code.
A
for(i = 0; i < 100 && str[i] != '\0'; i++)
should do the trick if you omit the j-- afterwards.

I dont know what is wrong with this program. it's supposed to convert binary to decimal in c [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
well this program is supposed to convert a binary number to decimal. im new to c and im not very confident in coding C. tried and coded this program but doesnt run properly. and I have no idea what part is wrong here. need some help to complete this program.
thanks
binaryToDecimal(char str[]) {
for(int i = strlen(str)-i; i>=0; i--) {
if(str[i] == 48 || str[i] == 49) {
int tmp = pow(2, counter);
int sum= str[i]*tmp;
counter++;
answer += sum;
} else if(str[i]>49 || str[i]<48) {
printf("error");
}
}
printf("%d", &answer);
}
This phrase doesn't make sense:
int i = strlen(str)-i;
i hasn't been initialized yet, but you're using it in the expression!
I believe you meant:
int i = strlen(str)-1; // ONE ... not I
str[i] is a character, either '1' or '0' which as you have it is equal to 48 and 49 as integers. So you want to convert them to 1 and 0 them do the multiplication.
sum = (str[i] - 48) * tmp;
Assuming all variables have been initialised to sensible values and str holds the input. The following code should work, although it is not particularly efficient.
You can use '0' and '1' instead of more obscure 48 and 49.
for (i = strlen(str)-1, j = 0; i >= 0; --i, ++j) {
if (str[i] != '0' && str[i] != '1') {
printf("ERROR: unxepected input\n");
exit(EXIT_FAILURE);
}
if (str[i] == '1')
sum += pow(2, j);
}
when printing the result provide the value and not it's address, e.g.
printf("%d\n", sum); // (!) not &sum

Weird results in c [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'd like to ask you about my prog. The main purpose of this one is to fill the "result" array with data collect from "tab1" and "tab2" arrays. Could anybody check, why does results are so weird? Thank you.
#include <stdio.h>
#include <stdlib.h>
void laczenie(char tab1[],char tab2[])
{
int i;
char* result =(char*) malloc(100*sizeof(char));
for(i=0;i<30;i++)
{
if(tab1[i] != '\0') tab1[i]==result[i];
else if (tab2[i] !='\0')tab2[i]==result[i];
else printf(" ");
}
for(i=0;i<30;i++)printf("%c",result[i]);
free(result);
}
int main()
{
char x[10]={'n','a','p','i','s','1'};
char y[10]={'n','a','p','i','s','2'};
//char x[10] = {"napis1"};
//char y[10] = {"napis2"};
laczenie(x,y);
return 0;}
In addition to LihOs answer above this block looks wrong:
if(tab1[i] != '\0')
tab1[i]==result[i];
else if (tab2[i] !='\0')
tab2[i]==result[i];
else printf(" ");
Don't you mean to assign the value in tab1[i]or tab2[i] to result[i]like this?
if(tab1[i] != '\0')
result[i] = tab1[i];
else if (tab2[i] !='\0')
result[i] = tab2[i];
else printf(" ");
Also using magic numbers like in the loops: for(i=0;i<30;i++) is pretty bad practice, you should probably be using a constant for the size value (which you could then use in both the loops and in the array declarations. And why loop to 30 when the arrays is 10 elements only?
In your function you check for null-terminating character:
if(tab1[i] != '\0')
but where is null-terminating character here?
char x[10]={'n','a','p','i','s','1'};
Try:
char x[7]={'n','a','p','i','s','1','\0'};
Also note that tab1[i]==result[i]; compares tab[1] with result[i], if you want to assign the result[i] to tab1[i], use assignment operator =:
tab1[i]=result[i];
if(tab1[i] != '\0')
result[i] = tab1[i];
else if (tab2[i] !='\0')
result[i] = tab2[i];
else printf(" ");`
This is still wrong as by the time you assign tab2 to result i will be already at 6 so you will have to use two for loops i suppose for assign tab1 and tab 2

Resources