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

C Programming

Introduction:
C is a procedural programming language developed in 1972 by Denis Ritchie at AT and Ts Bell Laboratory in USA.

Character Set:
o o o o o C uses the uppercase (A-Z) Lowercase (a-z) Digits(0-9) Special Symbols: - ~ ! @ # % ^ & * () _ - + = | \ { } [] : ; <> , . ? / White space, blank space, horizontal tab.

Keyword:
Keywords are reserved words in c that have predefined meaning. Keywords are in lower case, they can be used only for their intended purpose. E.g. for, do, int, if etc.

Identifiers:
Identifiers are the names given to various program elements such as variables, function etc. These are user defined names and consist of sequence of letters and digits. The first character of an identifier should always be a letter. Underscore (_) character may also be used. Upper & lowercase are distinct.

Constant:
A program elements that have fixed value in C i.e. value do not change during the executing of the program.

Basic Data Types:


Data types decide the amount of memory to be allocated to a variable to store particular types of data. The data types used in C are as follows: Integers (int):-It stores number value without any decimal point. The OS allocates 16 bits (2 bytes) to a variable that is declared to be of type int. Floating point (float):-It stores only numeric value with decimal point. It can hold the decimal point upto 6 digits. The variable that is declared to be of type float is allocated 4 bytes of memory. Double:-It stores only numeric value but the size is large than that of int and float. It can hold decimal point upto 10 digits. A variable declared of type double is allocated 8 bytes of memory. Character (char):- It stores only one character at a time. Its size is in bit. 1 char =1 Bit Boolean:-Besides text and numeric data, we also often come across logical data such as True and False. Such data is referred to as logical data. To be able to store this type of data, a variable needs to be declared of type Boolean. It occupies a space of 2 bytes.

Derived data types:


The data types which have been derived from basic data types are known as derived data types. There are three types of derived data types: Unsigned:-This data type can be used with the int data types. Declaring a variable using unsigned permits only positive numbers to be stored. It is declared as: unsigned int num; num=12345; 1

Short:-This data type can be used with int data type. It modifies the basic int data type so that it occupies less memory place. It occupies only 1 bytes space. Long:-This data type can be used with int as well as double data types. When it is used with int, it occupies 4 bytes and when used with double, it occupies 16 bytes space. It is declared as: long int num; or long double num;

Variable:
A variable is a named location in memory where a particular value is stored. Int Data type a Variable

Header Files in C Programming:


#include:-It is a preprocessor directives. Stdio:-Standard input output. Conio:-console input output.

Input output Statements:


Void main():-This line of the program indicates the point at which the working of the program begins. getch( ) / Getche( ):-Getch( ) and getche( ) wait for a keypress and the return . gets():-The gets function takes a string as its argument. puts( ):-Thes puts function takes a string as its argument and writes it on the screen. getchar ( ):-Reads a character from the keyboard; waits for carriage and then return. Clrscr( ):- Clear the screen. Printf( ):-Printf is used to print or display data on the console in a formatted form. It returns the number of characters written or a negative value if an error occurs. Scanf( ):- Scanf returns the number of data items which have successfully been assigned a value.

User Input and Output commands:


%d:- For integer input and output. %c:- For single character. %f:- For floating point value. %s:- For string. %ld:- For long integer. %lf:- For double.

Escape Characters:
Escape Characters are used with the printf( ). Escape Characters are specified in the first argument of the printf( ) and are used mainly for screen formatting of the output. The escape characters are always preceded with a backspace (\). \n =For new line \t = For horizontal tab. & =ampersand is address of operator or the location of the variable where the variable is stored. Program-1 #include<stdio.h> #include<conio.h> 2

void main() { printf(Welcome to C programming); getch(); } Program-2 The use of: \t:-tab, \n:-new line: #include<stdio.h> #include<conio.h> void main() { printf(My\t name\t is\t abc); printf(I Live in Nepal\n); }

Operator in C:
Operators are a set of symbols that help manipulate or perform some sort of function on data. Consider the following statement: A+B This would add the contents of the two variables A and B. The symbol + in the statement is called the operator and the variables on whom the operation is performed are called operands. The combination of the operands is known as an expression. Operators can be classified as: o Arithmetic Operators : + Plus Minus * Multiply / Divide % Modulus (To get the remainder) o Assignment Operators: = Equal to += Plus and Equal to -= Minus and Equal to *= Multiply and Equal to /= Divide and Equal to %= Modulus and Equal to o Comparison operators:1) > Greater than 2) < Less than 3) >= Greater and Equal to 4) <= Less and Equal to o Equality Operator:1) == Equal to 2)! = Not Equal to o Logical Operator:1) And (&&) 2) Or (or) 3) Not (!)

