Anda di halaman 1dari 13

C-Programming Tutorial 1.

INTRODUCTION AND BASICS OF C Introduction to C C compiler

2. C LANGUAGE PRELIMINARIES
Constants and Variables Datatypes in C Modifiers and Keywords

3.INPUT AND OUTPUT FUNCTIONS printf scanf 4. OPERATORS Assignment Arithmetic Type Casting Relational operators +Operators- Arithmetic operators, +Expressions and statements 3. Input and output functions +printf and scanf + getchar() and putchar()------------ in advanced + puts and gets --------------------- advanced 3. Know your operators + Assignment, Arithmatic, Relational, Logical operators, Unary,Conditional,bitwise + Sizeof operator, Typecasting + Logical operators + Operator precedence 4. Control statements-----------------by pavan + If + If else +for +while +do while + switch +case+break+contine+goto +nested loops 5. Functions------------------------------------by sudarshan 6. Advanced +input-outpt advanced : getchar() and putchar()------------ in advanced + puts and gets --------------------- advanced +Arrays+Pointers +Pre-processor commands +Strings +structres,unions,enum +storage types + File structure and handling

INTRODUCTION AND BASICS OF C Introduction to C

C is a High-level programming language which contains set of statements with each having their own syntactical(grammatical) rules. High level programming language provides ease to programmer in writing the programs Lets start with a basic program,to see how C program looks like : Example 1 - C hello world program #include <stdio.h> Pre-processor command void main() Starting point of the program always { printf("Hello World"); Prints hello on screen } Output Hello World

#include<stdio.h> commands are always the first statement of a C program and are called as Pre-processor commands. Pre-processor commands are built-in library functions which are already available. We will discss Pre-processor commands in detail later. Main() : Main method is the starting point of the C program from where its execution begins.Every C program gets executed right from main() method or function. The round braces () indicates that main is a function. All functions are always enclosed in { } braces. Opening brace '{' indicates start of function where closing brace '}' indicates end of function. NOTE :-'void' is a reserved keyword and is return-type of the function. A function name is always preceded by its return-type. Return type is the type of data that will be returned by function.'void' here means, there is no nothing to return. We will discuss in brief about Functions in later topic. Printf() : printf() is a built-in output function, used to print the output to the screen. Whatever is written in printf () function, system will display that on Output screen. As you can see Hello world is get displayed on Output screen in Example 1

Note:-Each and every statement need a semicolon(;) at the end as just like full stop(.) in our general lauguage

C compiler

To run the C program we have to compile it first, with the Compiler. Compiler will translate source program into machine code which can be executed directly on machine. C programs are compiled into binary code with compilers and then executed. The different files you will come through in C are : Source code file : It is where your program statements go in and they are with an extension '.c' . Object code file : After we compile the program ,we generate a binary code format which then can be executed , they are with '.o' or '.obj' extension. Header file : They are built-in standard fnctions (eg. preprocessor commands) with extension '.h' as their extension. For eg. Stdio.h, math.h . We will discuss on this in brief later on.

C LANGUAGE PRELIMINARIES
In this section we will discuss the need of the variables and constants , for building the programming statements. Similar to learning a language we need to know, about the alphabets, then we can create words and then sentences and then into paragraphs. Similararly, in C, we need to know what are variables and constants , to create instructions in the program. Constants : A "constant" is a number, character, or character string that can be used as a value in a program. Use constants to represent floating-point, integer, enumeration, or character values that cannot be modified . For eg. Integer constants as : 23,567,-90 . Character constants as : 'A','g','#' . Variables : A variable is just a named area of storage that can hold a single value (numeric or character). The C language demands that you declare the name of each variable that you are going to use and its type, or class, before you actually try to do anything with it otherwise C compiler wouldn't recognise the variable. Variable names are case sensitive. Once you declare a variable, a memory is allocated to that variable according to its datatype , that we will discuss in next section. General syntax of creating a variable : data-type variable-name; eg. int counter; char ch; 'type is datatype we will discss frther in the section. 'variable-name' is the name given by programmer, and should be chosen carefully so that the are identifiable. The name can contain letters, digits and the underscore but the first letter has to be a letter or the underscore (_). However you should avoid using underscore as the first letter because the variable name can be clashed with standard system variables. The length of name can be up to 247 characters but 31 characters are usually adequate. There are some words that reserved as keywords therefore you cannot use it as variable name.

