Sunteți pe pagina 1din 56

C Language

Overview of C
C is developed by Dennis Ritchie C is a structured programming language C supports functions that enables easy maintainability of code, by breaking large file into smaller modules Comments in C provides easy readability C is a powerful language

Overview of C
 The original PDP-11 version of the Unix system was developed in assembly language.  In 1973, C language had become powerful enough that most of the Unix kernel was rewritten in C.  C spread throughout many colleges and universities because of its close ties to UNIX and the availability of C compilers.  C is the most widely used System Programming Language.

Program Structure
A Sample C Program #include <stdio.h> int main() { printf(Hello world\n); }

Output

Hello World

Header File
 #include <stdio.h>
The files that are specified in the include section is called as header file These are precompiled files that has some functions defined in them We can call those functions in our program by supplying parameters Header file is given an extension .h C Source file is given an extension .c

Main Function
 int main()
This is the entry point of a program When a file is executed, the start point is the main function From main function the flow goes as per the programmers choice. There may or may not be other functions written by user in a program Main function is compulsory for any c program

Main Function
 {
 open brackts is starting line of the main function. Close brackts is ending line of the main function.

 }

printf - function
 printf(Hello World\n);
Print the value present inside the .

;
All the statement should end with ; except some places.

Running a C program
 Type a program  Save it  Compile the program This will generate an exe file (executable)  Run the program (Actually the exe created out of compilation will run and not the .c file)  In different compiler we have different option for compiling and running. We give only the concepts.

Comments in C
Single line comment
// (double slash) Termination of comment is by pressing enter key

Multi line comment


/*. .*/ This can span over to multiple lines

Data Types in C
Name char small int Description character Short integer Size ( byte) Range 1 2 -128 to + 127 0 to 255 32768 to 32767 0 to 65535 long int Long integer 4
-2147483648 to 2147483647

0 to 4294967295

bool Float double

Boolean value Floating point integer Double precision floating point number

1 4 8

true or false

Variables
 Variables are data that will keep changing.  In any program we typically do lots of calculations.  The results of these calculations are stored in computer memory locations.  To make the retrieval and usage of these values we give names to the memory locations.  These names are called variables.

Variable Declaration.
Var_type(data type) list of variables. Example:
 Int I, j, k;  char answer  m = 10;
m Computer memory name

Memory value

10

Variable names- Rules


Should not be a reserved word like int etc.. Should start with a letter or an underscore(_) Can contain letters, numbers or underscore. No other special characters are allowed including space Variable names are case sensitive
A and a are different.

Types of Variables
 Numeric variables that hold numbers.  int a;  a = 100;  String variables that hold only text. One to many characters long.  char name[25];
Name = Ravi;

example02.c
#include <stdio.h> main() {
} // Variable declaration Int age; // assignment statement age = 25; // printstatement printf(My age is %d\n,age);

output
My age is 26

Input and Output


Input
scanf(%d,&a); Gets an integer value from the user and stores it under the name a

Output
printf(%d,a) Prints the value present in variable a on the screen

Arrays
 Arrays fall under aggregate data type  Aggregate More than 1  Arrays are collection of data that belong to same data type  Arrays are collection of homogeneous data  Array elements can be accessed by its position in the array called as index  0 1 2 3 4 5 6 7

Arrays
 Array index starts with zero  The last index in an array is num 1 where num is the no of elements in a array  int a[5] is an array that stores 5 integers  a[0] is the first element where as a[4] is the fifth element  We can also have arrays with more than one dimension  float a[5][5] is a two dimensional array. It can store 5x5 = 25 floating point numbers  The bounds are a[0][0] to a[4][4]

Arithmetic Operators
No. 1 2 3 4 5 6 7 8 Operator * / + = ++ -% Descriptions multiplication division Addition Subtraction Assignment Increment Decrement modulus

Arithmetic operator
 The ++ and operators can b either in postfixed or pre-fixed.  ++a With pre-fixed the value is computed before the expression is evaluated.  b++ whereas with post-fixed the value is computed after the expression is evaluated.

Example03.c
 #include <stdio.h>  main() {  Int I,j,k,l,m,n, z;  float fresult01, fresult02;  I = 10;  j = 20;  k = 30;  l = 40;  m = I + j;  n = I - j;  o = k * l;  fresult01 = m / k;  z = k % j;

 Printf(value of m=%d,n=%d,o=%d,result01=%f, z=%d,m,n,o,result01,z); }

example04.c
 #include <stdio.h>  main() {
 Int I,j,k;  I = 10;  j = 20;  k = 30;  I = I + 1;  ++j; k++; printf(Value of I,j,k is %d,%d,%d\n,I,j,k);

}

Comparison Operator
No. 1 2 3 4 5 6 Symbol == != < > <= >= Description equal Not equal Less than Greater than Less than equal Greater than equal

if Statement
 if statement has a same function like other languages.  It has three basic forms.

if ( expression ) { statement; }

If statement with else

if( expression ) { Statement-1;}  else { Statement-2;}

If Statement

if(expression) { Statement-1;} else if ( expression) { Statement-2;} else { statement3;}

String functions
 strlen(str) To find length of string str  strrev(str) Reverses the string str as rts  strcat(str1,str2) Appends str2 to str1 and returns str1  strcpy(st1,st2) copies the content of st2 to st1  strcmp(s1,s2) Compares the two string s1 and s2  strcmpi(s1,s2) Case insensitive comparison of strings

The ? Operator
 The ? (ternary condition) operator is a more efficient form for expressing simple if statements. It has the following form

