How the comparisons "if (arr<=arr1)" works in the given program? - c

How this comparison works?
#include <stdio.h>
#include <string.h>
int main(void) {
char arr[]="WELCOME";
char arr1[]="WELCOME";
if (arr<=arr1)
printf("equal");
else
printf("not equal");
return 0;
}
In this program that if condition this always go to else,
so please some one help me how that comparison done here.

The comparison ends up asking where the two arrays arr and arr1 are located with respect to each other in memory. It is asking which one has the lower address.
If you're trying to compare the string values contained in the two arrays, use strcmp:
if(strcmp(arr, arr1) <= 0) ...

As far as my knowledge goes, arr or as a matter of fact any array variable stores the address of the first element in the array. So when you do arr<=arr1 you are actually comparing their addresses. So that's what it does.
P.S. you can print the addresses just in case you want to check. As in:
printf("\n%p", (void*) arr);
From the looks of your program, it seems that you want to compare the two strings. You then have to do:
if(strcmp(arr,arr1)==0)
printf("Entered strings are equal.\n");
else
printf("Entered strings are not equal.\n");

Related

How on earth to use char and if statements?

I'm a rookie programmer trying to run a simple code on VS code.
#include<stdio.h>
int main()
{
char* a;
printf("Enter a char");
scanf("%s",&a);
if (a = "yes")
{
printf("Number is 30");
}
else if (a = "no")
{
printf("Number is 50");
}
else{
printf("oops");
}
return 0;
}
I guess looking at the code you guys can figure out what I'm trying to do, if the user enters "yes", a specific sentence need to be displayed and similarly for "no".
The problem here is whatever I write in the input, it will always print the first statement, "Number is 30". I've tried running similar codes but ended up with the same output.
If possible, please explain me how to use char,strings,arrays with if-else statements.
There are several misunderstandings in the posted code.
First there is a misunderstanding of char versus string. A char is for instance a single letter, a single special character like ., ;, etc. (see note1) while a string is a serie of chars. So
'y' is a char
"yes" is a string
You print "Enter a char" but from the code it's obvious that you really want "Enter a string".
This leads to the next problem. To input a string using scanf you need to pass a "pointer to char". Your code pass "a pointer to pointer to char" due to the &. Further the passed pointer must point to some memory. So you need:
char a[10]; // Make it an array of char so that it can hold a string
printf("Enter a string, max 9 characters");
scanf("%9s", a); // No & before a and width specifier used to avoid buffer overflow
Now this part
if (a = "yes")
is not the way to compare two strings in C. For that you need the function strcmp - like:
if (strcmp(a, "yes") == 0)
Putting it together it's like:
int main()
{
char a[10];
printf("Enter a string, max 9 characters");
scanf("%9s", a);
if (strcmp(a, "yes") == 0){
printf("Number is 30");
}
else if (strcmp(a, "no") == 0)
{
printf("Number is 50");
}
else
{
printf("oops");
}
return 0;
}
That said, I don't understand why you print stuff like: "Number is 30" but that's kind of irrelevant here.
note1: The type char is actually an integer type, i.e. a number, but the common use is to map these numbers to characters using ASCII encoding.
There are different ways to initialize a variable to access C string.
char *char_ptr = "Hello";
This initializes char_ptr to point to the first character of the read-only string "Look Here".A C string initialized through a character pointer cannot be modified. When a C string is initialized this way, trying to modify any character pointed to by char_ptr is undefined behaviour. An undefined behaviour means that when a compiler encounters anything that triggers undefined behaviour, it is allowed to do anything it seems appropriate.
A more convenient way to define strings that can be modified is to use:
char str[];
This way you can modify any character in the C string
p.s you also need to use strcmp() for the if statement
You can take string input in C using
scanf(“%s”, str);
And to compare the string you need to use:
strcmp(str1, "yes");

How does strcmp work when comparing strings?

I am implementing a lexicographic sort and my professor told us to use strcmp in our implementation. The problem is, strcmp is very confusing in respects to how it compares strings.
For instance, this here yields false:
if (strcmp("What", "am") > 0) {
printf("true\n");
} else {
printf("false\n");
}
Isn't "What" suppose to be greater than "am" lexicographically? The man page is very spartan in terms of explaining how the function determines if one string is greater or less than the other. There are some questions here, but I still cannot determine this result based on those explanations.
The problem is that strcmp makes a binary comparison. This fact makes the function case sensitive! The ASCII code of "W" is smaller than the ASCII code of "a".
The way to solve the problem is to compare text strings that as the same capitalization.
A simple way to obtain this shall be:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
char* stoupper( char* s )
{
char* p = s;
while (*p) {
*p= toupper( *p ); p++
};
return s;
}
int main(void)
{
char a[10];
char b[10];
strcpy(a,"What");
strcpy(b,"am");
if (strcmp(stoupper(a), stoupper(b)) > 0) {
printf("true\n");
} else {
printf("false\n");
}
}
Remember that the use of the function stoupper modifies definitively the text in the string!
Any capital letter compare less than any lowercase one. Look at an ASCII chart and the definition of lexicographical comparison.
My guess is that this is because 'W' comes before 'a' in the ascii table. So 'What' is actually 'lesser' than 'am'.
If you switch them I guess 'am' is 'greater' than 'What'.

Searching for an element in 2D array, C programming

