Helping people get this ****ty idea out of their heads. C is not a hard language.
So C is just like batch you can input stuff, output stuff, to use that we include:
STDIO.H // Standard input/output
to output something we put printf("Hello world")
To ask the user for something we use scanf();
now to start a program.
To declare a variable.. there's :
Char, int, float that are mostly used.
a 1 in float is 1.000000
So lets make a simple program that asks for two numbers then does the sum and prints it shall we?
first of all
%d = decimal ( integer )
%s = string
%c = char
%f = float
%.2f = displays two numbers after the comma
%.3f = Displays three numbers after the comma. like 1.123
\n = new line
\t = gives a little space.
So that's easy right ?Code:#include<stdio.h> main() { int a,b,c; // you can see we use a ; at the end of every line, except some statements printf("Enter two numbers\n"); scanf("%d%d", &a,&b); The & is used to assign the value entered in %d for the variable. c=a+b; printf("%d", c); }
To conceive less memory we can use instead of
int c;
unsigned c;
now to move to other statements.
IF statements :
There are logical operators :
== ( equal )
!= ( NOT equal )
< ( smaller than )
!< ( NOT smaller than )
Now if the action is only 1 line of code we won't need { }Code:If(condition) action else if(condition action else action
if the first statement is wrong, it checks if the second is true. If none are true it goes to the ELSE.
There's the modulo in C wich is %
Will display 0, Why ? well you should know what a modulo is. I'm not that good in englishCode:fprintf("%d", 10%2);
So lets make a statement that checks if a number is dividable by two
Now we go to loops.Code:if((number%2)==0) printf("%d is dividable by two", number); else printf("%d is not dividable by two", number);
There are 3 kinds of loops, for, while, DO.. while.
using for is like this:
same thing in while it would be likeCode:for(i=0; i<10; i++) { printf("Hi\n"); }
You can see a while loop does not add anything automatically. you need to add the variable or else it would get stuck in the loop.Code:while(i<10) { printf("HI\n"); i++; }
now do while is the following:
now what it does is that it doesn't check for the condition untill it does the actionCode:do{ printf("Hi\n"); i++; while(i<10);
Now to move on to Switch Statement:
A switch statement is just like an easier " IF else if else if else if... "
This
Can be replaced byCode:#include<stdio.h> int main() { int c; scanf("%d", &c); if(c==0) { printf("You entered 0"); } else if(c==1) { printf("You entered 1"); } else if(c==2) { printf("You entered 2"); } }
you can see we used switch(variable)Code:#include<stdio.h> int main() { int c; scanf("%d", &c); switch(c) { case 0: printf("You entered 0"); break; case 1: printf("You entered 1"); break; case 2: printf("You entered 2"); break; } }
You can consider the variable as something the switch holds and checks the cases.
lets take a virtual example,
lets say if switch case 1 is true, the value is now 1(true)
So now it won't check for others. it will just keep going writing all the other cases.
Thats why we use "Break" statement, it will break the loop,if,switch statement and move on.
If case 1: is false, it won't check whats inside knowing that it won't be needing it!
So now that we know what switch is.. Lets do some examples on all those statements;
A calculator using if statement
GUEST MADE IT NOT ME.Code:#include <stdio.h> int main() { float num1, num2; char operation; while (1) { scanf("%f%c%f", &num1, &operation, &num2); if (operation == '+') printf("%f\n", num1+num2); if (operation == '-') printf("%f\n", num1-num2); if (operation == '*') printf("%f\n", num1*num2); if (operation == '/') printf("%f\n", num1/num2); } getchar(); return 0; }
Thats for the if, now that you know how to use switch, you should know how to change all of those if's to switch cases...
Now for using strings..
A string is like uhh a sentence !
How do we call it a string ? Easy !
char str[lengh];
keep in mind that the string will hold a '\0' so if you call the lengh 90, it will only hold 89 letters.
So how to ask the user to input a string ? there are many ways ! But the safest one is
fgets(buffer, buffer_size, stdin);
Why we use this ? because simply this limits the amount of characters to take from the user to prevent buffer overflows ( Zekedragon told me that)
To print a string you can either use printf("%s", str);
or puts(str);
keep in mind while using fgets when you press enter it will also grab the enter and put it in the string.
So if we put " hello man [enter] "
The string will say " Hello man \n" taking the crusor to a new line..
To clear it up we use a " LOOP "
This will eliminate the new line for usCode:for ( i = 0; i < stringsize; i++ ) { if ( input[i] == '\n' ) { input[i] = '\0'; break; } }
Now of course our beloved C has made things easier for us by making a library called " string.h "Wich holds some usefull statements like
strcat is short for "string concatenate"; concatenate is a fancy word that means to add to the end, or append. It adds the second string to the first string. It returns a pointer to the concatenated string. Beware this function; it assumes that dest is large enough to hold the entire contents of src as well as its own contents.Code:strcpy strcat strlen
strcpy is short for string copy, which means it copies the entire contents of src into dest. The contents of dest after strcpy will be exactly the same as src such that strcmp ( dest, src ) will return 0.
strlen will return the length of a string, minus the termating character ('\0'). The size_t is nothing to worry about. Just treat it as an integer that cannot be negative, which is what it actually is. (The type size_t is just a way to indicate that the value is intended for use as a size of something.)
Now a small program to make things easier:
Credits for C programming.com - Your Resource for C and C++ Programming for the last source and string definitionsCode:#include <stdio.h> /* stdin, printf, and fgets */ #include <string.h> /* for all the new-fangled string functions */ /* this function is designed to remove the newline from the end of a string entered using fgets. Note that since we make this into its own function, we could easily choose a better technique for removing the newline. Aren't functions great? */ void strip_newline( char *str, int size ) { int i; /* remove the null terminator */ for ( i = 0; i < size; ++i ) { if ( str[i] == '\n' ) { str[i] = '\0'; /* we're done, so just exit the function by returning */ return; } } /* if we get all the way to here, there must not have been a newline! */ } int main() { char name[50]; char lastname[50]; char fullname[100]; /* Big enough to hold both name and lastname */ printf( "Please enter your name: " ); fgets( name, 50, stdin ); /* see definition above */ strip_newline( name, 50 ); /* strcmp returns zero when the two strings are equal */ if ( strcmp ( name, "Alex" ) == 0 ) { printf( "That's my name too.\n" ); } else { printf( "That's not my name.\n" ); } // Find the length of your name printf( "Your name is %d letters long", strlen ( name ) ); printf( "Enter your last name: " ); fgets( lastname, 50, stdin ); strip_newline( lastname, 50 ); fullname[0] = '\0'; /* strcat will look for the \0 and add the second string starting at that location */ strcat( fullname, name ); /* Copy name into full name */ strcat( fullname, " " ); /* Separate the names by a space */ strcat( fullname, lastname ); /* Copy lastname onto the end of fullname */ printf( "Your full name is %s\n",fullname ); getchar(); return 0; }![]()
Overall, this seems like a random hodge-podge of bits that does a lesser job than most of introducing the C language.
I generally advise avoiding scanf -- unless you are willing to venture into all of the caveats and issues that arise when you attempt to use it safely and correctly (which can be non-trivial).
Implicit int declaration of main has really been out of date since 1989. With scanf, which I mentioned earlier has many issues, you should at least be checking the return value to see if you actually obtained the input before using them. I might also add that main returns an int, and generally 0 is what is returned for success.
Meh.
I have no idea why or what you are trying to say here. Both likely use the exact same amount of memory, and this bit just appears out of nowhere for no reason (as well as not really being correct).
Are you kidding me?
Match parens.
True. And like the source of future bugs. I always use braces. I recommend it.
You might as well try to write equivalent loops -- which would require you to initialize i for the while loop. Especially since...
...you bring up the attempt for equivalence here. And the for loop doesn't add anything automatically for you either -- the code to do so is in a different location.
Which means (an important thing to bring up) that a do...while will always execute at least once. Again, though, i needs to be initialized.
Except that a switch only works with integer constants for cases. So you can't use if for string comparisons. You can't use it for ranges.
When a switch is in a loop, the break statement in a case will not break the loop, it will break out of the switch. I'm not sure what you're trying to say.
---
Overall, this is quite a mixed bag of various things you mention. But I don't think it's a good substitute for other introductions such as:
C Programming Notes
Keep at it, though. I try to offer constructive criticism. I hope my comments are received as such, even though the words I choose at times may seem unduly harsh.
Okay uhh , thanks ?
Nice tut Moudi
Get rid of this code. scanf isn't used correctly. Have a peak at this post for more information.Code:#include <stdio.h> int main() { float num1, num2; char operation; while (1) { scanf("%f%c%f", &num1, &operation, &num2); if (operation == '+') printf("%f\n", num1+num2); if (operation == '-') printf("%f\n", num1-num2); if (operation == '*') printf("%f\n", num1*num2); if (operation == '/') printf("%f\n", num1/num2); }
Helping people get this ****ty idea out of their heads. C is not a hard language.
Any language can be hard to learn for most people when they first start out. I recommend just getting your hands on a good book. No one short post could ever cover all the basics and if you believe so you may want to also go and get a nice book. scanf is fine to start off learning with and it's flaws shouldn't even be mentioned till the student has a fine enough grasp on simple programming concepts. They are plenty of standard C functions that can totally screw up an otherwise great program.
And btw signed and unsigned ints are the same size. You may of been thinking of short int, int, long int, long long int. Which have no gaurentees of having different sizes either. The only guarentee is that long long int >= long int >= int >= short int. The sizes are machine specific and the knowledge can really be skipped until some better foundation in programming has been established.
They are other flaws in your post that dcs didn't pick up on. On a 5 star rating for useful tutorials I have to give this just 1 star. Sorry. Keep practicing and learning you are getting there. I think a "newb" would be better off skipping this tut.
I guess I'll just leave off saying learning to program isn't hard. It's the programming concepts that can be hard (and the jargon).
C is basicly a few reserved keywords and operators.
Last edited by XJamesX; 03-23-2010 at 10:09 AM. Reason: typo iaks
while(1) { if(if_girl_is_pretty(girl)) ask_her_out();
else drink_another_beer(); }
Another useful thread i've been doing some study on C programming in the last few months and the lecturer over complicates the language. I hope you don't mind but I've made copy of this tutorial for my own reading. I find it is always useful to have multiple materials when learning a programming language.
I agree that C is quite easy, the problem is when people are first starting out and they find it difficult to understand some of the concepts of programming theory in general.
Thanks for writing this tut.
That's a good tutorial and good reviews. No doubt it's helpful for beginners to start. A revealing criticism will be much appreciated although , i.e. not just " why did you use scanf() " ,insteed " you should use (something) because it help you to overcome problem like (something) "
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks