Вы находитесь на странице: 1из 16

IP University C Programming UNIT - I

A character Set
A character denotes any alphabet ,digit or symbols to represent information. The following are the valid alphabets, numbers and special symbols permitted in C Numerals: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

Alphabets: a, b, .z
A, B, ...Z

Arithmetic Operations: +, -, *, /, %(Mod) Special Characters:

( = \

) ! blank

{ $ & -

} ? | _

[ . ^ /

] , ~ *

< : ` %

> ; # @

Identifiers
"Identifiers" or "symbols" are the names you supply for variables, types, functions, and labels in your program. Identifier names must differ in spelling and case from any keywords. You cannot use keywords (either C or Microsoft) as identifiers; they are reserved for special use. You create an identifier by specifying it in the declaration of a variable, type, or function. In this example, result is an identifier for an integer variable, and main and printf are identifier names for functions.
#include <stdio.h> int main() { int result; if ( result != 0 ) printf_s( "Bad file handle\n" ); }

Once declared, you can use the identifier in later program statements to refer to the associated value.

C Keywords
C makes use of only 32 keywords or reserved words which combine with the formal syntax to the form the C programming language. Note that all keywords in C are written in lower case. A keyword may not be used as a variable name. auto break case char const double else enum extern float int long register return short signed sizeof static struct switch typedef union unsigned void volatile while

continue for default do goto if

Data Types
C has different data types for different types of data and can be broadly classified as : 1. Primary data types 2. Secondary data types Primary data types consist following data types.

Data Types in C

Integer types:
Integers are whole numbers with a range of -32768 to +32767 values. Generally an integer occupies 2 bytes memory space. C has three classes of integer storage namely short int, int and long int. All three data types have signed and unsigned forms. A short int requires half the amount of storage than normal integer. Unlike signed integer, unsigned integers are always positive. Therefore the range of an unsigned integer will be from 0 to 65535. The long integers are used to declare a longer range of values and it occupies 4 bytes of storage space. Syntax: int <variable name>; like int num1; short int num2; long int num3; Example: 5, 6, 100, 2500.

Integer Data Type Memory Allocation

Floating Point Types:


The float data type is used to store fractional numbers (real numbers) with 6 digits of precision. Floating point numbers are denoted by the keyword float. When the accuracy of the floating point number is insufficient, we can use the double to define the number. The double is same as float but with longer precision and takes double space

(8 bytes) than float. To extend the precision further we can use long double which occupies 10 bytes of memory space. Syntax: float <variable name>; like float num1; double num2; long double num3; Example: 9.125, 3.1254.

Floating Point Data Type Memory Allocation

Character Type:
Character type variable can hold a single character. As there are singed and unsigned int (either short or long), in the same way there are signed and unsigned chars; both occupy 1 byte each, but having different ranges. Unsigned characters have values between 0 and 255, signed characters have values from 128 to 127. Syntax: char <variable name>; like char ch = a; Example: a, b, g, S, j.

Void Type:
The void type has no values therefore we cannot declare it as variable as we did in case of integer and float. The void data type is usually used with function to specify its type.

Secondary Data Types

Array in C programming An array in C language is a collection of similar data-type, means an array can hold value of a particular data type for which it has been declared. Arrays can be created from any of the C data-types int,... Pointers in C Programming A pointer is a special kind of variable. Pointers are designed for storing memory address i.e. the address of another variable. Declaring a pointer is the same as declaring a normal variable except you stick an asterisk '*' in front of the variables identifier. Following is the example how to define a Pointer variable

int a =45; int *ptr; ptr = &a;

Structure in C Programming A structure in C is a collection of items of different types.


Simply you can group various built-in data types into a structure. Object conepts was derived from Structure concept. You can achieve few object oriented goals using C structure but it is very complex.

Following is the example how to define a structure.


struct student { char firstName[20]; char lastName[20]; char SSN[9]; float gpa; };

Now you have a new datatype called student and you can use this datatype define your variables of student type:

Vairable
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. The Programming language C has two main variable types

Local Variables Global Variables

Local Variables

Local variables scope is confined within the block or function where it is defined. Local variables must always be defined at the top of a block. When a local variable is defined - it is not initalised by the system, you must initalise it yourself. When execution of the block starts the variable is available, and when the block ends the variable 'dies'.

Check following example's output


main() { int i=4; int j=10; i++; if (j > 0) { /* i defined in 'main' can be seen */ printf("i is %d\n",i); } if (j > 0) { /* 'i' is defined and so local to this block */ int i=100; printf("i is %d\n",i); }/* 'i' (value 100) dies here */ printf("i is %d\n",i); /* 'i' (value 5) is now visable.*/ } This i is i is i is will generate following output 5 100 5

Here ++ is called incremental operator and it increase the value of any integer variable by 1. Thus i++ is equivalent to i = i + 1; You will see -- operator also which is called decremental operator and it idecrease the value of any integer variable by 1. Thus i-- is equivalent to i = i - 1;

Global Variables
Global variable is defined at the top of the program file and it can be visible and modified by any function that may reference it. Global variables are initialized automatically by the system when you define them! Data Type int char float pointer Initialzer 0 '\0' 0 NULL

If same variable name is being used for global and local variable then local variable takes preference in its scope. But it is not a good practice to use global variables and local variables with the same name.
int i=4; /* Global definition */

main() { i++; /* Global variable */ func(); printf( "Value of i = %d -- main function\n", i ); } func() { int i=10; /* Local definition */ i++; /* Local variable */ printf( "Value of i = %d -- func() function\n", i ); } This will produce following result Value of i = 11 -- func() function Value of i = 5 -- main function

i in main function is global and will be incremented to 5. i in func is internal and will be incremented to 11. When control returns to main the internal variable will die and and any reference to i will be to the global.

What is the difference between logical and relational operators?


Logical operators don't Compare values they combine Boolean values and produce a Boolean result. Examples of logical operators are && (and), ||, (or), ! (not). If you have two Boolean values and you combined them with the && operator the result will be (TRUE) only if both values were (TRUE). If you combined them with the || operator the result will be TRUE if any of them or both of them were TRUE. Relational operators compare two values and produce a Boolean result. Most of the time we use logical operators to combine the results of two or more comparison expressions that use relational operators. For instance we may say: If( a > b && a <= c) { do something} This means that if both expressions a>b AND a <= c are TRUE the result will be true and the body of the if statement will be executed.

FLOW CONTROL
C provides two sytles of flow control:

Branching Looping

Branching is deciding what actions to take and looping is deciding how many times to take a certain action.

Branching:
Branching is so called because the program chooses to follow one branch or another.

if statement
This is the most simple form of the branching statements.

It takes an expression in parenthesis and an statement or block of statements. if the expression is true then the statement or block of statements gets executed otherwise these statements are skipped. NOTE: Expression will be assumed to be true if its evaulated values is non-zero. if statements take the following form:
if (expression) statement1; else statement2;

else-if statement
In an else if ladder the conditions are evaluated from the top of the ladder. As soon as match is found in else if ladder, the true block associated with the condition is executed and the control leaves the else if ladder and executes the statement following the ladder. #include <stdio.h> main() { int cows = 6; if (cows > 1) printf("We have cows\n"); if (cows > 10) printf("loads of them!\n"); else printf("Executing else part...!\n"); if (cows == 5 ) { printf("We have 5 cows\n"); } else if( (cows == 6 ) { printf("We have 6 cows\n"); } }

This will produce following result:


We have cows Executing else part...! We have 6 cows

Nested if-elses

It is perfectly all right if we write an entire if-else construct within either the body of the if statement or the body of an else statement. This is called nestingof ifs. This is shown in the following program. /* A quick demo of nested if-else */ main( ) { int i ;

printf ( "Enter either 1 or 2 " ) ; scanf ( "%d", &i ) ; if ( i == 1 ) printf ( "You would go to heaven !" ) ; else { if ( i == 2 ) printf ( "Hell was created with you in mind" ) ; else printf ( "How about mother earth !" ) ; } } 62

Let Us C

Note that the second if-else construct is nested in the first else statement. If the condition in the first if statement is false, then the condition in the second if statement is checked. If it is false as well, then the final else statement is executed. You can see in the program how each time a if-else construct is nested within another if-else construct, it is also indented to add clarity to the program.

The Conditional Operators


The conditional operators ? and : are sometimes called ternary operators since they take three arguments. In fact, they form a kind of foreshortened if-then-else. Their general form is, expression 1 ? expression 2 : expression 3 What this expression says is: if expression 1 is true (that is, if its value is non-zero), then the value returned will be expression 2, otherwise the value returned will be expression 3. Let us understand this with the help of a few examples: (a) int x, y ; scanf ( "%d", &x ) ; y=(x>5?3:4); This statement will store 3 in y if x is greater than 5, otherwise it will store 4 in y.

LOOPS
Loops provide a way to repeat commands and control how many times they are repeated. C provides a number of looping way.

while loop
The most basic loop in C is the while loop.A while statement is like a repeating if statement. Like an If statement, if the test condition is true: the statments get executed. The difference is that after the statements have been executed, the test condition is checked again. If it is still true the statements get executed again.This cycle repeats until the test condition evaluates to false. Basic syntax of while loop is as follows:

Example
while ( expression ) { Single statement or Block of statements; }

Example:
#include <stdio.h> main() { int i = 10; while ( i > 0 ) { printf("Hello %d\n", i ); i = i -1; } }

This will produce following output:


Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello 10 9 8 7 6 5 4 3 2 1

for loop
for loop is similar to while, it's just written differently. for statements are often used to proccess lists such a range of numbers: Basic syntax of for loop is as follows:
for( expression1; expression2; expression3) { Single statement or Block of statements; }

In the above syntax:

expression1 - Initialisese variables. expression2 - Condtional expression, as long as this condition is true, loop will keep executing. expression3 - expression3 is the modifier which may be simple increment of a variable.

#include <stdio.h> main() { int i; int j = 10; for( i = 0; i <= j; i ++ ) { printf("Hello %d\n", i ); } }

This will produce following output:


Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello 0 1 2 3 4 5 6 7 8 9 10

do...while loop
do ... while is just like a while loop except that the test condition is checked at the end of the loop rather than the start. This has the effect that the content of the loop are always executed at least once. Basic syntax of do...while loop is as follows: Example
do { Single statement or Block of statements; }while(expression); #include <stdio.h> main() { int i = 10;

do{

printf("Hello %d\n", i ); i = i -1; }while ( i > 0 ); }

This will produce following output:


Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello 10 9 8 7 6 5 4 3 2 1

switch Statement
switch is a selection statement provided by C. It has a buil in multiple - branch structure and work similar to if else ladder generally. The input value to to the switch statemetnt construct is a int or char variable. Note that no float or any other data is allowed. This input variable is compared against a group of integer constant. All the statments in and after the case in which thier is a match is executed until a break statement is encountered or end of switch is reached. We are also allowed to give a default case which will be executed if no other statement match is found. Also use of standard indenting is recommended. General representation of switch in C can be switch (input) { case constant1 : statement1; break; case constant2 : statement2; break; case constant3 : statement3; break; . . . . ... n cases case constant n+1 : statement n+1; break; case default : statement n+2; break;

It is defined by C that a compiler must support a minmum of 257 case statements in C89 and 1023 case statements in C99 though you may want to keep this to minimum in consideration of efficiency. Common use of switch is in for menus and other selection interfaces. Also break in the switch statements is optional and if no break is present in a case the flow of statements transfer to next case and so on till the break statement is encountered or switch case ends.
#include <stdio.h> int main (void) { char ch; printf ("\nEnter Character A,B or C: "); ch = getchar (); switch (ch) { case 'A' : printf ("You Entered A"); break; case 'B' : printf ("You Entered B"); break; case 'C' : printf ("You Entered C"); break; default : printf ("You Didnot Entered A, B or C"); } return 0; }

JUMP Statements There are four jump statements available in C. return goto break continue return Statement return is a jump statement in c. It is used to return from the executing function to the function which called this executing function. Return statement also has a special property that it can return a value with it to the calling function if the fuunction is declared non - void. Void functions are the one which are explicitly declared not to return a value and hence a return statement with value when encountered in such a function leads to an error by compiler. Also a function declared non-void should always return a value of the respective type. General form of return statement is return expression; In such a statement the value of the expression is returned. Value can also be explicitly mentioned making a function always return a fixed constant value.

Return will discussd in greater detail in further tutorials specially one explaining functions. Following Code shows return statment in action #include <stdio.h> int function (void) { int b; b = scanf ("%d", &b); return b; // returns the value of b to the calling function. } int main () { printf ("\n%d", function ()); return 0; }

goto Statement Goto is used for jumping from one point to another point in your function. You can not jump from one function to another. Jump points or way points for goto are marked by label statements. Label statement can be anywhere in the function above or below the goto statement. Special situation in which goto find use is deeply nested loops or if - else ladders. General form of goto statement is . . . goto label1; . . . . label1 : . . . label2 : . . . . goto label2;

EXAMPLE #include <stdio.h> int main (void)// Print value 0 to 9 { a = 1; loop:; // label stament printf ("\n%d",a); a++; if (a < 10) goto loop ; // jump statement retrun 0; } break Statement break statment is a jump statment in C and is generally used for breaking from a loop or breaking from a case as discussed in switch stament. Break statement when encountered within a loop immediately terminates the loop by passing condition check and execution transfer to the first statment after the loop. In case of switch it terminates the flow of control from one case to another. Also one important thing to remember about break is that it terminates only the innermost switch or loop construct in case of nested switch and loop variations. The C source code below shows an simple application of break statement#include <stdio.h> int main () { for (int i = 0; i<100; i++) { printf ("\n%d", i); if (i == 10); // This code prints value only upto 10. break; } return 0; } continue Statement continue is a jump statement provided by C. It is analogus to break statement. Unlike break which breaks the loop, continue stament forces the next execution of loop bypassing any code in between.

For for staments it causes the conditional check and increment of loop variable, for while and do-while it passes the control to the conditon check jumping all the statements in between. Continue plays an important role in efficiently applying certain algorithms. Below is a C source code showing the application of continue statement #include <stdio.h> int main () { for (int i = 0; i<100; i++) { if (i == 10); // This code prints value only upto 9 even though loop executes 100 times. continue ; printf ("\n%d", i); } return 0; }

Вам также может понравиться