C Programming tut by Polygrithm/Whackerz
C Programming Tutorial by Polygrithm This is another short tutorial on C programming its for newbies who want to start C. We start our first C program from Hello World: #includevoid main(){ printf("Hello World!"); } This is our First C program the first line #include is called a header file # is a preprocessor directive which includes stdio.h in our C program for what purpose ?: Because printf() function is not known to Compiler so it is defined in stdio.h which is then known to the Compiler. What is a function: Function is something which used for carrying out some specific task so printf() function is used for printing purposes in C. void main() This is also a function called the main function which is the first part to be executed Every C program consist of this function. This programs prints : Hello World! on the screen when Compiled. Escape Sequences : The following are the escape sequences : \n Line \b BackSpace \t Tab \a Beep or alert \f Form feed \v vertical form feed \' for inserting ' \" for inserting " How To Use Escape Sequences : In our First Program if you we want the World to be printed on the next line we will use \n for this purpose printf("Hello \n World!"); will print: Hello World! You can use other escape sequences in the same way .. I hope you will have understand the above program. Before going into practical programming You must read the following theory .... Constants , Variables and Keywords: Constants and Variables: Constant is something whose values remain the same in the whole program.Whereas a variable is something whose value can be changed . for Example : 8x+4y=32 Here 8 ,4 and 32 are constants whereas the x and y are the variables any value can be assigned to these variables for example x=4 and y=3 . Types of Constants : Integer Constants: Integer constants must not have a decimal point it must have at least one digit no commas or blanks are allowed. examples: 2 222 +53 -243 etc ... An integer constant have a range of -32768 to +32767 Floating type constants: These are different from integer constants : it can have a decimal point its range is from -3.4e38 to 3.4e38 Examples: 33.2 -22.43 4.1e8 etc.. Character Constant: These include characters from A to Z or a to z digits from 0 to 9 Special symbols . Character constants are written in single quotes like : 'a' Types of Variables: There are three types of Variables: 1.Integer 2.Real or Floating point 3.Character 1.Integer Variables : Integer variable declaration has the following form : int a; int=>This is the reserved word for integer whenever you want to declare something as an integer you will write int before it a=>this is the variable name. Integer Variables occupy 2 bytes . If you need more than 2 bytes then you can use long how? long a=2225325325; It occupies 4 bytes. 2.Floating point : Floating point declaratoin has the following form: float a; I wont go into much detail here as you will have understand if not! read integer variables. It occupies 4 bytes. for values more than 4 bytes we use double. double value=3.4423534397; 3.Character : To declare a character variable : char c='a'; It eates one byte in memory. Keywords: Keywords are reserved words in C you can't use it as variable names .They are known to the Compiler. The following are the reserved or keywords in C: auto, double ,if ,static ,break ,else, int, struct, case ,enum ,long, switch ,char near, typedef ,extern,register,union,continue,far,return,unsigned,default,for,short,void ,do ,goto, signed,while . *Comments Comments are something which the compiler ignores while executes comments are used to make a program easier to read .. //This is called a single line comment /*This is a multi line comment */ Thats all now lets start some practical programming.. ŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻ Now lets make a program which calculates the sum of two numbers.. #include void main(){ int a=2; int b=4; int sum=a+b; printf("Sum=%d",sum); } You are already familiar with some of the above statements However I have to explain: Here we have initialized a variable named a with 2, Whenever you want to assign a constant,variable or another statement we use '=' sign like a=2; now 2 is stored in a. printf("Sum=%d",sum); What is %d ? This is called a format specifier it tells the compiler that sum is an integer .. Some common format specifiers: %d is used for integer. %c for character %f floating point After compiling the above program you will get something like this sum=6 and thats the answer. Okay now you want to create a program which gets user input. #include void main(){ int a,b,sum; //a, b and sum are declared as integer variables printf("Enter two numbers="); //Asks the user to input two numbers scanf("%d %d",&a,&b); //inputs the two numbers sum=a+b; // adds the two numbers printf("Sum=%d",sum); outputs the sum } This program is a bit different from the first one because of the function scanf("%d %d",&a,&b); This is quite simply %d you already know it is used whenever you want to input or output some integer stuff .Now whats &? & sign is called ampersand it reserves memory for a variable for example when the following program asks to enter a numbers and you enter 2 and 6 these numbers will be hold in memory because of & sign its a pointer operator which points to a particular location in memory.. Whats a pointer ? We'll be discussing this later .... DECISION CONTROL !~~??~~! We have three statements for making and controling conditions and decisions: 1. if statement 2. if-else statement 3. Conditional Operators. Now lets discuss if statement.: It has the following general form: if (some condition) statements to b executed. What the keyword if does? If the condition in the if statement is true then the block of statements which are after the if statement are executed other wise if the condition is false then the program continues with other statements if any after the if statement... Now lets write a Program: include void main(){ int a; //variable a is declared printf("Enter a number"); //asks the user to input a number scanf("%d",&a); //inputs the number if (a==2) //checks the condition printf("You entered 2\n"); // if the condition is true then this is the output.. } I think this is self explanatory one thing here which is not defined so far is '==' operator .In mathematics we use = as equal sign but in C we will be using == for equality . '=' is used to assign a variable ,constant or other statement to a variable '!=' this is not equal to operator . || This is OR operator.. && And operator < greater <= greater than or equal >less than >= less than or equal *(We'll be discussing all these in our programs so dont worry just memorize it)* NOw lets this program even more complex #include void main(){ int a; printf("Enter a number="); scanf("%d",&a); if (a>=0 && a<=10) printf("The number you enter is between 0 and 10 \n"); } if (a>=0 && a<=10): this condition means that if the number is greater than or equal to 0 it means if its positive integer and it is less than or equal than 10 then execute the statement : printf("The number you enter is between 0 and 10 \n"); Okay now lets work with IF-ELSE statement: It has the following general form: if (condition) //statements else //statements if the condition is true in the if statement the body of the if statement will be executed othewise else statement will be executed.. Now lets make a program which discusses if-else #include void main(){ float temp; printf("Enter the temperature ="); scanf("%f",&temp); if (temp>30 && temp<50) printf("Its Hot !"); else printf("Its moderate"); } Now lets make use of Nested IF-ELSE statements: we'll write the above program more complex: #include void main(){ float temp; printf("Enter the temperature ="); scanf("%f",&temp); if (temp>30 && temp<50) printf("Its Hot !"); else if (temp>0 && temp <30) printf("Its cool"); else printf("Moderate"); } *TRY TO MAKE YOUR OWN PROGRAM LOGIC JUST GET SOME IDEA FROM THESE PROGRAMS .. LLLLLLOOOOOOOOOPPPPPPSSSSSS (loops); For Loop. While Loop. Do While Loop. For Loop> For loop is used whenever you want the iterations to be executed to a finite number of times . It has the following general form: for (exp1,exp2,exp3) exp1 is initialization here a variable is initialized . exp2 is condition . exp3 increment or decrement. for example: when we want to print numbers from 1 to 10 we will be using for loop as following: main(){ int i; //variable i declared for (i=1;i<=10;i++) printf("%d",i); } In the above program we have initialized i to 1 the condition is set to 10 and i is incremented by 1; i++: This is same as i+1.When we use i++ it means that it increments by one.If we want to increment by 2 then we will be using i=i+2. Example: Factorial of a number : If we want to find the factorial of a number we will write a program like the following: main(){ int fact=1,n; printf("Factorial Program "); printf("Enter a number :\n"); scanf("%d",&n); for (i=1;i<=n;i++){ fact=fact*i; } printf("Factorial =%d",fact); } The above program calculates the factorial of a number. TIP: we can also use for loop as following: int i=1; for (;i<=n;i++) or for (;i<=n; ;) i++; ............. While Loop: We use the while loop when we dont know the number of iterations... while(condition){ statements; } [*NOTE:We use { } whenever there are more than one statements so dont get confused *] For example if we want to print alphabets from A to Z. The following program will be used by us. main(){ char a='A'; while (a<='Z'){ printf("%c",a); //%c is used because we are outputting a character variable } } The Do while loop: The structure of the do...while loop is as follows: do statement while (condition); The statements associated with a do...while loop are always executed at least once. This is because the test condition is evaluated at the end, instead of the beginning, of the loop. In contrast, for loops and while loops evaluate the test condition at the start of the loop, so the associated statements are not executed at all if the test condition is initially false. The do...while loop is used less frequently than while and for loops. It is most appropriate when the statement(s) associated with the loop must be executed at least once. You could, of course, accomplish the same thing with a while loop by making sure that the test condition is true when execution first reaches the loop. A do...while loop probably would be more straightforward, however. Listing 6.5. A simple do...while loop. 1: /* Demonstrates a simple do...while statement */ 2: 3: #include 4: 5: int get_menu_choice( void ); 6: 7: main() 8: { 9: int choice; 10: 11: choice = get_menu_choice(); 12: 13: printf("You chose Menu Option %d\n", choice ); 14: 15: return 0; 16: } 17: 18: int get_menu_choice( void ) 19: { 20: int selection = 0; 21: 22: do 23: { 24: printf("\n" ); 25: printf("\n1 - Add a Record" ); 26: printf("\n2 - Change a record"); 27: printf("\n3 - Delete a record"); 28: printf("\n4 - Quit"); 29: printf("\n" ); 30: printf("\nEnter a selection: " ); 31: 32: scanf("%d", &selection ); 33: 34: }while ( selection < 1 || selection > 4 ); 35: 36: return selection; 37: } 1 - Add a Record 2 - Change a record 3 - Delete a record 4 - Quit Enter a selection: 8 1 - Add a Record 2 - Change a record 3 - Delete a record 4 - Quit Enter a selection: 4 You chose Menu Option 4 EXPLANATION: This program provides a menu with four choices. The user selects one of the four choices, and then the program prints the number selected. Programs later in this book use and expand on this concept. For now, you should be able to follow most of the listing. The main() function (lines 7 through 16) adds nothing to what you already know. Lines 18 through 37 contain get_menu_choice(). This function displays a menu on-screen (lines 24 through 30) and then gets a selection. Because you have to display a menu at least once to get an answer, it is appropriate to use a do...while loop. In the case of this program, the menu is displayed until a valid choice is entered. Line 34 contains the while part of the do...while statement and validates the value of the selection, appropriately named selection. If the value entered is not between 1 and 4, the menu is redisplayed, and the user is prompted for a new value. When a valid selection is entered, the program continues to line 36, which returns the value in the variable selection. Well thats all for now i told you in the begining its just a short tutorial for newbies who want to be started and i think you have done most of it. Also let me know if you want me to extend this tutorial. My Other tutorials that can be found on Ebcvg.com ,astalavista and hrvg.tk are wsh tutorial ,Aol Hacks and other geek stuff. =>TO ERROR IS HUMAN For Comments and Suggestions write to me: cyberghost4@hotmail.com NrAziz Bye!