Datatypes in C : C has a concept of 'data types' which are used to define a variable before its use. The definition of a variable will assign storage for the variable and define the type of data that will be held in the location. The value of a variable can be changed any time. C has the following basic built-in datatypes: int float double char

int - data type int is used to define integer numbers. Syntax : { int abc; abc = 5; }

float - data type float is used to define floating point numbers. Syntax : { float f; f = 5.6; } double - data type double is used to define BIG floating point numbers. It reserves twice the storage for the number. On PCs this is 8 bytes. Syntax : { double d; d = 2500000; }

char - data type char defines characters. Syntax : { char character; character = 'x'; }

Modifiers : The three data types above have the following modifiers. short long signed unsigned

The modifiers define the amount of storage allocated to the variable. The amount of storage allocated is not cast in stone. ANSI has the following rules: short int float <= int <= long int <= double <= long double

What this means is that a 'short int' should assign less than or the same amount of storage as an 'int' and the 'int' should be less or the same bytes than a 'long int'. What this means in the real world is: Type unsigned short int int long int signed char unsigned char float double Long double Bytes 2 2 Bits 16 Range 0 -> +65,535 (32Kb)

2 16 0 -> +65,535 (32Kb) unsigned int 4 16 0 -> +4,294,967,295 ( 4Gb) int 4 32 -2,147,483,648 -> +2,147,483,647 ( 2Gb) long int 4 32 -2,147,483,648 -> +2,147,483,647 ( 2Gb) signed char 1 8 -128 -> +127 unsigned char 1 8 0 -> +255 float 4 32 double 8 64 long double 12 96

Keywords : "Keywords" are words that have special meaning to the C compiler. There are 32 kewords in C. The C language uses the following keywords: auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while

Note : One cannot use above reserved keywords for variables or functions name PROGRAM EXAMPLE FOR VARIABLES.... INPUT AND OUTPUT FUNCTIONS : In this section, we will learn the methods, as how the user can enter the data and how it can be used to generate output for the program.There is need of standard input and output functions to accept the user data and output the data. C provides with two inbuilt functions printf() - used to print the data to the screen and scanf() - to accept the data from the user. printf() : This is an in-built function which gives structured output to the screen. The general format of the printf is as follows : printf(format string,list of variables); First parameter : Format string : Also called as format specification string, it contains characters after the '%' sign . This characters are called as concersion characters, and varies for the datatype. The following table indicates the information for conversion characters : Conversion character

Description Used to display integer data Used to display character data Used to display string data

d c s

Used to display float data

In addition to the above data, Escape characters can be used with the printf function. We will let you know the most useful ones : \n : It is used to enter the newline in the output. That is to take the output to the next line. \t : It gives a tab space on the line. A SAMPLE PROGRAM FOR PRINTF

#include<stdio.h> void main (){ printf (\t WELCOME TO BOOK STORE \n) printf(------------------------------------------------------------) printf(\n Number of books = 3); printf(\n Cost of books = 1230.56 ); } OUTPUT OF PROGRAM : WELCOME TO BOOK STORE -----------------------------------------------------------Number of books = 3 Cost of books = Rs. 1230.56

Scanf () : To accept the input from the screen scanf() fnction is used. There are numerous instances where the program needs some input from the user , and hence the need of the function scanf(). General form of scanf function is : scanf( format of string ,list of addresses of variables); The first parameter, in the scanf function is similar to the one we discussed in the previous section. The second paramter, i.e list of addresses of variables , as it says, it is used to store the variables in the memory location or at a particular address. Now this address can be obtained with the help of '&' (ampersand sign) before the name of the variable.

Eg. Syntax : scanf(%d,&a);

A SAMPLE PROGRAM FOR SCANF : For example to accept a integer data from user : int a; printf(Enter the integer :); scanf(%d,&a); printf(\n Value of a :); printf(%d,a); printf(\n Address of the variable 'a' :\n); printf(%d,&a); Output : Enter the integer : 5 Value of a : 5 Address of the variable 'a' : 1010 a --------------> variable 5 1010-------------->address of variable The address assigned to the variable is not permanent, it would vary everytime you compile and execute the program, this is done by the OS according to the availablility of memory location.

A DETAILED PROGRAM FOR SCANF AND PRINTF

There are more input and output functions which are seldom used. Hence we have moved this to the advaned section. We have given details about the following functions in the advanced part : putchar() , getchar (), puts() , gets().

