Escolar Documentos
Profissional Documentos
Cultura Documentos
Compilation Process,Basic Data types, Importance of braces ({ }) in C Program, enumerated data type, Identifiers,Scope of
Easy to learn Structured language It produces efficient programs. It can handle low-level activities. It can be compiled on a variety of computers.
Facts about C:
C was invented to write an operating system called UNIX. C is a successor of B language which was introduced around 1970 The language was formalized in 1988 by the American National Standard Institue (ANSI). By 1973 UNIX OS almost totally written in C. Today C is the most widely used System Programming Language. Most of the state of the art software have been implemented using C
Why to use C? C was initially used for system development work, in particular the programs that make-up the operating system. C was adoped as a system development language because it produces code that runs nearly as fast as code written in assembly language. Some examples of the use of C might be:
Operating Systems Language Compilers Assemblers Text Editors Print Spoolers Network Drivers Modern Programs Data Bases Language Interpreters Utilities
Figure:-Sturucture of C program
Documentations:The documentation section consist of a set of comment lines giving the name of the program, the another name and other details, which the programmer would like to use later.
Global Declarations:The variables are declared before the main ( ) function as well as user defined functions are called global variables. These global variables can be accessed by all the user defined functions including main ( ) function. The main ( ) function:Each and Every C program should contain only one main ( ). The C program execution starts with main ( ) function. No C program is executed without the main function. The main ( ) function should be written in small (lowercase) letters and it should not be terminated by semicolon. Main ( ) executes user defined program statements, library functions and user defined functions and all these statements should be enclosed within left and right braces.
Braces:Every C program should have a pair of curly braces ({,}). The left braces indicates the beginning of the main ( ) function and the right braces indicates the end of the main ( ) function. These braces can also be used to indicate the user-defined functions beginning and ending. These two braces can also be used in compound statements. Local Declarations:-
The variable declaration is a part of C program and all the variables are used in main ( ) function
Program Algorithm / Explanation:1. #include<stdio.h> header file is included because, the C in-built statement printf we used in this program comes under stdio.h header files. 2. #include<conio.h> is used because the C in-built function getch() comes under conio.h header files. 3. main () function is the place where C program execution begins. 4. printf is used to display Hellow World. printf is the C in-built function, to display to the standard output device (Monitor). 5. Since C program execution happen in milliseconds, we cannot see the output (Hellow World) in the screen. Thats because Program output window closes immediately after execution. So we need a way to stop the program output window from closing. getch() will wait for keypress in our program execution and hence, we can see the result Hellow World. After viewing the output we can close the output by pressing any key in the keyboard.
Output :
C is a Structured Programming Language (program executes line by line). Even though many Advanced modern programming languages have emerged, C still remains the most powerful programming language ever invented. Why C is the most powerful language? To put that in a simple way,
Almost all modern programming languages are built from C. Almost all the modern Operating Systems that control the PCs are made of C. Windows, Linux, FreeBSD you name it.
Even though modern programming languages are created to provide additional features and ease of implementation for programmers, I would say, modern languages are created to prevent us from using / practising C, because C provides a special feature, which was completely eliminated from modern programming languages.
figure:-BIOS System Now consider a situation, we want to copy a file to our PC Hard Disk. When we initiate copy process in our Operating System the operating system communicates with BIOS (Firmware) with the help of Interrupts Request (IR) instructions to do the Job. The BIOS after receiving the suitable IR Instructions moves the Read/Write Head of hard Disk to the appropriate Location and does the file copy job in the Hardware Level. So for every job like copy, format, delete etc, there are separate IR Instructions. Memory Specifications :It is very important that every C programmer should be aware of memory. 1 Bit Space required to store a single character (eg :- a or , or or /or . or 4 etc) 1 Byte 8 Bits 1 Kilo Byte (KB) 1024 Bytes 1 Mega Byte (MB) 1024 KB 1 Giga Byte (GB) 1024 MB 1 Tera Byte (TB) 1024 GB 1 bit x 8 byte x 1024 kb x 1024 mb x 1024 gb = 8589934592 Bits (1 TB). Variables in C :Variable is used to store the values temporarily during the execution (runtime) of the program. Variables are allocated Memory Space (in RAM) depending on the data type. First we have to declare the needed variables in our program before actually using it. Declaring the variables doesnt guarantee that space is allocated in the Main Memory (RAM). The space is allocated during the execution (runtime) of the program.
Example : - a, number, s5, book_no etc. Data types in C :Data types define the type of data to be stored in variables. So it is important that we mention the data type, when a variable is declared.There are many different data types in C. Data Types int unsigned int float long unsigned long double long double char unsigned char Table:-different data types in C Syntax for declaring Variables in C :data_type variable_name ; Where, Data_type Valid C data type. (eg : int, char, float etc) Variable_name valid user defined C variable. Example :- int i, char name, float no etc. Format String %d %u %f %ld %lu %lf %lf %c / %s %c / %s
Output :
variable_size.c #include<stdio.h> #include<conio.h> void main() { printf("\n Size of Int : %d",sizeof(int)); printf("\n Size of short Int : %d",sizeof(short int)); printf("\n Size of long Int : %d",sizeof(long int)); printf("\n Size of Double : %d",sizeof(double)); printf("\n Size of Long Double : %d",sizeof(long double)); getch(); } Program Algorithm / Explanation:1. #include<stdio.h> header file is included because, the C in-built statement printf we used in this program comes under stdio.h header files. 2. #include<conio.h> is used because the C in-built function getch() comes under conio.h header files. 3. main () function is the place where C program execution begins. 4. sizeof() is used to display the size of different datatypes.
Constants in C:Constants can be also called as static variables. In variables values can be changed to any number of times during execution, whereas in constants value once assigned will remain static throughout the entire period.Rules for declaring a constant is exactly the same as variables, except constant declaration is preceded by the keyword constant. Syntax for Constant :const data_type constant_name = value; Where, const C keyword data_type valid C data type (eg : int, char, float etc) constant_name user defined name value static value assigned to constant by the programmer. Types of Constants in C:1. 2. 3. 4. Integer constant Real Constant Single Character constant String constant
1) Integer Constant : Integer constant can have integer values. Eg : 1, 100, -20 etc. 2) Real constant : Real constant can also be called floating point constants. Because, we can store values with
Formatted I/O in C : The formatted Input / Output functions can read and write values of all data types, provided the appropriate conversion symbol is used to identify the datatype.scanf is used for receiving formatted Input and printf is used for displaying formatted output. Syntax for scanf : scanf(control_string 1, - - , control_string n,&variable1, - - - - ,variable n); Syntax for printf : printf(control_string 1, - - , control_string n,variable1, - - - - , variable n); Sample Program : printf_scanf.c #include<stdio.h> #include<conio.h> void main() { int no; char ch; char s[20];
printf("Enter a Word or String : "); scanf("%s",&s); printf("\n Character : %c",ch); printf("\n No : %d",no); printf("\n String : %s",s); getch(); } Program Algorithm / Explanation 1. #include<stdio.h> header file is included because, the C in-built statement printf we used in this program comes under stdio.h header files. 2. #include<conio.h> is used because the C in-built function getch() comes under conio.h header files. 3. main () function is the place where C program execution begins. 4. Variable no of type int is declared. 5. Variable ch of type char is declared. 6. Array s[] of size 20 and type char is declared. 7. printf is used to prompt the user to input data to the above variables. 8. scanf is used to receive the datas. 9. Control string %d used for receiving user input for integer data, %c for character and %s for receiving in a array. 10. The user input datas are displayed using printf. Output :
Syntax for getch () in C :variable_name = getch(); getch() accepts only single character from keyboard. The character entered through getch() is not displayed in the screen (monitor). Syntax for getche() in C : variable_name = getche(); Like getch(), getche() also accepts only single character, but unlike getch(), getche() displays the entered character in the screen. Syntax for getchar() in C : variable_name = getchar(); getchar() accepts one character type data from the keyboard. Syntax for gets() in C : gets(variable_name); gets() accepts any line of string including spaces from the standard Input device (keyboard). gets() stops reading character from keyboard only when the enter key is pressed.
Functions in C:When we write large complex programs, it becomes difficult to keep track of the source code. The job of functions is to divide the large program to many separate modules based on their functionality. There are 4 types of functions in C. 1. 2. 3. 4. Functions with no arguments and no return value. Functions with arguments but no return value. Function with no arguments but with return value. Functions with arguments and with return value.
1) Functions with no arguments and no return value in C : Syntax : function_name () { Valid C Statements; } Sample Program : function1.c #include<stdio.h>
3) Function with no arguments but with return value in C : Syntax : data_type function_name() { Valid C Statements; return(value); } Sample Program : function3.c #include<stdio.h> #include<conio.h> void main() { int result; result=funct(); printf("\n Result = %d",result); getch(); } int funct() { int a,b,c;
Conditional Statements in C :Conditional statements are used to execute a statement or a group of statement based on certain conditions. 1. 2. 3. 4. 5. if if else else if switch goto
1) if conditional statement in C : Syntax for if statement in C : if(condition) { Valid C Statements; } If the condition is true the statements inside the parenthesis { }, will be executed, else the control will be transferred to the next statement after if. if.c
3) else if in C :Syntax : if(condition) { Valid C Statements; } else if(condition 1) { Valid C Statements; } else if(condition n) { Valid C Statements; } else { Valid C Statements; } In else if, if the condition is true the statements between if and else if is executed. If it is false the condition in else if is checked and if it is true it will be executed. If none of the condition is true the statement under else is executed.
4) Switch statement in C :Syntax : switch(variable) { case 1: Valid C Statements; break; case n: Valid C Statements; break; default: Valid C Statements; break; } Switch statements can also be called matching case statements. If matches the value in variable (switch(variable)) with any of the case inside, the statements under the case that matches will be executed. If none of the case is matched the statement under default will be executed. switch.c #include<stdio.h> #include<conio.h>
5) goto statement in C :goto is a unconditional jump statement. Syntax : goto label; so we have to use the goto carefully inside a conditional statement. goto.c #include<stdio.h> #include<conio.h> void main() { int a,b; printf("Enter 2 nos A and B one by one : "); scanf("%d%d",&a,&b); if(a>b) { goto first; } else { goto second; } first: printf("\n A is greater.."); goto g; second: printf("\n B is greater..");
Looping Statements in C :Looping statements are used to execute a statement or a group of statements repeatedly until the condition is true. 1. for loop 2. while loop 3. do while
2) while Loop in C :Syntax : while(condition) { Valid C Statements; } While loop executes statements based on certain conditions. But unlike for loop, while loop dont have variable initialisation or increment/decrement. while.c #include<stdio.h> #include<conio.h> void main() { int a=1; while(a<11) { printf("\n %d",a); a++; } getch(); }
3) do while Loop in C :Syntax : do { Valid C Statements; }while(condition); do while performs exactly like while except one condition. On the first cycle, condition is not checked as the condition is placed below. dowhile.c
Arrays in C :Array can be defined as group of related data types that share a common name.For example : -
single_array2.c #include<stdio.h> #include<conio.h> void main() { int a[5]={1,2,3,4,5}; int i; for(i=0;i<5;i++) { printf("%d",a[i]); } getch(); } Program Algorithm / Explanation : 1. #include<stdio.h> header file is included because, the C in-built statement printf we used in this program comes under stdio.h header files. 2. #include<conio.h> is used because the C in-built function getch() comes under conio.h header files. 3. main() function is the place where C program execution begins. 4. Array a of type int is declared and initialised with 5 values. int a[5]={1,2,3,4,5}; 5. A for loop is used with initialising i=0 and setting condition i<5.for(i=0;i<5;i++) 6. On the first cycle i=0 so a[0] will be printed. a[0]=1, so 1 will be displayed. 7. This process continues and prints all the 5 values in array. when i becomes 5 the condition fails, so control jumps out of for loop.
single_array3.c #include<stdio.h> #include<conio.h> void main() { int a[20]; int n,i; printf("\n Enter the size of array :"); scanf("%d",&n); printf("%d",n); printf("\n Enter Values to store in array one by one by pressing ENTER :"); for(i=0;i<n;i++) { scanf("%d",&a[i]); } printf("\n The Values in array are.."); for(i=0;i<n;i++) { printf("\n %d",a[i]); } getch(); } Program Algorithm / Explanation : 1. #include<stdio.h> header file is included because, the C in-built statement printf() we used in this program comes under stdio.h header files. 2. #include<conio.h> is used because the C in-built function getch() comes under conio.h header files. 3. main() function is the place where C program execution begins. 4. Array a of size 20 is declared. a[20] 5. Two int variable i & n are declared. 6. scanf() is used to get user Inputs for variable n which will be used as array size. 7. A for loop is used which will run nth time.
Two Dimensional Arrays in C :Syntax for 2D array in C : data_type array_name[row][column]; 2d_array1.c #include<stdio.h> #include<conio.h> void main() { int i,j; int a[2][2]={{11,12},{21,22}}; for(i=0;i<2;i++) { for(j=0;j<2;j++) { printf(" %d",a[i][j]); } printf("\n"); } getch(); }
2d_array2.c #include<stdio.h> #include<conio.h> void main() { int i,j,n; int a[6][6]; printf("\n Enter the Size (row x column) of a square matrix :"); scanf("%d",&n); for(i=0;i<n;i++) { for(j=0;j<n;j++) { scanf("%d",&a[i][j]); } } printf("\n Matric Output ..\n"); for(i=0;i<n;i++) {
Structures in C:Structure can be defined as a group of different data types that share a common name.Structure is a collection of one or more variables of different data types grouped under one name.
structure.c #include<stdio.h> #include<conio.h> void main() { struct employee { char name[20]; int age; }; struct employee emp; printf("\n Enter Name:"); scanf("%s",emp.name); printf("\n Enter Age:"); scanf("%d",&emp.age); printf("\n Name : %s",emp.name); printf("\n Age : %d",emp.age); getch(); }
Array of structures in C :It is a known fact that even though array can be store multiple values, they all can be of only one data type.Whereas structure can store different data types. So by declaring structure variable as a array, we can store many values of different data types. structure_array.c #include<stdio.h> #include<conio.h> void main() { int i,j,n; i=0; j=0; struct emp { char emp_name[40]; int emp_no;
The above example is the clear demonstration of storing multiple datas in a structure using the concept Array of Structures. Structures and Functions in C :We can use structure members to pass values (arguments) to a function. structure_function.c #include<stdio.h> #include<conio.h> void main() { struct emp { char emp_name[40]; int emp_no; }; struct emp d={"sat",1}; display(d.emp_name,d.emp_no); getch(); }
structure_function1.c #include<stdio.h> #include<conio.h> struct emp { char emp_name[40]; int emp_no; }; void main() {
Program Algorithm / Explanation : 1. #include<stdio.h> header file is included because, the C in-built statement printf we used in this program comes under stdio.h header files. 2. #include<conio.h> is used because the C in-built function getch() comes under conio.h header files. 3. main() function is the place where C program execution begins. 4. A structure by name family_members is declared with 3 member variables.
Enumeration in C :Enumeration is used to create our user-defined data types. enum.c #include<stdio.h> #include<conio.h> void main() { int j; enum countries { india=1,uk,usa };
scanf("%d",&j);
pointer2.c #include<stdio.h> #include<conio.h> void main() { char *ptr="sat"; printf("%s",ptr); getch(); } Program Algorithm / Explanation : 1. #include<stdio.h> header file is included because, the C in-built statement printf we used in this program comes under stdio.h header files. 2. #include<conio.h> is used because the C in-built function getch() comes under conio.h header files. 3. main() function is the place where C program execution begins. 4. A pointer *ptr of type char is declared and assigned a data sat. 5. Now just printing ptr displays the entire data sat. Output :
Structures using pointers in C :pointer5.c #include<stdio.h> #include<conio.h> void main() { struct emp { char emp_name[40]; int emp_no; }; struct emp emp_details,*ptr; printf("\n Enter Employee Name :"); scanf("%s",&ptr->emp_name); printf("\n Enter Employee No :"); scanf("%d",&ptr->emp_no); printf("\n Enter Employee Name : %s",ptr->emp_name); printf("\n Enter Employee No : %d",ptr->emp_no); getch(); } Program Algorithm / Explanation : 1. #include<stdio.h> header file is included because, the C in-built statement printf we used in this program comes under stdio.h header files. 2. #include<conio.h> is used because the C in-built function getch() comes under conio.h header files.
String Manipulation using Pointers :pointer6.c #include<stdio.h> #include<conio.h> void main() { int i; char name[20],*ptr; printf("\n Name : "); scanf("%s",&name); ptr=name; printf("\n The Name you Entered = "); while(*ptr!='\0') { printf("%c",*ptr); ptr++; } getch(); } Program Algorithm / Explanation : 1. #include<stdio.h> header file is included because, the C in-built statement printf we used in this program comes under stdio.h header files.
String Length using Pointers :pointer7.c #include<stdio.h> #include<conio.h> void main() { int i=0; char name[20],*ptr; printf("\n Name : "); scanf("%s",&name); ptr=name; printf("\n The Name you Entered = "); while(*ptr!='\0') { printf("%c",*ptr); ptr++; i++; } printf("\n Sring Length = %d",i); getch(); }
String functions / Operations in C 1) strlen() in C :This function is used to determine the length of a given string. Syntax :variable=strlen(string); The string length will be returned to the variable. str_length.c #include<stdio.h> #include<conio.h> #include<string.h> void main() {
2) strcpy() in C : This function copies the string from one variable to another variable. Syntax : strcpy(source_variable, destination_variable);
3) strncpy() in C :This function also copies the string from one variable to another variable, but only upto the specified length.
Syntax : strncpy(destination, source, length); strn_cpy.c #include<stdio.h> #include<conio.h> #include<string.h> void main() { char a[30],b[30]; printf("Enter a string : "); scanf("%s",&a); strncpy(b,a,3); printf("Value of a : %s",a); printf("\nValue of b : %s",b); getch(); } Program Algorithm / Explanation : 1. #include<stdio.h> header file is included because, the C in-built statement printf we used in this program comes under stdio.h header files. 2. #include<conio.h> is used because the C in-built function getch() comes under conio.h header files. 3. string.h header file included because c in-built function strncpy() comes under it. 4. main() function is the place where C program execution begins. 5. Two array of type char, a[30] and b[30] are declared. 6. User input is received and stored in the arrays a using scanf. 7. C in-built function strncpy() is used copy the datas from array a to array b upto a specified length. In this case it is 3. 8. Now when the array a & b are displayed array b will have data identical to array a upto the length of 3. Output :
4) strcmp() in C :This function is used to compare two strings. They are case sensitive. Syntax : strcmp(string1,string2); If both the strings are equal return value will be 0, else non_zero value will be returned. Sample program : str_cmp.c #include<stdio.h> #include<conio.h> #include<string.h> void main() { char a[30],b[30]; int n; printf("Enter string one : "); scanf("%s",&a); printf("Enter string two : "); scanf("%s",&b); n=strcmp(a,b); if(n==0) { printf("Both the Strings are Equal"); } else { printf("Strings are not Equal"); } getch(); }
Output :
5) stricmp() in C : This function is also used to compare two strings but they are not case sensitive. Syntax : stricmp(string1,string2); stri_cmp.c #include<stdio.h> #include<conio.h> #include<string.h> void main() { char a[30],b[30]; int n; printf("Enter string one : ");
6) strncmp() in C : This function compares two strings only upto a specified length. They are case-sensitive. Syntax : strncmp(string1,string2,length);
7) strnicmp() in C :This function also compares two strings upto a specified length, but not case-sensitive. Syntax : strnicmp(string1,stringn,length); Sample program : strni_cmp.c #include<stdio.h> #include<conio.h> #include<string.h> void main() { char a[30],b[30]; int n; printf("Enter string one : "); scanf("%s",&a); printf("Enter string two : "); scanf("%s",&b); n=strnicmp(a,b,3); if(n==0) { printf("Both the Strings are Equal upto the first 3 characters"); } else { printf("Strings are not Equal"); } getch(); }
8) strlwr() in C :This function converts uppercase characters to lowercase. Syntax : strlwr(string); str_lwr.c #include<stdio.h> #include<conio.h> #include<string.h> void main() { char a[30]; printf("Enter a string in uppercase : ");
9) strupr() in C :This function converts lowercase characters to uppercase. Syntax : strupr(string); str_upr.c #include<stdio.h> #include<conio.h> #include<string.h> void main() { char a[30]; printf("Enter a string in lowercase : ");
10) strdup() in C :This function is used to duplicate a string to a pointer variable by allocating the memory location of the string. Syntax : pointer=strdup(string); str_dup.c #include<stdio.h> #include<conio.h> #include<string.h> void main() {
Program Algorithm / Explanation : 1. #include<stdio.h> header file is included because, the C in-built statement printf we used in this program comes under stdio.h header files. 2. #include<conio.h> is used because the C in-built function getch() comes under conio.h header files. 3. string.h header file included because c in-built function strdup() comes under it. 4. main() function is the place where C program execution begins. 5. A char type array a and char type pointer variable *b are declared. 6. User Input for array a is received using scanf. 7. C in-built function strdup() is used to duplicate the datas in a to b. 8. Now when array and pointer variable *b are displayed, they both have identical datas. Output :
11) strcat() in C :This function is used to join (concatenate) two strings. Syntax : strcat(string1,string2); str_cat.c
13) strrev() in C :-This function is sued to reverse the characters in a given string. Syntax : strrev(string);
14) strset() in C :This function replaces all the characters of a string with a given symbol or character. Syntax : strset(string,symbol);
15) strnset() in C :This function also replaces the characters of a string with a given symbol but only to a specified length. strnset(string,symbol,n); strn_set.c #include<stdio.h> #include<conio.h> #include<string.h> void main() { char a[30]; char b; printf("Enter a string: "); gets(a); printf("Enter a symbol to replace the string : "); scanf("%c",&b); strnset(a,b,2); printf("After strset : %s",a); getch(); } Program Algorithm / Explanation : 1. #include<stdio.h> header file is included because, the C in-built statement printf we used in this program comes under stdio.h header files.
Dynamic Memory Allocations in C 1) Malloc in C :malloc() is used to allocate memory space in bytes for variables of any valid C data type. Syntax : pointer= (data_type*)malloc(user_defined_size); malloc.c #include<stdio.h> #include<conio.h> #include<stdlib.h> void main() { int a,*ptr; a=10; ptr=(int*)malloc(a*sizeof(int));
2) Calloc in C :calloc() is sued to allocate multiple blocks of memory dynamically during the execution (runtime) of the program. Syntax : pointer=(data_type*)calloc(no of memory blocks, size of each block in bytes); calloc.c #include<stdio.h>
Pre processors in C
header files in C : header files are used to include pre-built functions in our c programs. There are two types of header files. 1. C in-built header files. 2. C user defined header files. Header files like stdio.h, string.h are in-built headers in C.User defined header files are created by the programmer itself. header.c #include<stdio.h> #include<conio.h> #include "add.h" void main() { int a,b; printf("\n Enter 2 nos to add : "); scanf("%d%d",&a,&b); sum(a,b); getch(); }
typedef in C :We can define our own data types(user defined datatyes) from C in-built datatypes. Syntax : typedef in-built-datatype user-defined-datatype; typedef.c #include<stdio.h> #include<conio.h> void main() { typedef int nos; typedef char alpha; nos n; n=5; alpha a[10]="hellow"; printf(" %d \n %s",n,a); getch(); } Program Algorithm / Explanation : 1. #include<stdio.h> header file is included because, the C in-built statement printf we used in this program comes under stdio.h header files.
Command Line Arguments in C :-Command line arguments are used to pass values as arguments to the main() function of a C Program from the command line itself. comd.c #include<stdio.h> main(int argc,int *argv[]) { int i; printf("No of arguments %d",argc); for(i=0;i<argc;i++) { printf("\n %s",argv[i]); } } Program Algorithm / Explanation : 1. #include<stdio.h> header file is included because, the C in-built statement printf we used in this program comes under stdio.h header files. 2. #include<conio.h> is used because the C in-built function getch() comes under conio.h header files. 3. main() is the place where the program execution begins and arguments are received to main from command line.
Files in C Files are used to store datas in the secondary memory(eg:- hard disk, floppy, flash disk etc).There are various file operations that can be done in C like Creating a file, deleting a file, renaming a file, opening a file to read/write/append datas etc.We can use FILE pointers to navigate through various records in a file.Before doing any operations on a file, we have to declare a file pointer first. Syntax for declaring a file pointer in C FILE *file_pointer;
Eg :- FILE *fp; Where, FILE = keyword *fp = user defined file pointer variable. Once the file pointer is declared next step is to create/open a file. Creating / opening a file in C fopen() is used to open a specified file from disk, if it exist. If it doesnt exist a new file will be created and opened for further file operations.
Where, fp= user defined file pointer variable. filename= name of the file with file type as extension. mode= mode in which the file is to be opened. Eg :To Read r, To Write - w, To Append a To Read & Write w+, To Read and write r+ To Read Write with append a+ In w+ mode the contents in existing file is destroyed and then can perform read/write operations.In r+ mode just read and write operations can be performed.In a+ mode we can perform read and write operations with appending contents. So no existing datas in a file are destroyed.Example:-fp=fopen(data.txt,a+);After a file is opened, we have to perform read or wrote operations into it. Writing to a file in C:fprintf() fprintf() is used to write datas to a file from memory. Syntax for fprintf() fprintf(file pointer,control string,variables); example:- fprintf(fp,%s,name); Reading from a file in C fscanf() is used to read data from a file to the memory. Syntax for fscanf() fscanf(file pointer,control string,variables); eg:- fscanf(fp,%s,name); Closing a file in C
Where, fp= user-defined file pointer. Reading and Writing to a file in C Sample Program : fprintf_fscanf.c #include<stdio.h> #include<conio.h> void main() { FILE *fp; char c[60]; int no,n; fp=fopen("data2.txt","a+"); printf("Enter the Employee Name and No : "); scanf("%s %d",c,&no); fprintf(fp,"\n\n%s\n%d",c,no); rewind(fp); printf("Enter the Employee No : "); scanf("%d",&n); while(!feof (fp)) { fscanf(fp,"%s %d",c,&no); if(no==n) { printf("\n%s \n %d",c,no); } } fclose(fp); getch(); } Output :
Program Algorithm / Explanation 1. #include<stdio.h> header file is included because, the C in-built statement printf we used in this program comes under stdio.h header files. 2. #include<conio.h> is used because the C in-built function getch() comes under conio.h header files. 3. main () function is the place where C program execution begins. 4. A file pointer variable *fp is declared. 5. A char type array c[60] is declared along with two int type variables no & n. 6. fopen() is used to open the file data2.txt in append mode along with read/write permissions using a+ (append mode). 7. scanf() is used to receive the employee name and no to variable c & no from user input. 8. Now received datas are stored in the file using fprintf(). 9. Now rewind(fp) is used to move the file pointer to the top of the file. 10. scanf() is used to receive the employee no and a while statement is used to search for the corresponding employee record in the file. 11. fscanf() is used to read the records from the file and they are compared with employee number from user input. 12. If it matches, the particular employee record is displayed using printf. Writing Character by Character to a file in C:fputc.c #include<stdio.h> #include<conio.h> void main() { FILE *fp; char c; fp=fopen("data.txt","w"); printf("Enter datas to save inside the file 'data.txt' and press '~' to stop writing \n"); while(c!='~')
Output :
Program Algorithm / Explanation 1. #include<stdio.h> header file is included because, the C in-built statement printf we used in this program comes under stdio.h header files. 2. #include<conio.h> is used because the C in-built function getch() comes under conio.h header files. 3. main () function is the place where C program execution begins. 4. A file pointer variable *fp is declared. 5. A char type variable c is declared. 6. fopen() is used to open the file in write mode. 7. While loop is used to run until the symbol ~ is interrupted. 8. Inside while loop, getche() is used to receive user input and stored in variable c. 9. The character stored in variable c is written to the file using fputch(). 10. And fclose() is used to close the opened file. Reading Character by Character from a file in C:getc.c #include<stdio.h> #include<conio.h> void main() { FILE *fp; char c; fp=fopen("data.txt","r"); rewind(fp);
Output :
Program Algorithm / Explanation 1. #include<stdio.h> header file is included because, the C in-built statement printf we used in this program comes under stdio.h header files. 2. #include<conio.h> is used because the C in-built function getch() comes under conio.h header files. 3. main () function is the place where C program execution begins. 4. A file pointer variable *fp is declared. 5. A char type variable c is declared. 6. fopen() is used to open the file in read mode. 7. While loop is made to run until end of file is reached. 8. getc() is used to read a character from file and the same is displayed using printf(). Renaming a file in C rename.c #include<stdio.h> #include<conio.h> void main() { char a[50],b[50]; printf("Enter the name of the file to be renamed: ");
Output :
Program Algorithm / Explanation 1. #include<stdio.h> header file is included because, the C in-built statement printf we used in this program comes under stdio.h header files. 2. #include<conio.h> is used because the C in-built function getch() comes under conio.h header files. 3. main () function is the place where C program execution begins. 4. Two char type array a[50] & b[50] are declared. 5. scanf() is used to receive the existing file name to array a[] and new file name to array b[]. 6. Now a[] & b[] are used in rename() to rename existing file. Deleting / Removing a file in C:remove.c #include<stdio.h> #include<conio.h> void main() { char a[50]; printf("Enter the name of the file to be removed: "); scanf("%s",&a);
Program Algorithm / Explanation 1. #include<stdio.h> header file is included because, the C in-built statement printf we used in this program comes under stdio.h header files. 2. #include<conio.h> is used because the C in-built function getch() comes under conio.h header files. 3. main () function is the place where C program execution begins. 4. A char type array a[50] is declared. 5. scanf() is used to receive the file name from user input to array a[]. 6. The file name in array a[] is used to remove the particular file from disk using remove(). C Language - The Preprocessor:A unique feature of c language is the preprocessor. A program can use the tools provided by preprocessor to make his program easy to read, modify, portable and more efficient. Preprocessor is a program that processes the code before it passes through the compiler. It operates under the control of preprocessor command lines and directives. Preprocessor directives are placed in the source program before the main line before the source code passes through the compiler it is examined by the preprocessor for any preprocessor directives. If there is any appropriate actions are taken then the source program is handed over to the compiler. Preprocessor directives follow the special syntax rules and begin with the symbol #bin column1 and do not require any semicolon at the end. A set of commonly used preprocessor directives
Function Defines a macro substitution Undefines a macro Specifies a file to be included Tests for macro definition Specifies the end of #if Tests whether the macro is not def Tests a compile time condition Specifies alternatives when # if test fails
The preprocessor directives can be divided into three categories :1. Macro substitution division 2. File inclusion division 3. Compiler control division Macros: Macro substitution is a process where an identifier in a program is replaced by a pre defined string composed of one or more tokens we can use the #define statement for the task. #define identifier string The preprocessor replaces every occurrence of the identifier int the source code by a string. The definition should start with the keyword #define and should follow on identifier and a string with at least one blank space between them. The string may be any text and identifier must be a valid cname.
There are different forms of macro substitution. The most common form is 1.Simple macro substitution 2.Argument macro substitution 3. Nested macro substitution
Whenever the identifier appears in the source code it is replaced with the replacement token list, which can be empty. For an identifier declared to be a function-like macro, it is only replaced when the following token is also a left parenthesis that begins the argument list of the macro invocation. The exact procedure followed for expansion of function-like macros with arguments is subtle. Object-like macros were conventionally used as part of good programming practice to create symbolic names for constants, example: #define PI 3.14159 instead of hard-coding the numbers throughout the code. An alternative in both C and C++, especially in situations in which a pointer to the number is required, is to apply the const qualifier to a global variable. This causes the value to be stored in memory, instead of being substituted by the preprocessor.An example of a function-like macro is:
Many implementations do not support trigraphs or do not replace them by default. Many implementations (including, e.g., the C-compilers by GNU, Intel, Microsoft and IBM) provide a non-standard directive to print out a warning message in the output, but not stop the compilation process. A typical use is to warn about the usage of some old code, which is now deprecated and only included for compatibility reasons, example:-
(GNU, Intel and IBM) #warning "Do not use ABC, which is deprecated. Use XYZ instead." #pragma message("Do not use ABC, which is deprecated. Use XYZ instead.")
Some Unix preprocessors traditionally provided "assertions", which have little similarity to assertions used in programming. GCC provides #include_next for chaining headers of the same name. Objective-C preprocessors have #import, which is like #include but only includes the file once.
Uses As a general-purpose preprocessor (GPP) Since the C preprocessor can be invoked independently to process files other than those containing to-be-compiled source code, it can also be used as a "general purpose preprocessor" (GPP) for other types of text processing. One particularly notable example is the now-deprecated imake system.GPP does work acceptably with most assembly languages. GNU mentions assembly as one of the target languages among C, C++ and Objective-C in the documentation of its implementation of the preprocessor. This requires that the assembler syntax not conflict with GPP syntax, which means no lines starting with # and that double quotes, which cpp interprets as string literals and thus ignores, don't have syntactical meaning other than that. However, since the C preprocessor does not have features of some other preprocessors, such as recursive macros, selective expansion according to quoting, string evaluation in conditionals, and Turing completeness, it is very limited in comparison to a more general macro processor such as m4. Macro Substitution:When macroname is invoked, each occurrence of string1 in its definition string is replaced by string2. Syntax
Macro Substitution using # define in C A definition has the form #define name replacement text It calls for a macro substitution of the simplest kind - subsequent occurrences of the token name will be replaced by the replacement text. The name in a #define has the same form as a variable name; the replacement text is arbitrary. Normally the replacement text is the rest of the line, but a long definition may be continued onto several lines by placing a \ at the end of each line to be continued. The scope of a name defined with #define is from its point of definition to the end of the source file being compiled. A definition may use previous definitions. Substitutions are made only for tokens, and do not take place within quoted strings. For example, if YES is a defined name, there would be no substitution in printf("YES") or in YESMAN. Any name may be defined with any replacement text. For example #define forever for (;;) /* infinite loop */ defines a new word, forever, for an infinite loop. It is also possible to define macros with arguments, so the replacement text can be different for different calls of the macro. As an example, define a macro called max: #define max(A, B) ((A) > (B) ? (A) : (B)) Although it looks like a function call, a use of max expands into in-line code. Each occurrence of a formal parameter (here A or B) will be replaced by the corresponding actual argument. Thus the line x = max(p+q, r+s); will be replaced by the line x = ((p+q) > (r+s) ? (p+q) : (r+s)); So long as the arguments are treated consistently, this macro will serve for any data type; there is no need for different kinds of max for different data types, as there would be with functions. If you examine the expansion of max, you will notice some pitfalls. The expressions are evaluated twice; this is bad if they involve side effects like increment operators or input and output. For instance
Instruction selection: which instructions to use. Instruction scheduling: in which order to put those instructions. Scheduling is a speed optimization that can have a critical effect on pipelined machines. Register allocation: the allocation of variables to processor registers[1] Debug data generation if required so the code can be debugged.
Instruction selection is typically carried out by doing a recursive postorder traversal on the abstract syntax tree, matching particular tree configurations against templates; for example, the tree W := ADD(X,MUL(Y,Z)) might be transformed into a linear sequence of instructions by recursively generating the sequences for t1 := X and t2 := MUL(Y,Z), and then emitting the instruction ADD W, t1, t2. In a compiler that uses an intermediate language, there may be two instruction selection stages one to convert the parse tree into intermediate code, and a second phase much later to convert the intermediate code into instructions from the instruction set of the target machine. This second phase does not require a tree traversal; it can be done linearly, and typically involves a simple replacement of intermediate-language operations with their corresponding opcodes. However, if the compiler is actually a language translator (for example, one that converts Eiffel to C), then the second code-generation phase may involve building a tree from the linear intermediate code. Runtime code generation When code generation occurs at runtime, as in just-in-time compilation (JIT), it is important that the entire process be efficient with respect to space and time. For example, when regular expressions are interpreted and used to generate code at runtime, a non-determistic finite state machine is often generated instead of a deterministic one, because usually the former can be created more quickly and occupies less memory space than the latter. Despite its generally
Each instruction represents exactly one fundamental operation; e.g. "shift-add" addressing modes common in microprocessors are not present. Control flow information may not be included in the instruction set. The number of registers available may be large, even limitless.
A popular format for intermediate languages is three address code.A variation in the meaning of this term is to refer to those languages used as an intermediate language by some high-level programming languages which do not output object or machine code, but output the intermediate language only, to submit to a compiler for such language, which then outputs finished object or machine code. This is usually done to gain optimization much as treated above, or portability by using an intermediate language that has compilers for many processors and operating systems, such as C. Languages used for this fall in complexity between high-level languages and lowlevel languages, such as assembly languages.
the historical Register Transfer Language (RTL) the tree language GENERIC the SSA-based GIMPLE.
While most intermediate languages are designed to support statically typed languages, the Parrot intermediate representation is designed to support dynamically typed languagesinitially Perl and Python.The ILOC intermediate language is used in classes on compiler design as a simple target language. Coding character set You should limit yourself to the ASCII character set in C source files. The printable ASCII characters are represented by the bytes hexadecimal 20 to 7e. Non-ASCII characters (e.g. ISO-
use of underscore characters(e.g. get_name) use of upper case initials (e.g. GetName)
Some software packages use a kind of type prefix (e.g. uppercase initial for functions and lowercase type indicating initials for variables). E.g.: sz (zero terminated string), n/i (integer), p (pointer), psz (zero terminated string pointer), f/b (flag, boolean), c (character), fp (file pointer), pfn (function pointer), h (handle), w (word, unsigned int), fd (file descriptor). Name restrictions:
Case-insensitive linkers will have problems with external identifiers that differ only in case. There is a restriction on how many characters of an external identifier name a linker must support. Identifiers that begin on _ or __ are reserved for the C implementation and may not be used. Some additional prefixes are reserved and may not be used: str (string functions, string.h), E (operating system error numbers, errno.h).
Namespace A program's identifier namespace isn't partitioned in the C programming language, unlike in Lisp, Java or C++ 3rd Ed. Libraries tend to include package membership information (e.g. t_open, t_bind, etc. of the TLI network interface library) to omit name collisions. However, it will be impossible to find small unique package prefixes. File names The naming of source files, header files, libraries, directories and projects is not a C programming language issue. However, some considerations are worthwhile. Filesystems (in which the source files are stored) may or may not be case-sensitive. In the later case, one cannot save e.g. Main.c and main.c in the same directory. The recommended character set for file names, valid on most systems, is rather small: letters, digits, .-_ and maybe ~@+%,, reasons being
some characters are used by filesystems (/\:;) some characters have the meaning of quotes (in scripts or shells) ("'\`) some characters are delimiters in shells (blank, tab) some characters are meta characters in shells (<>()[]{}$=`;&|^*?#!) some characters depend on a non-ASCII character set
A package prefix is considerable with header files to avoid namespace problems (a bad example being external header files named error.h or types.h).
to catch some of K&R1 pitfalls (insufficient type checking, missing declarations) to check inter-module issues (inconsistent interface declarations, e.g. char p[] vs. extern char* p) to find globally unused functions and variables to find dead (unreachable) code (which is usually an error) to check for false or missing arguments to printf() or scanf() to check static array's bounds to catch inconsistent function use (e.g. ignoring return values sometimes)
number of source code lines number of lines of code (LOC, leaving out empty lines and comments) number of comments number of statements ratio of comments per statement
One can do statistics on the distribution of these values over modules or projects, or check if the values are in certain ranges. Advanced metrics can count function points, express code complexity (e.g. statements per function, nesting, number of cross-references, etc.). Even more advanced metrics may try to track changes in micro architecture, changes in interfaces and the like, as the project development goes on. This may be accomplished together with configuration management tools. Assertions An alternative to runtime checker applications are Assertions. They allow to check preconditions and postconditions of functions (and other constructs) at runtime. Assertions can be used to check the internal program logic and a correct program flow. Drawbacks are:
They're expensive to code. Their use might not be systematic (because manually created). The code may get harder to read.
Release versions typically do not contain the assertions. Beta versions may or may not contain the assertions. Runtime checkers:Applications are available that instrumentate code with runtime checks (for array boundaries, dynamic data boundaries, missing memory deallocation, function/system calls with bad arguments, etc.). The use of such tools may be time consuming since the program may run factors slower. The tool may not be able to distinguish between e.g. memory leaks (bad) and reusable buffers that won't be freed (a valid design decision). Samples are: purify, electric fence (dynamic memory checks only). These applications may be used in automated testing suite. Code complexity One of the aims of coding guidelines may be to keep code complexity as low as possible
Code can become unreadable. Complicated expressions may require a operator precedence lookup, based on the assumption that one does not have all of the precedences memorized. Source code debugging doesn't show intermediate data. Expressions need to be wrapped to a second line or the line will be extraordinary long.
One drawback of nested expression was the warning "assignment in conditional expression" with if(p = malloc(size)). The warning can be avoided by using parentheses or by separating statements: p = malloc(size); if(p). This may additionally make debugging easier. Redundancy:Code fragments should not be repeated. Redundant code is harder to maintain and increases the probability of introducing defects. Code with many redundancies is harder to read.If performance is the problem, use macros or an optimizing compiler that inlines the functions (preferred). Determinism Write deterministic code. Stack variables and buffers should be initialized. Searching for bugs that show non-deterministic symptoms is an unpleasant task at best. You may consider to assign a freed pointer 0. Modularity Modularity is an important key for code maintainability and handling complexity. If you introduce a module abstraction layer on top of the functions, you can decrease problem complexity tremendously. Interfaces Interfaces are the declarations used by implementation and referrers. They consist of type definitions, function declarations (prototypes) and maybe global data declarations and are located in header files. No extern declaration must appear in C files. They belong in commonly included header files. I tend to design one header file for each C source file. If several modules are linked together to a library, a new external header file may be created that declares all extern functions. Alternatively, all of the extern functionality can be encapsulated in one source file. Its according header then becomes the external header. There are very few reasons to include static definitions in header files. There is in my opinion no reason to include static function declarations in header files. They belong in the source file that implements the functions. Header files
Using Pascal style makes it unnecessary to track function interface changes in the prototypes. A compiler may chose only to inline functions on high optimization levels and if they have been defined before. C style sources seem to be easier to read since going from the start of the file to the end is much more like the actual program flow compared to Pascal style.
Error handling should typically be done without delay, example:fp = fopen(file, "r"); if(fp == 0) return -1; process(fp); is in my opinion preferable to
don't use conditional compiling at all conditionally include only a few macros and include directives conditionally include large parts of code
due to the fact that conditional compiling seems hard to read to some. However, suitable editors can display uncompiled parts of the code in comment font type and even fold it, to make sources more readable. There are tools available to remove the unused conditional parts. Alternatives to conditional compiling are including one of different header files (with the -I compiler option) or linking one of different libraries (with the -L compiler option) or both. In development, you may chose to create a set of subprojects and include and link one of them. Conditional use of parts of code, header files, libraries or subprojects is often used to encapsulate platform specifics. Scope The scope of an identifier (function, type, etc.) is the part of the code in which the identifier can be referenced. The C programming language offers
Scope of functions Functions have file scope (static) or application scope (not static). Limit a function to file scope if possible. This affects the modularization of a software component (i.e. the way functions are grouped together to source files). Scope of variables
The first one is the worst, it will be invalid if the array definition is changed without tracking the other occurrences of the size. The second one is better, but the third using sizeof is the preferred one. Buffer sizes It is strongly discouraged to implement or use functions that require a buffer as an argument, without also requiring the buffer size. This rule should be strictly followed if the input size is an external (and hence uncontrolled) property (e.g. a line length with gets()). Buffer overflows can
corrupt adjacent data corrupt the stack frame (if on the stack) corrupt malloc internal data (if on the heap)
The first one is hard to find because it can subtly change the program logic. The last one is also hard to find, since the program often crashes at some later point in a call to malloc() or free(). In that case often only a malloc debug package helps. A sample of a corrupted stack frame is a program that crashed (on a little endian system), leaving a core. Because of the overwritten stack, the debugger that was used to examine the core (sdb) was unable to display a backtrace and just displayed the message "cannot get_text from 0x63697245", which confused on the first look, but was a good hint that upon returning from the corrupting function, the program tried to jump to nil. One problem is to guess how much buffer size a sprintf() will require. However, sprintf() allows to specify maximal lengths of spliced fields to limit the output string size (e.g. sprintf(buf, "...%.*s...", sizeof(buf)-1-..., p). Note that buffer overflows are security problems. Overwriting stack based buffers (while knowing the affected program and the system it runs on very well) can be used to insert manipulated function caller addresses and hence execute malicious code.
Do most of the development without optimization. Look at the assembly output if you suspect errors.
buffers that starts at some size and increase if needed values that are encapsulated deep in some implementation of an algorithm
Use as few hardcoded values as possible. Don't use static sized tables of data, since they are almost never appropriate. Don't generate any hidden dependencies among constants. Define constants by means of the constants they derive from. Numeric constants are hard to understand if they're at the same time not commented and not composed of other named constants. Compilers are quite able to do arithmetics at compile time, use them. Sample: if you need a buffer to hold a string representation of an integer, define its size in terms of INT_MAX or sizeof(int). E.g.: sizeof(int)*5/2+3 (assuming 8 bits per byte). Longs, shorts Using longs is an issue on 16 bit systems (either if you develop for 16 bit systems directly or plan to port your products to them sometimes). Traditionally, long and short (or unsigned long, unsigned short) were used (together with htonl(), ntohl(), htons(), ntohs()) in implementing low-level network protocols, such as UDP-based application protocols. The assumption was that C implementations define a long to be exactly 32 bits, which is however not defined by the C language standard. Use ASCII representations of numbers, when you write them to file or network, in order to be system architecture independent (size, byteorder, padding). Besides using htonl() and ASCII, there exist some architecture independent data representation libraries like XDR. However, ASCII representations seem easier to debug, because human readable. Using shorts may save significant space in large arrays. However, if the problem domain changes, shorts may become too small. Conversions from shorts to ints and back may also bring some computational overhead. Know also that unexpected alignments may occur if you mix
Integers may be more adapted to the discrete nature of a problem. Integer arithmetics are faster than float arithmetics (if that matters). Not using floating point numbers results in smaller executables on systems that require floating point handling routines and link them statically.
Many problems are solvable without using floats. E.g. a typical hashtable high-water-mark of 0.75 may be expressed by a ratio and handled by integer arithmetics: if(4*items > 3*size) ... Avoid single precision float. Use double. If you have to deal with single precision floats on file, then encapsulate the code that deserializes (reads them back). If space counts, you may consider to use normalized numbers, that are adapted to the problem domain (e.g. shorts signifying 1000th). Parameter types Express arrays as pointers in the function parameters. Use int main(int argc, char** argv) instead of int main(int argc, char* argv[]). The internal semantics of a parameter are that of a variable declared as char** argv, not char* argv[]. Variable arguments Variable argument functions don't let the compiler check number and type of the arguments. For this reason you may chose to use them rarely. Some compilers (and e.g. lint) warn of wrong arguments supplied to the variable argument function families printf() and scanf(), which are part of the standard C library. Portability types If a simple type (e.g. some kind of identification number) is supposed to change sometimes (e.g. from short to long), then introduce a type synonym for this type using typedef. Standard library Use the standard library functions where possible. They are portable and usually optimized. Some standard library functions might even get inline expanded (memcpy()), so there's probably no performance problem. Don't use gets() and the scanf() family for safety (buffer overflow crashes or program corruption) and security reasons (buffer overflow exploits). Use fgets() respectively fgets();strtok();atoi(); etc. instead. NULL macro Nullpointer comparisons can be expressed by
if(!p) ...
all three being perfectly valid in C. Register One could assume that compilers know the CPU registers better than the C programmer does, since they are the interfaces to the register-using assembly languages. Goto Most of the control flow problems can be solved by using additional layers of local functions (that need not imply overhead). Use return to jump out of them. Introducing function layers may enhance modularity and code encapsulation. Appreciate also break and continue instead of goto. Tabulators Making no assumptions about tabulator settings restricts you to either use only tabulators to indent or only blanks, but not both (since the results are displayed differently). Tabulator setting independence forbids also the usage of tabulators at other places than at the left margin. Not all editors can preserve tabs or blanks. In a worse case, only the indentation of changed lines in a source file is converted. Tabulators can also become victims of branch merge tools (which are part of revision control software). Braces Opening and closing braces ({}) can either appear on a line of their own or on the preceding line. The closing braces being right after the last statement (Lisp style) being rarely seen. If the opening and/or closing braces are on a line of their own, they can be adjusted to the indent level of the outer block or to that of the inner block or (halfway) in between. The use of the above styles can differ between code (functions) and data (structs, unions, array initializations) and can differ between top level code braces (functions) and function level code braces (do, else, for, if, switch, while). Braces may or may not be omitted in control blocks if the block covers one or zero statements. Labels Switch labels (case, default) can either appear adjusted to the outer block indent level or to the inner (with or without adding one more indent level for the code in the switch statement) or in
a short description of functionality a revision date (maybe generated by version control) an author maybe a copyright maybe the revision history (unless maybe managed by version control)
Comments can have the semantics of a tool directive (e.g. /*LINTED*/, /*ARGSUSED*/, /*NOTREACHED*/ or /*EMPTY*/ for Lint). They might or might not be used. Block comments As blocks represent a functional entity, they are candidates for comments. As constructs that span multiple lines, they should preferably be commented on comment-only lines. You may consider to put an empty line between blocks to make them a bit more readable. You may generally consider consequent spacing. In the C language (unlike the C++ language), a block has two parts: a variable definition part and a code part. These two parts should be separated by a blank line to make them more readable. The Importance of the main() Function in C Programming All C language programs must have a main() function. It's the core of every program. It's required. The main() function doesn't really have to do anything other than be present inside your C source code. Eventually, it contains instructions that tell the computer to carry out whatever task your program is designed to do. But it's not officially required to do anything. The basic main() function When the operating system runs a program in C, it passes control of the computer over to that program. This is like the captain of a huge ocean liner handing you the wheel. Aside from any fears that may induce, the key point is that the operating system needs to know where inside your program the control needs to be passed. In the case of a C language program, it's the main() function that the operating system is looking for. At a minimum, the main() function looks like this: main() {}
The main() function The set of parentheses after a C language function name is used to contain any arguments for the function stuff for the function to digest. For example, in the sqrt() function, the parentheses hug a value; the function then discovers the square root of that value. The main() function uses its parentheses to contain any information typed after the program name at the command prompt. This is useful for more advanced programming. Beginning programmers should keep in mind what those parentheses are there for, but you should first build up your understanding of C before you dive into that quagmire. The braces are used for organization. They contain programming instructions that belong to the function. Those programming instructions are how the function carries out its task or does its thing. By not specifying any contents, as was done for the main() function earlier, you have created what the C Lords call a dummy function which is kind of appropriate, given that you're reading this at Dummies.com. Enumerated type In computer programming, an enumerated type (also called enumeration or enum, or factor in the R programming language, and a categorical variable in statistics) is a data type consisting of a set of named values called elements, members or enumerators of the type. The enumerator names are usually identifiers that behave as constants in the language. A variable that has been declared as having an enumerated type can be assigned any of the enumerators as a value. In other words, an enumerated type has values that are different from each other, and that can be compared and assigned, but which do not have any particular concrete representation in the computer's memory; compilers and interpreters can represent them arbitrarily. For example, the four suits in a deck of playing cards may be four enumerators named CLUB, DIAMOND, HEART, SPADE, belonging to an enumerated type named suit. If a variable V is declared having suit as its data type, one can assign any of those four values to it.
What is an Identifier?
Before you can do anything in any language,you must at least know how you name an identifier. An identifier is used for any variable ,function, data defintion etc. In the programming language C, an identifier is a combination of alpha numeric characters, the first being the letter of an alphabet or an underline, and the remaining being any letter of the alphabet, any numeric digit, or the underline. Two rules must be kept in mind while naming an identifier.
2. As C is defined, up to eight significant characters can be used and will be considered significant. If more than eight are used, they may be ignored by the compiler. The HiTech C compiler used with the Applix 1616 alllows 31 significant characters, and prepends an underscore(_). It should be pointed out that some C compilers allows use of a dollar sign in an identifier name, but since it is not universal, it will not be used anywhere in this tutorial. Check your documentation to see if it is permissible for your particular compiler.
Identifier An identifier is a name that identifies (that is, labels the identity of) either a unique object or a unique class of objects, where the "object" or class may be an idea, physical [countable] object (or class thereof), or physical [noncountable] substance (or class thereof). The abbreviation ID often refers to identity, identification (the process of identifying), or an identifier (that is, an instance of identification). An identifier may be a word, number, letter, symbol, or any combination of those. The words, numbers, letters, or symbols may follow an encoding system (wherein letters, digits, words, or symbols stand for (represent) ideas or longer names) or they may simply be arbitrary. When an identifier follows an encoding system, it is often referred to as a code or ID code. Identifiers that do not follow any encoding scheme are often said to be arbitrary IDs; they are arbitrarily assigned and have no greater meaning. (Sometimes identifiers are called "codes" even when they are actually arbitrary, whether because the speaker believes that they have deeper meaning or simply because he is speaking casually and imprecisely.) ID codes inherently carry metadata along with them. (For example, when you know that the food package in front of you has the identifier "2011-09-25T15:42Z-MFR5-P02-243-45", you not only have that data, you also have the metadata that tells you that it was packaged on September 25, 2011, at 3:42pm UTC, manufactured by Licensed Vendor Number 5, at the Peoria, IL, USA plant, in Building 2, and was the 243rd package off the line in that shift, and was inspected by Inspector Number 45.) Arbitrary identifiers carry no metadata. (For example, if your food package just says 100054678214, its ID may not tell you anything except identityno date, manufacturer name, production sequence rank, or inspector number.) Metadata Identifiers in various disciplines Identifier Scope
Serial number Service batch number Social Security Number Tax File Number
U.S. Australian
Objective-C Operators and Expressions In the previous chapters we looked at using variables and constants in Objective-C and also described the different data types. Being able to create variables is only part of the story however. The next step is to learn how to use these variables and constants in Objective-C code. The primary method for working with data is in the form of expressions. In this chapter we will look in detail at Objective-C expressions and operators. What is an Expression? The most basic expression consists of an operator, two operands and an assignment. The following is an example of an expression: int myresult = 1 + 2; In the above example the (+) operator is used to add two operands (1 and 2) together. The assignment operator (=) subsequently assigns the result of the addition to an integer variable named myresult. The operands could just have easily been variables (or a mixture of constants and variables) instead of the actual numerical values used in the example. In the remainder of this chapter we will look at the various types of operators available in Objective-C. The Basic Assignment Operator
The following table lists the primary Objective-C arithmetic operators: Operator Description -(unary) Negates the value of a variable or expression * / Multiplication Division
Note that multiple operators may be used in a single expression. For example: x = y * 10 + z - 5 / 4; Whilst the above code is perfectly valid it is important to be aware that Objective-C does not evaluate the expression from left to right or right to left, but rather in an order specified by the precedence of the various operators. Operator precedence is an important topic to understand since it impacts the result of a calculation and will be covered in detail the chapter entitled Objective-C 2.0 Operator Precedence. Compound Assignment Operators In an earlier section we looked at the basic assignment operator (=). Objective-C provides a number of operators designed to combine an assignment with a mathematical or logical operation. These are primarily of use when performing an evaluation where the result is to be stored in one of the operands. For example, one might write an expression as follows: x = x + y; The above expression adds the value contained in variable x to the value contained in variable y and stores the result in variable x. This can be simplified using the addition compound assignment operator: x += y The above expression performs exactly the same task as x = x + y but saves the programmer some typing. Numerous compound assignment operators are available in Objective-C. The most frequently used are outlined in the following table:
Table:- Numerous compound assignment operators Increment and Decrement Operators Another useful shortcut can be achieved using the Objective-C increment and decrement operators (also referred to as unary operators because they operate on a single operand). As with the compound assignment operators described in the previous section, consider the following Objective-C code fragment: x = x + 1; // Increase value of variable x by 1 x = x - 1; // Decrease value of variable x by 1 These expressions increment and decrement the value of x by 1. Instead of using this approach it is quicker to use the ++ and -- operators. The following examples perform exactly the same tasks as the examples above: x++; Increment x by 1 x--; Decrement x by 1 These operators can be placed either before or after the variable name. If the operator is placed before the variable name the increment or decrement is performed before any other operations are performed on the variable. For example, in the following example, x is incremented before it is assigned to y, leaving y with a value of 10:
Boolean Logical Operators Objective-C also provides a set of so called logical operators designed to return boolean true and false. In practice true equates to 1 and false equates to 0. These operators both return boolean results and take boolean values as operands. The key operators are NOT (!), AND (&&), OR (||) and XOR (^). The NOT (!) operator simply inverts the current value of a boolean variable, or the result of an expression. For example, if a variable named flag is currently 1 (true), prefixing the variable with a '!' character will invert the value to 0 (false): bool flag = true; //variable is true bool secondFlag; secondFlag = !flag; // secondFlag set to false The OR (||) operator returns 1 if one of its two operands evaluates to true, otherwise it returns 0. For example, the following example evaluates to true because at least one of the expressions either side of the OR operator is true: if ((10 < 20) || (20 < 10)) NSLog (@"Expression is true");
The AND (&&) operator returns 1 only if both operands evaluate to be true. The following example will return 0 because only one of the two operand expressions evaluates to true: if ((10 < 20) && (20 < 10)) NSLog (@"Expression is true"); The XOR (^) operator returns 1 if one and only one of the two operands evaluates to true. For example, the following example will return 1 since only one operator evaluates to be true:
2009-10-07 15:41:39.647 t[13153] Result is 171 Bitwise XOR The bitwise XOR (commonly referred to as exclusive OR and represented by the caret '^' character) performs a similar task to the OR operation except that a 1 is placed in the result if one or other corresponding bit positions in the two numbers is 1. If both positions are a 1 or a 0 then the corresponding bit in the result is set to a 0. For example: 10101011 XOR 00000011 ======== 10101000 The result in this case is 10101000 which converts to 168 in decimal. To verify this we can, once again, try some Objective-C code: int x = 171; int y = 3; int z; z = x ^ y; NSLog(@"Result is %i", z); When executed, we get the following output from NSLog: 2009-10-07 16:09:40.097 t[13790] Result is 168 Bitwise Left Shift The bitwise left shift moves each bit in a binary number a specified number of positions to the left. As the bits are shifted to the left, zeros are placed in the vacated right most (low order) positions. Note also that once the left most (high order) bits are shifted beyond the size of the variable containing the value, those high order are discarded:
Type Casting Converting an expression of a given type into another type is known as type-casting. We have already seen some ways to type cast: Implicit conversion Implicit conversions do not require any operator. They are automatically performed when a value is copied to a compatible type. For example: 1 short a=2000; 2 int b; 3 b=a;
Here, the value of a has been promoted from short to int and we have not had to specify any type-casting operator. This is known as a standard conversion. Standard conversions affect fundamental data types, and allow conversions such as the conversions between numerical types (short to int, int to float, double to int...), to or from bool, and some pointer conversions. Some of these conversions may imply a loss of precision, which the compiler can signal with a warning. This can be avoided with an explicit conversion.Implicit conversions also include constructor or operator conversions, which affect classes that include specific constructors or operator functions to perform conversions. For example: 1 class A {}; 2 class B { public: B (A a) {} }; 3
Here, an implicit conversion happened between objects of class A and class B, because B has a constructor that takes an object of class A as parameter. Therefore implicit conversions from A to B are allowed.
Type conversion In computer science, type conversion, typecasting, and coercion are different ways of, implicitly or explicitly, changing an entity of one data type into another. This is done to take advantage of certain features of type hierarchies or type representations. One example would be small integers, which can be stored in a compact format and converted to a larger representation when used in arithmetic computations. In object-oriented programming, type conversion allows programs to treat objects of one type as one of their ancestor types to simplify interacting with them. Each programming language has its own rules on how types can be converted. In general, both objects and fundamental data types can be converted. In most languages, the word coercion is used to denote an implicit conversion, either during compilation or during run time. A typical example would be an expression mixing integer and floating point numbers (like 5 + 0.1), where the integers are normally converted into the latter. Explicit type conversions can either be performed via built-in routines (or a special syntax) or via separately defined conversion routines such as an overloaded object constructor. In most Algol-based languages with nested function definitions, such as Ada, Delphi, Modula 2 and Pascal, conversion and casting are distinctly different concepts. In these languages, conversion refers to either implicitly or explicitly changing a value from one data type to another, e.g. a 16-bit integer to a 32-bit integer. The storage requirements may change as a result of the conversion. A loss of precision or truncation may also occur. The word cast, on the other hand, refers to explicitly changing the interpretation of the bit pattern representing a value from one type to another. For example 32 contiguous bits may be treated as an array of 32 booleans, a two character Unicode string, an unsigned 32-bit integer or an IEEE single precision floating point value. While the storage requirements are never changed, it still requires knowledge of low level details such as representation format, byte order, and alignment requirements in order to be meaningful. Typecasting
Typecasting (acting), the process by which an actor is strongly identified with a specific character, role, or trait
Typecasting (blogging), a form of blogging in which text is composed on a typewriter, then scanned and uploaded to a blog Casting of sorts (movable type pieces) for use in printing presses Type conversion in computer programming, the act or result of changing an entity of one data type into another Typecast (band), Filipino band Typecast (horse), American racehorse
There are several format specifiers - the one you use should depend on the type of the variable you wish to print out. Here are the common ones: Format Specifier %d (or %i) %c %f %lf %s %x Table:- format specifiers Type int char float double string hexadecimal
To display a number in scientific notation, use %e. To display a percent sign, use %%. %d is essentially the same as %i but I used %d from the very first day. LF stands for "long float".
Warning:-Don't try to display a (decimal) float/double number using the integer format specifier, %d, as this displays unexpected values! Similarly, don't use %f for displaying integers. Mixing %d with char variables, or %c with int variables is all right, as shown in this example: #include <stdio.h> int main() { int a = 72; char b = 'A'; printf("a equals %d \n", a); printf("a equals %c \n", a); printf("b equals %d \n", b); printf("b equals %c \n", b);
You could use as many format specifiers as you want with printf - just as long as you pass the correct number of arguments. The ordering of the arguments matters. The first one should correspond to the first format specifier in the string and so on. Take this example: printf("a=%d, b=%d, c=%d\n", a,b,c); If a, b and c were integers, this statement will print the values in the correct order. Rewriting the statement as... printf("a=%d, b=%d, c=%d\n", c,a,b); ... would still cause the program to compile OK, but the values of a, b and c would be displayed in the wrong order!
Suppose you want the program to display output that occupies a minimum number of spaces on the screen. You can achieve this by adding an integer value after the percent sign of a format specifier. For example, if you want to display an integer using a minimum of 8 spaces, you'd write %8d in your printf statement. This example gives a demonstration: #include <stdio.h> int main() { int x = 123; printf("Printing 123 using %%0d displays %0d\n", x); printf("Printing 123 using %%1d displays %1d\n", x); printf("Printing 123 using %%2d displays %2d\n", x); printf("Printing 123 using %%3d displays %3d\n", x); printf("Printing 123 using %%4d displays %4d\n", x); printf("Printing 123 using %%5d displays %5d\n", x); printf("Printing 123 using %%6d displays %6d\n", x); printf("Printing 123 using %%7d displays %7d\n", x); printf("Printing 123 using %%8d displays %8d\n", x); printf("Printing 123 using %%9d displays %9d\n", x);
Scanf:If you have multiple format specifiers within the string argument of scanf, you can input multiple values. All you need to do is to separate each format specifier with a DELIMITER - a string that separates variables. For convenience, the delimiter should be one character that's a punctuation mark, like a comma or a space. As a default, scanf stops reading in a value when space, tab or Enter is pressed. Consider scanf("%d %d", &x, &y);(Assume that x and y have been declared beforehand!). If I entered: 1 2 and pressed Enter, 1 would get assigned to x, and 2 would get assigned to y. But if I entered 1, 2 and pressed Enter, x would equal 1, but y won't get assigned 2 because scanf was not expecting a comma in the input string. Now consider: scanf("%d, %d, %d", &x,&y,&z); If I entered 1 2 3 and pressed enter 1 would get assigned to x but 2 and 3 won't get assigned to y or z, simply because I didn't separate the numbers with commas. Entering 1,2,3 works, but why does 1, 2, 3 also work? scanf ignores spaces, tabs and carriage returns immediately after the delimiters. Just don't put a space, tab or carriage return before the delimiter! 1 ,2, 3 won't work. If you want the user to press return after each number, try something along the lines as: scanf("%d\n%d\n%d", &x,&y,&z); Note that you shouldn't put a delimiter after the last format specifier!
scanf format string Scanf format string (which stands for "scan formatted") refers to a control parameter used by a class of functions typically associated with some types of programming languages. The format string specifies a method for reading a string into an arbitrary number of varied data type
#include <stdio.h> int main(void) { int n; while (scanf("%d", &n) > 0) printf("%d\n", n); return 0; } After being processed by the program above, a messy list of integers such as 456 123 789 456 1 2378 456 12
will appear neatly as: 456 123 789 456 12 456 1 2378 To print out a word: #include <stdio.h> int main(void)
%d : Scan an integer as a signed decimal number. %i : Scan an integer as a signed number. Similar to %d, but interprets the number as hexadecimal when preceded by 0x and octal when preceded by 0. For example, the string 031 would be read as 31 using %d, and 25 using %i. The flag h in %hi indicates conversion to a short and hh conversion to a char. %u : Scan for decimal unsigned int (Note that in the C99 standard the input value minus sign is optional, so if a negative number is read, no errors will arise and the result will be the two's complement, effectively ignoring the negative sign in most cases. See strtoul ().Correspondingly, %hu scans for an unsigned short and %hhu for an unsigned char. %f : Scan a floating-point number in normal (fixed-point) notation. %g, %G : Scan a floating-point number in either normal or exponential notation. %g uses lower-case letters and %G uses upper-case. %x, %X : Scan an integer as an unsigned hexadecimal number. %o : Scan an integer as an octal number.
%s : Scan a character string. The scan terminates at whitespace. A null character is stored at the end of the string, which means that the buffer supplied must be at least one character longer than the specified input length. %c : Scan a character (char). No null character is added. Whitespace: Any whitespace characters trigger a scan for zero or more whitespace characters. The number and type of whitespace characters do not need to match in either direction. %lf : Scan as a double floating-point number. %Lf : Scan as a long double floating-point number.
The above can be used in compound with numeric modifiers and the l, L modifiers which stand for "long" in between the percent symbol and the letter. There can also be numeric values between the percent symbol and the letters, preceding the long modifiers if any, that specifies the number of characters to be scanned. An optional asterisk (*) right after the percent symbol denotes that the datum read by this format specifier is not to be stored in a variable. No argument behind the format string should be included for this dropped variable. The ff modifier in printf is not present in scanf, causing differences between modes of input and output. The ll and hh modifiers are not present in the C90 standard, but are present in the C99 standard. An example of a format string is "%7d%s %c%lf" The above format string scans the first seven characters as a decimal integer, then reads the remaining as a string until a space, new line or tab is found, then scans the first non-whitespace character following and a double-precision floating-point number afterwards. Error handling scanf is usually used in situations when the program cannot guarantee that the input is in the expected format. Therefore a robust program must check whether the scanf call succeeded and take appropriate action. If the input was not in the correct format, the erroneous data will still be on the input stream and must be read and discarded before new input can be read. An alternative method of reading input, which avoids this, is to use fgets and then examine the string read in. The last step can be done by sscanf, for example. Security Like printf, scanf is vulnerable to format string attacks. Great care should be taken to ensure that the formatting string includes limitations for string and array sizes. In most cases the input string size from a user is arbitrary; it can not be determined before the scanf function is executed. This means that uses of %s placeholders without length specifiers are inherently insecure and
Limited-function early computers The history of the modern computer begins with two separate technologies, automated calculation and programmability, but no single device can be identified as the earliest computer, partly because of the inconsistent application of that term. A few devices are worth mentioning
First general-purpose computers In 1801, Joseph Marie Jacquard made an improvement to the textile loom by introducing a series of punched paper cards as a template which allowed his loom to weave intricate patterns automatically. The resulting Jacquard loom was an important step in the development of computers because the use of punched cards to define woven patterns can be viewed as an early, albeit limited, form of programmability. It was the fusion of automatic calculation with programmability that produced the first recognizable computers. In 1837, Charles Babbage was the first to conceptualize and design a fully programmable mechanical computer, his analytical engine. Limited finances and Babbage's inability to resist tinkering with the design meant that the device was never completed
Programming language
programming languages are designed to permit no ambiguity and to be concise. They are purely written languages and are often difficult to read aloud. They are generally either translated into machine code by a compiler or an assembler before being run, or translated directly at run time by an interpreter. Sometimes programs are executed by a hybrid method of the two techniques. Low-level languages Machine languages and the assembly languages that represent them (collectively termed lowlevel programming languages) tend to be unique to a particular type of computer. For instance, an ARM architecture computer (such as may be found in a PDA or a hand-held videogame) cannot understand the machine language of an Intel Pentium or the AMD Athlon 64 computer that might be in a PC. Higher-level languages Though considerably easier than in machine language, writing long programs in assembly language is often difficult and is also error prone. Therefore, most practical programs are written in more abstract high-level programming languages that are able to express the needs of the programmer more conveniently (and thereby help reduce programmer error). High level languages are usually "compiled" into machine language (or sometimes into assembly language and then into machine language) using another computer program called a compiler. High level languages are less related to the workings of the target computer than assembly language, and more related to the language and structure of the problem(s) to be solved by the final program. It is therefore often possible to use different compilers to translate the same high level language program into the machine language of many different types of computer.
Calculators
Colossus, ENIAC, Manchester SmallScale Experimental Machine, EDSAC, Manchester Mark 1, Ferranti Pegasus, Ferranti Mercury, CSIRAC, EDVAC, UNIVAC I, IBM 701, IBM 702, IBM 650, Z22
Mainframes Third generation (discrete transistors and SSI, MSI, LSIintegrated circuits) Minicomputer
4-bit microcomputer
8-bit microcomputer
16-bit microcomputer
32-bit microcomputer
64-bit microcomputer
Embedded computer
Personal computer
Desktop computer, Home computer, Laptop computer, Personal digital assistant (PDA), Portable computer, Tablet PC, Wearable computer
Theoretical/experimental
Quantum computer, Chemical computer, DNA computing, Optical computer, Spintronics based computer