Coding in C: help with if statements

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • MarioNintendo
    Expect delays.
    FFR Simfile Author
    FFR Music Producer
    • Mar 2008
    • 4177

    #1

    Coding in C: help with if statements

    Hey peeps! Just started getting into C for University. I am experimenting with the language, and so far I came with a little problem. To begin with, here's my code:

    Code:
    #include <stdio.h>
    int main (void)
    {
    	/*Declarations --------------------------------*/
    	char yourname[30]; 
    	
    	/*Program--------------------------------------*/
    	
    	printf("What's your name, bro? ");
    	scanf("%s", yourname);  // I ask the user to write his name 
    	
    	if (yourname == "Felix")  // If the name entered is Felix, he gets a warm welcome. 
    	{
    		printf("Hello master %s, king of the universe.\n", yourname);	
    	}
    	
    	else                  // If the name entered is anything other than Felix, the program doesn't recognize you. 
    	{
    		printf("I don't know you\n");
    	}
    }
    What I'm trying to do is to make it "recognize" me. Sadly, even when I type Felix, it doesn't recognize me at all! It will always reply "I don't know you". I get no error from the compiler, so I assume this must be some kind of weird syntax mistake... What's going on here?

    Weirdly enough, when I try to make a similar program using numbers this time around (integers, to be exact), it works like a charm. This is what makes me wonder why it doesn't work when I type letters. Here's an example:

    Code:
    #include <stdio.h>
    int main (void)
    
    {
    	/*Declarations --------------------------------*/
    	int yourage; 
    	
    	/*Program--------------------------------------*/
    	
    	printf("What's your age, bro? ");
    	scanf("%d", &yourage);  // I ask the user to write his age, this time. 
    	
    	if (yourage == 20)  // If the name entered is 20 years old, he gets a warm welcome. 
    	{
    		printf("Hello my master, king of the universe.\n");
    		
    	}
    	
    	else                  // If the age is anything other than 20, the program doesn't recognize you. 
    	{
    		printf("I don't know you\n");
    	}
    }
  • dag12
    FFR Simfile Author
    FFR Simfile Author
    • Dec 2004
    • 468

    #2
    Re: Coding in C: help with if statements

    Do you know how strings (really an array of characters in C) work in C? Are you familiar with the concept of pointers?

    In any case, using strcmp() when comparing strings will likely solve your issue.

    Comment

    • MarioNintendo
      Expect delays.
      FFR Simfile Author
      FFR Music Producer
      • Mar 2008
      • 4177

      #3
      Re: Coding in C: help with if statements

      Sadly, I am not. I thought strings would work just like numbers. Really, why is there a difference?

      Comment

      • Zageron
        Zageron E. Tazaterra
        FFR Administrator
        • Apr 2007
        • 6592

        #4
        Re: Coding in C: help with if statements

        Code:
        #include <stdio.h>
        #include <string.h>
        
        int main()
        {
        	char yourname[30];
        	scanf("%s", yourname);
        
        	// [url]http://www.cplusplus.com/reference/cstring/strcmp/[/url]
        	if(strcmp(yourname, "Felix") == 0)
        	{
        		printf("Hello master %s, king of the universe.\n", yourname);
        	}
        
        	else
        	{
        		printf("I don't know you...");
        	}
        
        	while(1);
        
        	return 0;
        }
        This is a rather quick way to do it. There are more raw ways of doing it as well, but for now. This will suffice.

        Do you know what will happen if you type in more than 30 characters?


        Edit: I'm glad to see you've adopted the open brace style, instead of the Egyptian style. (Stick with it!)
        I would also like to highly recommend against using CTRL + F5 to run your code, always use only F5. You should also get into the habbit of hitting Ctrl + Shift + B to compile before running.

        Of course, if you are using gcc and vim, this wont mean anything. This is under the assumption that you are using Visual Studio.
        Last edited by Zageron; 09-4-2013, 07:58 PM.

        Comment

        • MarioNintendo
          Expect delays.
          FFR Simfile Author
          FFR Music Producer
          • Mar 2008
          • 4177

          #5
          Re: Coding in C: help with if statements

          Are you using C++? I can't even compile this code, I get the following errors:

          Cstring no such files or directory
          'new' undeclared (it thinks it's a variable)
          Implicit declaration of strcmp
          'delete' undeclared

          And I don't know what happens if I type more than 30 characters, it doesn't seem to cut them. It won't compile if I don't specify a number though...

          I'm a real beginner btw rofl. Thanks for the help though, really appreciate it!

          Comment

          • Zageron
            Zageron E. Tazaterra
            FFR Administrator
            • Apr 2007
            • 6592

            #6
            Re: Coding in C: help with if statements

            Haha, my bad. You're using C. I definitely missed that, what a derp I am.

            I'll simplify the code so it doesn't confuse the **** out of you. (And also convert it into C)

            Edit: Changed the code. Sorry, I'm a C/C++ fusion programmer.

            Comment

            • MarioNintendo
              Expect delays.
              FFR Simfile Author
              FFR Music Producer
              • Mar 2008
              • 4177

              #7
              Re: Coding in C: help with if statements

              Hey, thanks a whole bunch. I'll keep this thread as a reference, I had no idea about the strcmp command. On the other hand, just to end this topic, I was wondering about why you included these commands:

              while(1);
              return 0;

              When I tried to remove them to see if they were essential, I saw no noticeable change. What do they do?

              Comment

              • Zageron
                Zageron E. Tazaterra
                FFR Administrator
                • Apr 2007
                • 6592

                #8
                Re: Coding in C: help with if statements

                Originally posted by Zageron
                Edit: I'm glad to see you've adopted the open brace style, instead of the Egyptian style. (Stick with it!)
                I would also like to highly recommend against using CTRL + F5 to run your code, always use only F5. You should also get into the habbit of hitting Ctrl + Shift + B to compile before running.

                Of course, if you are using gcc and vim, this wont mean anything. This is under the assumption that you are using Visual Studio.
                This might answer one of your questions, if you try out the different shortcuts. (Of course if you aren't using VS this wont make a difference.)

                The return 0 is good practice. If you are returning a type, you should always return a value from that type from all code paths.

                Example:
                Code:
                int main()
                {
                	if(true)
                	{
                		return 0;
                	}
                	else
                	{
                		return 1;
                	}
                }
                Purpose of this particular if statement aside, the end of the main() function doesn't have a return statement. Therefore if the if statement ever reached the else block, it should have a return value. You will understand why this is important later.
                Last edited by Zageron; 09-4-2013, 08:17 PM.

                Comment

                • Fission
                  no
                  FFR Simfile Author
                  • Jan 2004
                  • 1850

                  #9
                  Re: Coding in C: help with if statements

                  Originally posted by MarioNintendo
                  while(1);
                  this is an infinite loop because booleans that aren't equal to 0 always evaluate to true in C/C++. you won't ever be able to gracefully exit your program with this here. i would recommend against doing this and instead use http://www.cplusplus.com/reference/cstdio/fgets/ (keep in mind this is unsafe; more robust methods of halting are used in production code) so you can control when your program exits.

                  Originally posted by MarioNintendo
                  (yourname == "Felix")
                  this isn't doing what you think it is doing. you aren't comparing an array of characters to a string literal, you are comparing the address of the beginning of an array to a string literal. this isn't going to make much sense until you find out how arrays are actually implemented, but use strcmp as was posted here.

                  Originally posted by MarioNintendo
                  Really, why is there a difference?
                  because you don't always want the contents of the array concatenated together into a string -- sometimes you just want the location of the array in memory. this is something else that probably won't make sense until you discuss pointers.
                  Last edited by Fission; 09-4-2013, 09:42 PM.

                  Comment

                  • dAnceguy117
                    new hand moves = dab
                    FFR Simfile Author
                    • Dec 2002
                    • 10097

                    #10
                    Re: Coding in C: help with if statements

                    Originally posted by MarioNintendo
                    I thought strings would work just like numbers. Really, why is there a difference?
                    Great question.




                    Here's the pertinent information from that link:
                    In computer programming, a null-terminated string is a character string stored as an array containing the characters and terminated with a null character ('\0', called NUL in ASCII).
                    At the time C (and the languages that it was derived from) was developed, memory was extremely limited, so using only one byte of overhead to store the length of a string was attractive. The only popular alternative at that time, usually called a "Pascal string" (though also used by early versions of BASIC), used a leading byte to store the length of the string. This allows the string to contain NUL and made finding the length need only one memory access (O(1) (constant) time). However, C designer Dennis Ritchie chose to follow the convention of NUL-termination, already established in BCPL,
                    to avoid the limitation on the length of a string caused by holding the count in an 8- or 9-bit slot, and partly because maintaining the count seemed, in our experience, less convenient than using a terminator.
                    To put it very simply: that's how C works. Your idea would have worked in many other languages, although it's probably not in accordance with best practice.

                    Does anyone know where to find comprehensive documentation or help guides? We can post Wikipedia links all day, but that doesn't compare to something like the Python documentation.

                    Comment

                    • Fission
                      no
                      FFR Simfile Author
                      • Jan 2004
                      • 1850

                      #11
                      Re: Coding in C: help with if statements

                      two references i have used in the past:



                      the latter is a bit incomplete, but has still proven to be helpful where other references have failed.

                      Comment

                      • MarioNintendo
                        Expect delays.
                        FFR Simfile Author
                        FFR Music Producer
                        • Mar 2008
                        • 4177

                        #12
                        Re: Coding in C: help with if statements

                        Hey y'all! Back with another problem. I'm now trying to integrate a specific function which should supposedly give back the value close to pi=3.1415... and compare this value to the actual value of pi.

                        Here is a normal code I made which works right:
                        Code:
                        #include <stdlib.h>
                        #include <math.h>
                        #define N 1000
                        int main(void)
                        {
                        /* Declarations ------------------------------------------*/
                          double x[N]; /* A line function which depends on k */
                          float xi, xo; /* The ends of my interval */
                          int k, j;
                          double f[N];   /* This function will become f(x)=(1-x^2)^(1/2) */
                          float sum;     
                          float error;
                          float pi;
                          pi=M_PI;
                        
                        /* Executable --------------------------------------------*/
                          /*printf("f(x)=(1-x^2)^(1/2)\n\n"); */
                          xi=0;
                          xo=1;
                          for (k=0; k<N; k++) 
                            {
                              x[k]=xi+k*(xo-xi)/(N-1); /* Divide the line going from x=0 to x=1 in N-1 increments and go an increment farther each time this loop restarts */
                              f[k]=sqrt(1-pow(x[k],2));   /* This is the function on which we integrate from 0 to 1 */
                        	sum+=2*(f[k]+f[k-1])*(x[k]-x[k-1]); /* Area of each trapeze that we sum with the accumulation variable named 'sum' */
                               /*printf("f(%f) = %f    sum=%f        k = %d\n", x[k], f[k], sum, k); */
                            }
                              error=fabs(pi-sum);
                            printf("\nN = %d         Sum = %2.10f,         Error = %2.10f\n", N, sum, error);
                        
                            printf("\nEnd of line.\n\n");
                        }


                        This is fine and all. Now, I am trying to do the same thing, but for different N's, in other words, different fractions of the x=0 to the x=1 line. This is the one that crashes:

                        Code:
                        #include <stdlib.h>
                        #include <math.h>
                        #include <plplot.h>
                        #define I 8 /* I will be the maximal value of the j's linked to each N. We must not got further than this value. */
                        int main(void)
                        {
                        /* Declarations ------------------------------------------*/
                          double x[I]; 
                          double xi, xo; /* The ends of our interval */
                          int k, j;
                          double f[I];   /* This function will become f(x)=(1-x^2)^(1/2) */
                          double sum;
                          double error;
                          int N[I];
                          double pi;
                          pi=M_PI;   /* pi is really equel to pi */
                        
                        /* Executable --------------------------------------------*/
                          xi=0;
                          xo=1;
                          N[1]=3;             /* I manually assignate a value for each N */
                          N[2]=10;
                          N[3]=30;
                          N[4]=100;
                          N[5]=300;
                          N[6]=1000;
                          N[7]=3000;
                          N[8]=10000;
                        
                        j=0;
                        while (j<I)           /* I do a loop of the precedent code for each different value of N already pre-defined */
                          {
                            j++;
                            sum = 0;      /* Accumulation variable */
                            for (k=0; k<N[j]; k++) 
                              {
                        	x[k]=xi+k*(xo-xi)/(N[j]-1); /* Divide the line going from x=0 to x=1 in N-1 increments and go an increment farther each time this loop restarts */
                        	f[k]=sqrt(1-pow(x[k],2));   /* The function on which we integrate */
                        	  sum+=2*(f[k]+f[k-1])*(x[k]-x[k-1]); /* Area of each trapeze that we sum with the accumulation variable named 'sum'  */
                              }
                        	error=fabs(pi-sum);
                        	printf("For N=%d,    Error= fabs( %f - %f ) = %f\n", N[j],  sum, pi, error);
                          }
                              /* printf("sum = %2.10f\n", sum); */
                              printf("\nEnd of line.\n\n");
                        }
                        It gives me a segmentation error, which I guess means that the compiler dosen't have enough memory to run it (when I assign smaller values to N, like anything under 12, the code will work). Is there any way to fix this? I think my coding is in order, but I'm looking for a way not to make C crash in memory!
                        Last edited by MarioNintendo; 09-13-2013, 06:13 PM.

                        Comment

                        • Shouka
                          FFR Veteran
                          • Nov 2006
                          • 382

                          #13
                          Re: Coding in C: help with if statements

                          Umm, in the second code segment what is the value of i?

                          I don't see where it is initialized

                          Comment

                          • MarioNintendo
                            Expect delays.
                            FFR Simfile Author
                            FFR Music Producer
                            • Mar 2008
                            • 4177

                            #14
                            Re: Coding in C: help with if statements

                            Oops, my bad, it should read "I" instead of "i". Still, that doesn't seem to be the reason why it crashes, because when I manually change the N[j] values to smaller numbers, everything works fine.

                            Comment

                            • Shouka
                              FFR Veteran
                              • Nov 2006
                              • 382

                              #15
                              Re: Coding in C: help with if statements

                              Change "x[i] " and "f[i]" to "x[M]" and "f[M]". Then, add the line "#define M 10000" to the top of your program. Let me know if that fixes your issues.

                              What's happening is that you have only allocated space for 8 doubles in your arrays. In your for loop, the variable 'k' can range between 0 and 9999. So, when you execute the following lines:

                              x[k]=xi+k*(xo-xi)/(N[j]-1);
                              f[k]=sqrt(1-pow(x[k],2));

                              you are writing to memory that was not allocated for those arrays.

                              Also, arrays are zero indexed. So in the following lines:

                              N[1]=3; /* I manually assignate a value for each N */
                              N[2]=10;
                              N[3]=30;
                              N[4]=100;
                              N[5]=300;
                              N[6]=1000;
                              N[7]=3000;
                              N[8]=10000;

                              you should start counting from 0 and not 1. The element N[8] is actually the 9th element and is not in the space you have allocated for the array.
                              Last edited by Shouka; 09-14-2013, 11:05 AM.

                              Comment

                              Working...