Hierarchy of operators (+,-,/,*,=):


1st priority:- *,/ 2nd priority:- +,3rd priority:- = Whenever we use the parenthesis() in any of the expression, it is evaluated in the beginning and the rest of the process takes place and if we have a block of parenthesis, the innermost block is evaluated first and then the outer one and then the next.

Conversion character:
They indicate the type of data item. %c:- string character %d:- integer %f:- floats %h:- short integer %s:- string %o:- octal integer %x:- hexadecimal. Program-1(i) #include<stdio.h> #include<conio.h> void main() { int n1,n2,res; n1=4; n2=6; res=n1+n2; printf(%d,res); //to show the value of n1 and n2,then printf(the addition of %d and %d is %d,n1n2,res); } Program-1(ii) Float n1,n2,res; N1=4.5; N2=5.5; Res=n1+n2; Printf(%f,res); } //To keep only 2 digits after decimal type Printf(%2f,res); //To get the result after executing type Getch(); //after printf. Program-2 #include<stdio.h> void main() { int a,b,c; 4

printf(Enter the first number : ); scanf(%d, &a); printf(Enter the second number: ); scanf(%d, &b); c=a+b; printf(The sum of numbers is %d ,c); } Program-3 #include<stdio.h> void main() { int a,b; a=5; b=a++; printf(value of b : %d,b); b=a; printf(value of b : %d,b); }

Control statements:
(1) Conditional statements. a) If else statement b) switch statement c) Continue statement d) Goto statement (2) Looping statement. a) For loop b) While loop c) do-while loop. If-else:In this conditional statement we compare the two or more in a single or multiple statement. If the condition is true it goes to the very first output statement otherwise it goes to else statement. If else if Statement:This is another common programming construct adapted from the initial if statement. If the condition is true, the statement evaluates and execute, and the rest of the ladder is bypassed. Example of if:#include<stdio.h> #include<conio.h> void main() { int num,i; clrscr(); printf("Enter a number"); scanf("%d",&num); i=num%2; if(i==0) { 5

printf(Even number!); } getch(); } Example of if-else:#include<stdio.h> #include<conio.h> void main() { int num,i; clrscr(); printf("Enter a number"); scanf("%d",&num); i=num%2; if(i==0) { printf(Even number!); } else { printf(Odd number!); } getch(); } Switch Statement:Switch is a multiple secession maker. In switch the conditions are applied in case statement. The case will be integer or character type not a float integer string type. Every case statement is terminate with break statement, Break also terminate the whole program. In switch there is a default case which is used to store default value. If all the conditions are false the default output will be display. Example: #include<stdio.h> #include<conio.h> void main() { int day; clrscr(); printf("Enter the days of a week:"); scanf("%d",&day); switch(day) { case 1: printf("Sunday"); break; case 2: printf("Monday"); break; case 3: printf("Tuesday"); break; 6

case 4: printf("Wednesday"); break; case 5: printf("Thursday"); break; case 6: printf("Friday"); break; case 7: printf("Saturday"); break; default: printf("Invalid day number!"); break; } getch(); } Looping Statement: A. For Loop:The For Loop continues to execute as long as the conditional test evaluates to true. When the condition becomes false the program comes out of the loop. There are three expressions in for loop. 1) Initialization 2) Condition 3) Increment or decrement operator. Increment 1) Postfix Increment: - First initialization than increment. 2) Prefix Increment: - First increment than initialization. Nested For Loop (1) Outer Loop: - First Loop. (2) Inner Loop: - Under First Loop. Example-1 #include<stdio.h> #include<conio.h> void main() { int i; clrscr(); for(i=1;i<=10;i++) { printf("%d\n",i); } getch(); } Example-2 #include<stdio.h> #include<conio.h> void main() 7

{ int a,b; for(a=1;a<=5;a++) { for(b=1;b<=a;b++) { printf("*"); } printf("\n"); } getch(); } B. While Loop:The while loop repeats a statement or a set of statements while a certain specified condition is true. Example: #include<stdio.h> #include<conio.h> void main() { int i; clrscr(); i=0; while(i<10) { i=i+1; printf("%d\n",i); } getch(); } C. Do-while loop:The do-while statement will execute a block of code at least once, then will repeat the loop as long as a condition is true. Example loop: #include<stdio.h> #include<conio.h> void main() { int i; clrscr(); i=0; do { i=i+1; printf("%d\n",i); } while(i<10); getch(); 8