OPERATORS Now as we know, about variable and constants, lets move ahead with creating expressions. You will come across instances where you need to create expression in the programs. For example., consider the following expression : a) quantity > 200 b) sum = number1 + number2 The symbols in the above expressions '+', '=' and '>' are called 'operators' and the variables and constants which work on them are called as 'operands',i.e. quantity , sum, number1 and number2 are operands. Operators are meaningful symbols that bind two or more operands in an expression. In the above said example : sum = number1 + number2 Expression here results a value which is stored in another variable. i.e number1 + number2 are added together and their added value is stored in 'sum'. Sometimes, expression can just be a condition statement, where it does not return a value. It may result in a boolean value that can be either true or false. We will discuss it in detail this section, regarding all the operators that come in C. Assignement Operator : Assignement operator is used to assign a value to a variable and its symbol is '=' . Syntax : variable = expression ; variable is any variable name or identifier. expression is can be a constant or a valid expression Example : int volume = 100; float length = 10.6; char car = 'y'; SAMPLE PROGRAM : #include<stdio.h> void main () { float cost = 1230.56; int number_of_books = 3; printf(\n Number of books = %d, number_of_books); printf(\n Cost of books = Rs. %f , cost); } In the above program, we have declared two variable. Integer variable number_of_books and float variable cost. And assigned value to them via assignment operator '=' . And we are giving an output to the screen with the printf() function. OUTPUT OF PROGRAM : Number of books = 3

Cost of books = Rs. 1230.56

Arithmetic Operators: Arithmetic operators supported by C language are as follows : Assume variable A holds value 10 and variable B holds value 20 then:

Operator + * / %

Description Adds two operands Subtracts second operand from the first Multiply both operands Divide numerator by denumerator Modulus Operator ,results remainder of after an integer division A + B will give 30

Example

A - B will give -10 A * B will give 200 B / A will give 2(quotient) B % A will give 0(remainnder)

Lets understand them better by programmin example :


#includes<stdio.h> void main() { int a = 41; int b = 10; int c ; c = a + b; printf(" a c = a - b; printf(" a c = a * b; printf(" a c = a / b; printf(" a c = a % b; printf(" a

+ b - Value of c is %d\n", c ); - b - Value of c is %d\n", c ); * b - Value of c is %d\n", c ); / b - Value of c is %d\n", c ); % b - Value of c is %d\n", c );

OUTPUT OF THE PROGRAM :


a a a a a + * / % b b b b b Value Value Value Value Value of of of of of c c c c c is is is is is 51 31 410 4 1

Type Casting : Typecasting is making a variable of one type, such as an int, act like another type, a float, for one single operation. To typecast something, simply put the type of variable you want the actual variable to act as inside parentheses in front of the actual variable.

For eg. int a (float)a , will make the variable 'a' act as float despite declaring 'a' as integer. One use of typecasts is to force the correct type of mathematical operation to take place. In C (and other programming languages), the result of the division of integers is itself treated as an integer. For instance, 4/5 becomes 0. Because 4/5 is less than 1, and integer division ignores the remainder. On the other hand, it turns out that division between two floating point numbers, or even between one floating point number and another an integer, is sufficient to keep the result as a floating point number. For eg. 4.0/5 or 4.0/5.0 will result in 0.8 . So if we were performing a division as above said 4/5 and you want the result not to be truncated or in a floating point value , you can do the following to store the result in float. For instance, (float)(4/5) would result in 0.8 as expected. The below examples, would helpful to understand in better :
#includes<stdio.h> void main() { int a = 41; int b = 10; float c ;

float d ;

c = a / b; printf(" a / b - Value of c is %f\n", c ); d = (float)(a / b); printf(" (float)(a / b) - Value of d is %f\n", d ); }

OUTPUT OF THE PROGRAM :


a / b - Value of c is 4 (float)(a / b) - Value of d is 4.1

Relational operators : Relational operators are symbols which test the relationship between the two operands, where operands may be variable , constant or an expression, which results in a boolean value true or false. Relational operators are useful in creating conditional expressions and also in iterations. The following table describes the relational operators : Assume variable A holds 10 and variable B holds 20 then:

Operator == !=

Description Checks if the value of two operands is equal or not, if yes then condition becomes true. Checks if the value of two operands is equal or not, if values are not equal then condition

Example (A == B) is not true. (A != B) is true.

becomes true. > Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (A > B) is not true.

<

(A < B) is true.

>=

(A >= B) is not true.

<=

(A <= B) is true.

Using operators in conditional statements Logical operators Operator precedenc

Anda mungkin juga menyukai