I'm a noob at C programming and I'm having some difficulties making a string list and searching for a specific element.
#include <stdio.h>
#include <string.h>
# define MAX 6
int main(){
char word[MAX];
char x[MAX][20];
int i;
strcpy(x[0], "One");
strcpy(x[1], "Two");
strcpy(x[2], "Three");
strcpy(x[3], "Four");
strcpy(x[4], "Five");
strcpy(x[5], "Six");
printf("%s", "Search:");
scanf("%s", word);
for (i=0; i<6; i++) {
if (x[i] == word) {
printf("%s", "Found a match!");
}
}
return 0;
}
It's never executing the statement present in the if block (i.e, printf("Found a match!")) . Any idea why it is not executing the above mentioned statement?
Thanks!
Use
if(strcmp(x[i],word) == 0)
printf("Found match\n");
== can't be used to compare strings as you are doing it.
This only compares the pointers and not the strings
It never returns "Found a match!". Any idea why?
Reason:
In C, array names are converted to pointers to their first elements ( with some exceptions there). x[i] == word is comparing two pointers instead of comparing strings. Since the base addresses of both arrays are different, comparison returns a false value.
Correction:
Use strcmp to compare two strings.
This
if (x[i] == word)
should be
if (strcmp(x[i], word) == 0)
In c a predefined function is present in string.h library it is strcmp as stated by other users function int strcmp(const char *str1, const char *str2) compares the string pointed to bystr1 to the string pointed to by str2.u can write your own function for comparing strings and use it.
I want you to conceptually understand why we can't use == in c unlike c++ as c don't contain anything like string class(c is purely procedural) so that u can create object of it and use it.hence c uses char array to represent a string .if u examine ur code x[i] == word compares starting addresses of char arrays/strings x[i],word. I believe u understood the concept . now I want to explain that u can use pointers here i.e
if (*x[i] == *word)
printf("Found a match!");
Works fine as u can understand that here we are comparing two strings directly by pointing to their address locations.sorry if I have provided unwanted info due to my inexperience in SO as this my first answer in SO.
use strcmp() function for comparing two string. when two string is match its result is 0.
so you can change like :
if ( ! strcmp(word,x[i]) ) // when match result will be `! 0 = 1`
printf("Found Match\n");
in the C programming language, the == operator is not working for comparing strings(as others wrote before me). I advice to try using a really nice feature in C++ called string. It is builded in the standard library, and with this, you can use the == operator for comparing.
#include <iostream>
using namespace std;
int main(void)
{
string a = "Apple";
if( a == "Apple" ) cout << "This is working" << endl;
}

The following code for palindrome doesn't work?is there a logical mistake?

Could someone point me to the error in this code. Iam using codingblocks IDE.
#include <stdio.h>
main()
{
char a[100],b[100];int i,j=0;
scanf("%s",&a);
for(i=strlen(a)-1,j=0;i>=0;i--)
{
b[j]=a[i];
j=j+1;
}
b[j]='\0';
if(a==b) # on printing i get both 'a' and 'b' as equal however this condition still remains
# false
printf("true"); #doesnot print?
}
Change this statement
if(a==b)
to
if ( strcmp( a, b ) == 0 )
Otherwise you are comparing addresses of the first elements of the arrays.
Also you need to include header <string.h>. Function main shall have return type int. Change this statement
scanf("%s",&a);
to
scanf( "%s", a);
Take into account that there is no need to define second array that to determine whether a string is a palindrome. You could do this check "in place".
Few issues in your code
You never copy anything in b, so that array has random characters.
a==b will always be false because they are character arrays not pointers and both contain different values.
If you are reading string, you don't need & for char array, so the scanf() should be scanf("%s",a);

swapping string in c using pointer

Need help
this is my code
void swapstringfun()
{
int i=0,j=0;
char *str=(char *)malloc(sizeof(char)*15);
char *mystr=(char *)malloc(sizeof(char)*15);
system("cls");
printf("Please enter first string :\t");
scanf("%s",str);
printf("Please enter second string :\t");
scanf("%s",mystr);
while(*(str+i)!='\0' && *(mystr+i)!='\0')
{
*(str+i) ^=*(mystr+i);
*(mystr+i) ^=*(str+i);
*(str+i) ^=*(mystr+i);
i++;
}
printf("%s swapped to %s",str,mystr);
getch();
main();
}
I wrote the above code to swap the string using XOR operator. The problem with this code is. when my input is lets say.. RAJESH and ASHISH. Then, it shows output ASHISH and RAJESH. And, that is expected.
But, when input is let say.. ABHISHEK and CODER .Then, output is CODERHEK and ABHIS. But, the expected output is CODER and ABHISHEK. Anyone help me to solve this problem. I will appreciate.
You iterate and swap until you reach the end of the shorter string
while(*(str+i)!='\0' && *(mystr+i)!='\0')
(or both, if the lengths are equal). To iterate until you reach the end of the longer string, you need an || instead of the && and be sure that 1. both pointers point to large enough memory blocks, and 2. the shorter string ends with enough 0 bytes. So you should calloc the memory, not malloc.
However, you should swap the pointers, really,
char *tmp = str;
str = mystr;
mystr = tmp;
You also need to swap the terminating 0, as its part of what is called a string in C.
The 0 is the stopper element in the character array, describing the string.
You need to XOR the entire length of both strings. Since in your second example, the strings are different lengths, your algorithm won't work.
This is the statement you'll have to reconsider:
while(*(str+i)!='\0' && *(mystr+i)!='\0')

Resources