Array:
An array is defined in the same way as a variable is defined, except that the array name is followed by one or more expressions, enclosed within square brackets [ ], specifying the array dimension. Array is a collection of same types of data in a single variable. In C there are three types of array: (1) One dimensional Array (2) Two dimensional Array (3) Multiple dimensional Array The most commonly used Array is one dimensional array. Array always starts with 0 (zero) index; means the first value of array is in the position of zero. Array declares with square bracket. We define the size of array is in square bracket. Example-1 #include<stdio.h> void main() { int a,b,e; char c[10],d[10]; clrscr(); printf("Enter your name : "); scanf("%s",&c); printf("Enter your address : "); scanf("%s",&d); printf("Enter your age : "); scanf("%d", &e); printf("Enter your roll no : "); scanf("%d", &a); printf("Enter your phone no : "); scanf("%d", &b); printf("Your name is :%s", c); printf("\nYour address is :%s", d); printf("\nYour phone is :%d", b); printf("\nYour age is :%d", e); printf("\nYour roll no is :%d", a); getch(); } Example-2 #include<stdio.h> #include<conio.h> void main() { float a, s=0; int i; int marks[5]; clrscr(); for(i=0;i<=4;i++) { printf("Enter the marks : "); scanf("%d", &marks[i]); 9

} for(i=0;i<=4;i++) s=s+marks[i]; a=s/5; printf("Total marks = %f",s); printf("\nAverage marks = %f", a); getch(); }

Pointer:
A pointer is a special type of variable because it doesnt store the values but the address of another variable. The pointer points the address of another variable. Pointer declaration: int *i; //defines i is a pointer to the integer. a[i] is equivalent to *[a+i]

Function in C:
A function is a self-contained program segment that carries out a specific, well defined task and used to break a large program into different parts to solve and find errors, read easily. There are two types of functions:1. User defined 2. Library / System. User defined function: 1. Function Declaration. 2. Function Call. 3. Function Definition. Library Function: There are three types of library functions:1) Mathematical Function. <math.h> 2) String function.<string.h> 3) Character Function.<ctype.h> Mathematical Function: (1) abs( ) :- Return absolute value. Only parameter in this function. (2) sqrt ( ):- Return square root. Only one parameter in this function. sqrt(a) (3) pow( ) :- Return the raised to the power. Two parameters in this function. (4) sin( ) :- Return the sin value. Only one parameter in this function. sin(a) String Function: (1) strcpy( ) :-Copy the value of one string of another string. (2) strcat( ) :-Concat the two string in a single string. (3) strlen( ) :- Find the total length of any string. (4) strcmp( ) :-compare the two string equal or not. (5) strupr( ) :- Convert lower case string to upper case. (6) strlwr( ) :- convert upper case string to lower case. Character Function: (1) isalpha( ) :-Check the given character is alphabet or not. (2) isdigit( ) :- Check the given character is digit or not. (3) Isalnum():- Check the given character is alphanumeric or not. (4) islower( ) :- check the given character is in lower case or not. (5) isupper( ) :-Check the given character is in upper case or not. (6) tolower( ) :- Convert upper case character to lower case character. 10

(7) Toupper() :-Convert lower case character to upper case character. Example-1 #include<stdio.h> #include<conio.h> int calsum(int x, int y, int z); void main() { int a,b,c,sum; clrscr(); printf("Enter any three numbers"); scanf("%d%d%d", &a,&b,&c); sum=calsum(a,b,c); printf("\n sum=%d", sum); getch(); } int calsum(int x,int y,int z) { int d; d=x+y+z; return(d); } Example-2 #include<stdio.h> #include<conio.h> void main() { int a; a=30; clrscr(); fun(a); printf("%d",a); getch(); } fun(b) int b; { b=60; printf("%d\n", b); return 0; }

Structure in C:
Structure is collections of variables of different data types that can be accessed as one unit using a common name. To define any structure we use a struct keyword. In structure keyword we can define all variables if the variables are declare within structure these structure call by an object which is the reference of structure. To call the structure in program we use dot [.] operator. Declaring structure: 11

struct anyname { int anyname; char anyname; } Example: #include<stdio.h> #include<conio.h> struct rectangle { int length; int breadth; }; struct rectangle rect; void main() { int area; clrscr(); printf("Enter length:"); scanf("%d",&rect.length); printf("\nEnter breadth:"); scanf("%d",&rect.breadth); area=rect.length*rect.breadth; printf("The area is:%d",area); getch(); }

12

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