expression1 ? expression2: expression3  big = ( a > b )?a:b If ( a > b ) big = a; else big = b;

Logical Operator
No 1 2 Symbol && || Description AND operator OR operator

Logical operators are usually used with conditional statements

The switch statement


 the C switch is similar to Pascal's case statement.  it allows multiple choice of a selection of items at one level of a conditional.  it is a far neater way of writing multiple if statements:

Switch Statement format


 switch( expression) {
 case item1:
 Statement1;  break;

 case item2:
 Statement2;  break;

 default:
 Statement3;  break;

}

Switch Statement
 In each case the value of itemi must be a constant, variables are not allowed .  The break is needed if you want to terminate the switch after execution of one choice. Otherwise the next case would get evaluated.  The default case is optional and catches any other cases

Switch statement
We can also have null statements by just including a ; or let the switch statement fall through by omitting any statements .

example
 switch (letter)  { case `A':  case `E':  case `I':  case `O':  case `U':
 numberofvowels++;  break;

case ` ':
 numberofspaces++;  break;

 }

default:
 numberofconstants++;  break;

For Loops
 The syntax of for loop is
for(initialisation;condition checking;increment) { set of statements } Eg: Program to print Hello 10 times #include <stdio.h> Main() { int I; for(I=0;I<10;I++) { printf(Hello); } }

Assignment
1.Write a program to accept your name and print the name in the reverse order by using FOR . 2.write a program to accept your name and convert the name from lowercase to upper case by using FOR.

While Loop
 The syntax for while loop while(condn) { statements; } Eg: #include <stdio.h> main() { int a; a=10; while(a != 0) { printf(%d,a); a--; } }

Output: 10987654321

Assignment
1.Write a program to accept your name and print the name in the reverse order by using WHILE . 2.write a program to accept your name and convert the name from lowercase to upper case by using WHILE.

Do While Loop
 The syntax of do while loop do { set of statements }while(condn); Eg: i=10; do { printf(%d,i); i--; }while(i!=0)

Output: 10987654321

Assignment
Write a program to display the menu and accept the menu options. If the menu options is q, exit the menu.
A add student records. M Modify the student records. Q Display the student records. D Delete the student records. E exit the menu.

Write a program to accept two numbers and arithmetic operator and do the calculator operation. Display the menu unit arithmetic operator character is q.

Arithmetic Operator Precedence


Level 1 2 3 4 5 6 Operators Pre Increment/Decrement () - Unary Minus *, /, % +Post Increment/Decrement

Basic Input/ Output


 printf function  printf(<Message with format specifiers>, <List of Values or Variables delimited by comma>)  scanf function  scanf(<Format specifiers>, <List of Address of variables delimited by comma>)  Basic Format Specifiers for printf and scanf functions
Data type Character String Integer Unsigned Integer Float Double Specifier %c %s %d or %i %u %f %lf

Unconditional Branching Statements


Branching statement break continue Description Leaves the current block Leaves the current block, skips remaining logic in enclosing loop, and goes back to loop condition. Leaves the current block and jumps directly to a label of the form "<labelname>:" Leaves the current function.

goto return

Union
 Union is same as structure. The members of a union all share the same storage area within the computers memory where as each member within a structure is assigned its own unique storage area. (e.g) struct str { char a; int a; }s; union uni { char a; int I; }u; sizeof(s) is 3 sizeof(u) is only 2

            

float b[3][8]; //Memory = 3*8 * sizeof(float) = 3*8*4=96 Bytes


0 b 0 1 2 3 4 5 6 7

1 2

Compilation Process

.C / .CPP Preprocessor

Intermediate Source

.OBJ Compiler Linker

.EXE

Shortcuts: COMPILE MAKE EXE RUN

: Alt F9 D (.C/.CPP to .OBJ) : F9 D (.C/.CPP to .EXE) : Ctrl F9 D (.C/.CPP to .EXE and Execute )

Library

Symbolic Constant
We can define constants of any type by using the #define compiler directive. #define ANGLE_MIN 0 #define ANGLE_MAX 360

would define ANGLE_MIN and ANGLE_MAX to the values 0 and 360

Intialising Arrays
int a[]={4,5,2,-4,3,5} (Depth is taken as 6 by default) int a[3][3]={{1,2,3},{4,5,6},{7,8,9}) (Depth should be given)

Strings
String is implemented as a character array Usage: char <var>[<d>]; Ex; char name[20]; Here we can store a string of maximum 19 characters char name[]= C Program ; This statement allocates an array of 10 bytes This is the way how it is stored
C 0 1 P 2 r 3 o 4 g 5 r 6 a 7 m 8 \0 9

Scope of the Variables


#include <stdio.h> int count = 0; global variables Void test1(); Void test2(); void main() { int count = 0; // this hide the g.v for( ; count <5; count++) { test1(); test2(); } } Void test1() { printf( test1 value of count %d\n ,++count); } Void test2() { static int count; printf( test2 count value is %d\n ,++count); }

Variables
1. Local Variables: Variables defined local to a function disappear at the end of the function scope. So when we call the function again, storage for variables is created and values are reinitialize. 2. Static variables: if we want the value to be extent throughout the life of a program, we can define the local variable as "static." Initialization is performed only at the first call and data is retained between func calls. 3. Global variables: global variables have to be defined globally, persists (life is) throughout the program, scope is also throughout the program. This means such variables can be accessed from any function, any file of the program.

S-ar putea să vă placă și