Sie sind auf Seite 1von 152

UNIT 1 Syllabus:-Programming in C: Structure of C Program, Concept of Preprocessor, Macro Substitution,Intermediate code, Object Code, Executable Code.

Compilation Process,Basic Data types, Importance of braces ({ }) in C Program, enumerated data type, Identifiers,Scope of

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


Variable, Storage Class, Constants, Operators & Expressions in C, Type Casting,printf( ) and scanf ( ) with format specifires, reading single character. Structure of a C Program:C is a general-purpose high level language that was originally developed by Dennis Ritchie for the Unix operating system. It was first implemented on the Digital Eqquipment Corporation DP11 computer in 1972. The Unix operating system and virtually all Unix applications are written in the C language. C as now become a widely used professional language for various reasons.

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

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


All the C programs are writen into text files with extension ".c" for example hello.c. You can use "vi" editor to write your C program into a file. . C Compilers:When you write any program in C language then to run that program you need to compile that program using a C Compiler which converts your program into a language understandable by a computer. This is called machine language (ie. binary format). So before proceeding, make sure you have C Compiler available at your computer. It comes alongwith all flavors of Unix and Linux. If you are working over Unix or Linux then you can type gcc -v or cc -v and check the result. You can ask your system administrator or you can take help from anyone to identify an available C Compiler at your computer. If you don't have C compiler installed at your computer then you can use below given link to download a GNU C Compiler and use it. C language is very popular language among all the languages. Sometimes I think that had there been no "C" language there would have no C++ and even Java. So let me explain you the basic structure ofaClanguage. The structure of a C program is a protocol (rules) to the programmer, while writing a C program. The general basic structure of C program is shown in the figure below. The whole program is controlled within main ( ) along with left brace denoted by { and right braces denoted by }. If you need to declare local variables and executable program structures are enclosed within { and } is called the body of the main function. The main ( ) function can be preceded by documentation, preprocessor statements and global declarations.

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.

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


Preprocessor Statements:The preprocessor statement begin with # symbol and are also called the preprocessor directive. These statements instruct the compiler to include C preprocessors such as header files and symbolic constants before compiling the C program. Some of the preprocessor statements are listed below.

Figure:-header files & Symbolic constants

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

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


should be declared in the local declaration section is called local variables. Not only variables, we can also declare arrays, functions, pointers etc. These variables can also be initialized with basic data types. For examples. Code: Main ( ) { int sum = 0; int x; float y; } Here, the variable sum is declared as integer variable and it is initialized to zero. Other variables declared as int and float and these variables inside any function are called local variables. Program statements:These statements are building blocks of a program. They represent instructions to the computer to perform a specific task (operations). An instruction may contain an input-output statements, arithmetic statements, control statements, simple assignment statements and any other statements and it also includes comments that are enclosed within /* and */ . The comment statements are not compiled and executed and each executable statement should be terminated with semicolon. User defined functions:These are subprograms, generally, a subprogram is a function and these functions are written by the user are called user ; defined functions. These functions are performed by user specific tasks and this also contains set of program statements. They may be written before or after a main () function and called within main () function. This is an optional to the programmer. Now, let us write a small program to display some message shown below. Code: # include <stdio.h> main() { printf ("welcome to the world of C/n"); } C is a Structured programming language, so we have to write our C Programs in a Structured Format framed for it.

Header Files. main() {

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


C Statements and Functions; } Every C Statements should end with a semicolon (;). Based on this, we will write a Simple Hellow World program in C in the next Section. Hellow World Program in C hellow_world.c #include<stdio.h> #include<conio.h> void main() { printf("Hellow World in C"); 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. 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 :

206 FUNDAMENTAL OF COMPUTER PROGRAMMING

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.

206 FUNDAMENTAL OF COMPUTER PROGRAMMING

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.

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


Rules for declaring Variables in C :1. 2. 3. 4. 5. 6. 7. 8. The 1st letter should be alphabet. Variables can be combination of alphabets and digits. Underscore ( _ ) is the only special character allowed. Variables can be written in both Uppercase and Lowercase or combination of both. Variables are Case Sensitive. No Spaces allowed between Characters. Variable name should not make use to the C Reserved Keywords. Variable name should not start with a number.

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

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


Sample Program :variables.c #include<stdio.h> #include<conio.h> void main() { int i=10; float f=10.5; char c='s'; char s[10]="hellow"; printf("\n Integer : %d",i); printf("\n Float : %f",f); printf("\n Character : %c",c); 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 i of type int is declared and initialised with value of 10. 5. Variable f of type float is declared and initialised with value of 10.5. 6. Variable c of type char is declared and initialised with value of s. 7. Array s[] of type char with size 10 is declared and initialised with value of hellow. 8. Now i is displayed using control string %d, f using control string %f, c using control string %c, and array s using control string %s.

Output :

206 FUNDAMENTAL OF COMPUTER PROGRAMMING

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.

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


Output :

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

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


decimal places. Example:- 1.00, 100.50, etc 3) Character Constant : Character constant is used to store a single character. Example :- a, b, 1, 5 etc. 4) String constant : String Constants are used to store a string of characters. Example :- hi, welcome, 666 etc. Sample Program :constant.c #include<stdio.h> #include<conio.h> void main() { const int i=10; const float f=5.5; const char c='c'; const char *s="hellow"; printf("\n Integer Constant : %d",i); printf("\n Real Constant : %f",f); printf("\n Single Character Constant : %c",c); printf("\n String Constant : %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. Constant i of type int is declared and initialised with value of 10. 5. Constant f of type float is declared and initialised with value of 10.5. 6. Constant c of type char is declared and initialised with value of s. 7. Constant s of type char is declared and initialised with value of hellow. 8. Now i is displayed using control string %d, f using control string %f, c using control string %c, and s using control string %s.

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


Output :

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];

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


printf("Enter a character : "); scanf("%c",&ch); printf("Enter a No : "); scanf("%d",&no);

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 :

206 FUNDAMENTAL OF COMPUTER PROGRAMMING

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.

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


The unformatted output statements in C are putch, putchar and puts. Syntax for putch in C : putch(variable_name); putch displays any alphanumeric characters to the standard output device. It displays only one character at a time. Syntax for putchar in C : putchar(variable_name); putchar displays one character at a time to the Monitor. Syntax for puts in C : puts(variable_name); puts displays a single / paragraph of text to the standard output device. Sample program : gets_puts.c #include<stdio.h> #include<conio.h> void main() { char a[20]; gets(a); puts(a); getch(); } Program Algorithm / Explanation 1. #include<stdio.h> header file is included because, the C in-built statements gets and puts 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 char size 20 is declared.

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


5. gets is used to receive user input to the array. gets stops receiving user input only when the Newline character (Enter Key) is interrupted. 6. puts is used to display them back in the monitor. Output :

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>

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


#include<conio.h> void main() { funct(); getch(); } funct() { printf("hi, this is display from function funct()"); } Program Algorithm / Explanation : 1. #include<stdio.h> header file is included because, the C in-built statement printf and scanf 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. funct() is actually the function call to execute the function funct(). 5. Function funct() is written outside the main () function with no arguments and no return value. 6. printf is used to display the text hi, this is display from function funct(). 7. getch() is used to wait for key press so that displayed result can be viewed. Output :

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


2) Functions with arguments and no return value in C : Syntax : function_name(argument 1, - - - -, argument n) { Valid C Statements; } Sample Program : function2.c #include<stdio.h> #include<conio.h> void main() { int a,b; printf("Enter a value for a :"); scanf("%d",&a); printf("Enter a value for b :"); scanf("%d",&b); funct(a,b); getch(); } funct(int a1, int b1) { int c; c=a1+b1; printf("\n Result = %d",c); } 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 Integer variable a & b are declared. 5. printf is used to ask the user to input value of a and b and the same is received using scanf. 6. The values received in a & b are passed as arguments to function call funct(a,b). 7. The arguments from main() function are received in a1 & b1. funct(int a1, int b1). 8. Inside funct() a new variable c of type int is declared. 9. The values in a1 and b1 are added and stored in variable c.

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


10. The result in c are printed using printf. Output :

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;

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


printf("Enter a value for a :"); scanf("%d",&a); printf("Enter a value for b :"); scanf("%d",&b); c=a+b; return(c); } 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 result of type int is declared. int result; 5. Function call is assigned to variable result. result = funct() . 6. Inside function funct(), 3 variables a, b and c are declared of type int. 7. printf is used to prompt the user to Enter value for a & b. 8. scanf is used to receive the values of a and b. 9. The values received in a & b are added and stored in variable c. 10. The result in c is returned back using return(c). 11. Back in main() the returned value is stored in the variable result. result = funct() 12. And the value in result is displayed using printf. Output :

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


4) Functions with arguments and with return value in C : Syntax : data_type function_name(arguments) { Valid C Statements; return(value); } Sample Program : function4.c #include<stdio.h> #include<conio.h> void main() { int a,b,result; printf("Enter a value for a :"); scanf("%d",&a); printf("Enter a value for b :"); scanf("%d",&b); result=funct(a,b); getch(); } int funct(int a1, int b1) { int c; c=a1+b1; printf("\n Result = %d",c); return(c); } Program Algorithm / Explanation : 1. #include<stdio.h> header file is included because, the C in-built statement printf and scanf 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. Three variables a, b and result of type int are declared inside main(). 5. scanf is sued to receive user Input from a and b. 6. function call is made by passing a and b as arguments to funct() . 7. In function funct() the arguments passed from main() are received through a1 and b1. int funct(int a1, int b1)

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


8. Another variable c is declared inside funct(). 9. a1 and b1 are added and the result is stored in c. 10. The value in c is returned. return(c) 11. Back in main(), return value is stored in variable result.result = funct(a,b) 12. And the result is printed using printf. Output :

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

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


#include<stdio.h> #include<conio.h> void main() { int a,b; a=10; b=5; if(a>b) { printf("a is greater"); } 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. Two variables a&b of type int is declared. 5. Variable a is assigned a value of 10 and variable b with 5. 6. A if condition is used to check whether a is greater than b. if(a>b) 7. As a is greater than b the printf inside the if { } is executed with a message a is greater. Output :

2) if else in C : Syntax for if : if(condition) {

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


Valid C Statements; } else { Valid C Statements; } In if else if the condition is true the statements between if and else is executed. If it is false the statement after else is executed. if_else.c #include<stdio.h> #include<conio.h> void main() { int a,b; printf("Enter a value for a:"); scanf("%d",&a); printf("\nEnter a value for b:"); scanf("%d",&b); if(a>b) { printf("\n a got greater value"); } else { printf("\n b got greater value"); } printf("\n Press any key to close the Application"); 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. Two integer variable a and b are declared. 5. User Input values are received for both a and b using scanf. 6. An if else conditional statement is used to check whether a is greater than b. 7. If a is greater than b, the message a got greater value is displayed using printf. 8. If b is greater the message b got greater value is displayed.

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


Output :

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.

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


else_if.c #include<stdio.h> #include<conio.h> void main() { int a,b; printf("Enter a value for a:"); scanf("%d",&a); printf("\nEnter a value for b:"); scanf("%d",&b); if(a>b) { printf("\n a is greater than b"); } else if(b>a) { printf("\n b is greater than a"); } else { printf("\n Both a and b are equal"); } printf("\n Press any key to close the application"); 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. Two variables a & b of type int are declared. 5. Values for a & b are received from user through scanf. 6. if condition is used to check whether a is greater than b. if(a>b) If the condition is true the statement between if and else if is executed. 1. If the condition is not satisfied else if() condition is checked. Else if(b>a) If b is greater than a the statement between else if and else is executed. 1. If both the conditions are false the statement after else is executed.

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


Output :

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>

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


void main() { int a; printf("Enter a no between 1 and 5 : "); scanf("%d",&a); switch(a) { case 1: printf("You choosed One"); break; case 2: printf("You choosed Two"); break; case 3: printf("You choosed Three"); break; case 4: printf("You choosed Four"); break; case 5: printf("You choosed Five"); break; default : printf("Wrong Choice. Enter a no between 1 and 5"); break; } 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 a of type int is declared. 5. scanf is used to get the value from user for variable a. 6. variable a is included for switch case. switch(a). 7. If the user Input was 1 the statement inside case 1: will be executed. Likewise for the rest of the cases until 5. 8. But if the user Input is other than 1 to 5 the statement under default : will be executed.

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


Output :

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..");

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


g: 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. Two variables a & b of type int are declared. 5. User Inputs are received for a & b using scanf. 6. if condition is used to check whether a is greater than b. if(a>b). 7. if it is true goto statement is used to jump to the label first : and the statement under first : is executed and then again jump is performed to get to the end of the program. goto g: 8. if the condition is false a statement is used to jump to label second. goto second : and the statement under second : is executed. Output :

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

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


1) for Loop in C :Syntax : for(variable_initialisation;condition;increment/decrement) { Valid C Statements; } In for loop first the variable is initialised and checks for the condition. If the condition is true. The statement inside for loop will be executed. On the next cycle the initialised variable will be either incremented or decremented and again checks for the condition. If the condition is true, again the statement inside will be executed. This process will continue until the condition is true. Once the condition fails the control jumps out of for loop. for.c #include<stdio.h> #include<conio.h> void main() { int i,a=0; for(i=1;i<=10;i++) { printf("\n %d",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. A Variable of int i is declared. 5. A for loop is started and i is initialised as 1 and condition is if i less than or equal to 10. And i will be incremented. 6. On the first cycle, i=1 which means 1 is less than 10. so the condition is satisfied. 7. So the value of i is displayed using printf inside the for loop. 8. On the next cycle i is incremented. So now i becomes 2. 9. It again checks for the condition i<=10 means 2<=10. the condition is still satisfied, so i will displayed as 2.

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


10. The cycle continues until i is 10. When i becomes 11 the condition i<=10 fails. Eg : 11<=10 is false. So the control jumps out of for loop. Output :

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(); }

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


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 a of type int is declared and initialised with value of 1. int a = 1; 5. A while loop is started with condition a<11. a is initialised as 1 so 1<11 is true and hence the value of a is printed as 1 using printf. 6. Then a is incremented inside while loop a++; so a becomes 2. 7. while loop again checks for condition a<11, a is 2 so 2<11 is true and once again the value of a is printed. 8. The cycle continues until a is 10. When a becomes 11 condition fails. a<11 means 11<11 is false. 9. Hence control jumps out of while loop. Output :

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

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


#include<stdio.h> #include<conio.h> void main() { int a=1; do { printf("\n %d",a); a++; }while(a<5); 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 a of type int is declared and initialised as 1. 5. Now do while loop is used to print a. 6. On the 1st cycle no condition is checked and the value of a is printed. 7. The loop continues until a is 4. when a becomes 5 the condition (a<5) (i.e) (5<5) is false so the control jumps out of do while loop. Output :

dowhile1.c #include<stdio.h> #include<conio.h> void main()

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


{ int a=1; do { printf("\n %d",a); a++; }while(a<1); 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 a of type int is declared and initialised as 1. 5. Now do while loop is used to print a. 6. On the 1st cycle no condition is checked and the value of a is printed. 7. Then it checks for condition a<1. a is already 1 means 1<1 is false and so the control jumps out of do while loop. Output :

Arrays in C :Array can be defined as group of related data types that share a common name.For example : -

int a = 5; printf(%d,a); a=6; printf(%d,a);

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


In the above example at 1st printf() the value of a (i.e) 5 is printed. Then when a is assigned a value of 6 and then 6 is printed. This means in variables we can only replace that value. If we want many values to be stored simultaneously, we need to have as many variables declared, which will make things complicated.In such places arrays can be used. Only condition si, we can store only one type of datas in array (i.e) In Integer array we can store only nos in char array only characters cab be stored. Note:-Arrays always starts from location 0. There are three types of arrays in C, 1. Single Dimensional Array. 2. Two dimensional Array & 3. Multi Dimensional Array. 1) Single Dimensional Arrays in C :Syntax for declaring single dimensional array in C : data_type array_name[size]; single_array1.c #include<stdio.h> #include<conio.h> void main() { int a[5]={1,2,3,4,5}; printf("%d",a[0]); 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[5] which means size of the array is 5 and array locations starts from 0. 6. So when a[0] is printed using printf the very first data in our array 1 is printed.

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


Output :

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.

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


Output :

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.

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


8. Inside for loop values for array is received using scanf(%d,&a[i]). 9. Another for loop is used to print all the values of array. Output :

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(); }

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


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 two dimensional array is declared and initialised with values.int a[2][2]={{11m12},{21,23}}; 5. Nested for loop is used to print data in two dimensional array. 6. In the first cycle of for loop both i & j are 0, so the first data at location a[0][0] is displayed. 7. On the 2nd cycle i remains 0, whereas j is incremented to 1.So, a[0][1] is displayed. Output :

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++) {

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


for(j=0;j<n;j++) { printf(" %d",a[i][j]); } printf("\n"); } 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. Here the size of array is received from user input to variable n with scanf. 5. And that is used in for loop to receive user input for array using scanf. dynamically. 6. And they are displayed back using another for loop with printf. Output :

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.

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


Syntax for declaring a structure in C : struct structure_name { data_type variable_name 1; data_type variable_name n; }; Where, struct keyword. structure_name - user defined name. After declaring structure to access the datas (variables) inside the structure, we have to create structure variables. Syntax : struct structure_name structure_variable; Then datas inside structure can be accessed using, structure_variable.variable_name; Sample programs : structure_basic.c #include<stdio.h> #include<conio.h> void main() { struct employee { char name[20]; int age; }; struct employee emp={"sat",27}; printf("\n Name : %s",emp.name); printf("\n Age : %d",emp.age); getch(); }

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


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 with structure name employee is declared. 5. It got a char type array name[20] and a int type variable age. 6. Values are assigned to the structure using structure variable emp. struct employee emp={sat,27}; 7. And they are displayed using, structure_variable.variable. Output :

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(); }

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


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 with structure name employee is declared. 5. It got a char type array name[20] and a int type variable age. 6. Values for structure are received from user input using scanf. 7. And displayed using printf. Output :-

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;

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


}; struct emp emp_details[10]; printf("No of Emploees to be Entered : "); scanf("%d",&n); while(i<n) { printf("\n Enter Employee Name :"); scanf("%s",emp_details[i].emp_name); printf("\n Enter Employee No :"); scanf("%d",&emp_details[i].emp_no); i++; } printf("\n Entered Details are.."); while(j<n) { printf("\n Employee Name : %s",emp_details[j].emp_name); printf("\n Employee No : %d",emp_details[j].emp_no); j++; } 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. Three int type variables i, j &n are declared. i & j are assigned a value of 0. 5. A structure with structure name emp is declared with two members. char emp_name[40]; and int emp_no; 6. A structure variable is declared as a array. struct emp emp_details[10]; 7. scanf is sued to get user input for variable n. 8. A while statement is used to receive user input to structure member variables. while loop runs based on the value of n. 9. The received datas in structure are displayed using another while loop.

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


Output :

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(); }

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


display(char *name,int no) { printf(" Name : %s \n No : %d",name,no); } 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 with structure name emp is declared with two members. char emp_name[40]; int emp_no; 5. A structure variable d is declared to access structure member variables and the members are assigned values. struct emp d={sat,1} 6. Now the values are passed as arguments using structure_variable.structure_member to a function display().display(d.emp_name,d.emp_no); 7. The function display() receives the values from structure member to the function arguments name and no and the values are displayed using printf. Output :

structure_function1.c #include<stdio.h> #include<conio.h> struct emp { char emp_name[40]; int emp_no; }; void main() {

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


struct emp d={"sat",1}; display(d); getch(); } display(struct emp x) { printf(" Name : %s \n No : %d",x.emp_name,x.emp_no); } 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 with structure name emp is declared with two members. char emp_name[40]; int emp_no; 5. A structure variable d is declared to access structure member variables and the members are assigned values. struct emp d={sat,1} 6. Then the structure variable d itself passed as argument to function display()display(d); 7. In function display() the argument is received by creating a structure named x for the structure emp. display(struct emp x) 8. Now to print values, we use, structure_varaible.structure_member;x.emp_name,x.emp_no Output :

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


Structure within Structure using C :structure_in_structure.c #include<stdio.h> #include<conio.h> void main() { struct family_members { char dad[20]; char mom[20]; int kids; }; struct family { struct family_members family_name; }; struct family f; printf("\n Father's Name :"); scanf("%s",f.family_name.dad); printf("\n Mom's Name :"); scanf("%s",f.family_name.mom); printf("\n No of Kids :"); scanf("%d",&f.family_name.kids); printf("\n Daddy :%s",f.family_name.dad); printf("\n Momy :%s",f.family_name.mom); printf("\n Kids :%d",f.family_name.kids); 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 structure by name family_members is declared with 3 member variables.

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


5. Another structure by name family is declared. 6. Structure variable family_name for the structure family_members is declared in the 2nd structure family. 7. Then structure variable for the structure family is declared as f. 8. Now to access members of structure family_members we have to use,f.family_name.dad, f.family_name.mom, f.family_name.kids 9. scanf is used to receive user input for members of the structure. 10. And the received datas are displayed suing printf. Output :

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);

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


switch(j) { case india: printf("\n asia"); break; case uk: printf("\n europe"); break; case usa: printf("\n north america"); break; } 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 int type variable j is declared. 5. A enumeration data type countries is declared with 3 members. And the 1st member India is assigned a value of 1. 6. scanf is used to receive user input for j. 7. And variable j is used in switch case. 8. If j is 1 case India will be matched and the result will be asia. 9. If j is 2 case uk will be matched and the result will be Europe. Similarly, north America if j is 3. Output :

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


Pointers in CPointers are special variables which not only stores data to the memory but also keep track of those memory locations (address). Syntax for declaring Pointers in C : data_type *pointer_name; Pointer declarations are same as variable declaration, except that star(*) in the front of pointer name, pointer1.c #include<stdio.h> #include<conio.h> void main() { int *ptr,x=10; ptr=&x; printf("\n memory Address of X %d",&x); printf("\n memory Address of ptr %d",ptr); printf("\n %d",*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. Pointer variable *ptr is declared and also a int variable x with value of 10 is assigned. 5. The memory location of variable x is stored in pointer using &. ptr=&x; 6. Now printing ptr gives the memory address. 7. And printing *ptr gives the value 10, which we assigned in the variable . because pointer *ptr is assigned the memory location of variable x.

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


Output :

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 :

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


Pointer as array in C :pointer3.c #include<stdio.h> #include<conio.h> void main() { int i; char *ptr[2]={"hi","bye"}; for(i=0;i<2;i++) { printf("\n %s",ptr[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. Variable i of type int is declared. 5. Array pointer *ptr of type char with size 2 is declared and two datas are stored in it. 6. A for loop is used with condition to run twice in increment mode with the help of variable i. 7. On the first loop cycle i=0, so ptr[0] is printed which displays the 1st data hi and on next cycle i=1. so ptr[1] is printed which displays the 2nd data bye. Output :

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


Pointer as Function Arguments in C :pointer4.c #include<stdio.h> #include<conio.h> void main() { int a,b; printf("\n Enter the value of a :"); scanf("%d",&a); printf("\n Enter the value of b :"); scanf("%d",&b); sum(&a,&b); getch(); } sum(int *ptr1,int *ptr2) { int total; total=*ptr1+*ptr2; printf("\n Sum Value = %d",total); } 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 a & b of type int is declared. 5. User input is received for a & b using scanf. 6. Now the memory location of a and b are passed as arguments to a function call sum(). 7. Back in the function sum() the memory location are received through two int type pointer *ptr1 & *ptr2. 8. A int type variable total is declared and assigned with result adding datas of *ptr1 & *ptr2 . total=*ptr1+*ptr2; 9. And when total is printed the sum value of variable a+b is displayed.

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


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.

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


3. main() function is the place where C program execution begins. 4. A structure with structure name emp is declared with two data members emp_name[40] and emp_no. 5. A structure pointer variable *ptr is declared to access the member inside the structure. 6. Datas are received from user input using scanf and displayed using printf. Output :

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.

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


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 name[20] and pointer *ptr are declared. 5. User input is received to array name[] using scanf and the same is assigned to pointer ptr. 6. Now a while loop is used to display all the datas in pointer using,while(*ptr!='\0'). This will make sure while loop runs until the last data in pointer \0 is arrived. Output :

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(); }

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


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 int type variable i is declared and initialised with value of 0. 5. A char type array name[20] and pointer *ptr are declared. 6. User input is received to array name[] using scanf and the same is assigned to pointer ptr. 7. Now a while loop is used to display all the datas in pointer using,while(*ptr!='\0') 8. Inside the while loop variable i which had a initial value of 0 is incremented on each cycle of loop. 9. So when the loop cycle completes, I will have the count of characters and simply printing i will give us the string length. Output :

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() {

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


char a[30]; int l; printf("Enter a string : "); scanf("%s",&a); l=strlen(a); printf("\n Length of the Given String is : %d",l); 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 strlen() comes under it. 4. main() function is the place where C program execution begins. 5. A char type array a[30] is declared. 6. User input for array a is received using scanf. 7. C in-built function strlen() is used to determine the length of the given string in array a and the result is stored in variable l. 8. When variable l is printed the string length is displayed. Output :

2) strcpy() in C : This function copies the string from one variable to another variable. Syntax : strcpy(source_variable, destination_variable);

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


str_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); strcpy(b,a); 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 strcpy() 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 strcpy() is used to copy the datas from array a to array b. 8. Now when the arrays a & b are displayed both displays identical values. Output :

3) strncpy() in C :This function also copies the string from one variable to another variable, but only upto the specified length.

206 FUNDAMENTAL OF COMPUTER PROGRAMMING

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 :

206 FUNDAMENTAL OF COMPUTER PROGRAMMING

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(); }

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


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 strcmp() 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 and b using scanf. 7. C in-built function strcmp() is used to compare the values in a & b and the comparison result is returned to variable n. 8. A if condition is used to check whether the returned value in variable n is 0. 9. If it is 0 printf is used to display that both the strings are equal. If it is a non-zero value again printf is used to display that the given strings are not identical.

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 : ");

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


scanf("%s",&a); printf("Enter string two : "); scanf("%s",&b); n=stricmp(a,b); if(n==0) { printf("Both the Strings are Equal"); } else { printf("Strings are not Equal"); } 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 stricmp() 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 and b using scanf. 7. C in-built function stricmp is used to compare the value in a & b without any match case and the comparison result is returned to variable n. Output :

6) strncmp() in C : This function compares two strings only upto a specified length. They are case-sensitive. Syntax : strncmp(string1,string2,length);

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


strn_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=strncmp(a,b,3); if(n==0) { printf("Both the Strings are Equal upto the first 3 characters"); } else { printf("Strings are not Equal"); } 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 strncmp() 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 and b using scanf. 7. C in-built function strncamp() is used to compare the values of a & b upto a specified length (i.e. 3) and the comparison result is returned to variable n. 8. A if condition is used to check whether the returned value in variable n is 0. 9. If it is 0, printf is used to display that both the strings are equal. If it is a non-zero value again printf is used to display that the given strings are not identical. Output :

206 FUNDAMENTAL OF COMPUTER PROGRAMMING

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(); }

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


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 strnicmp() 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 and b using scanf. 7. C in-built function strnicmp() is used compare the values of a & b upto a specified length without any match case and the comparison result is returned to variable n. 8. A if condition is used to check whether the returned value in variable n is 0. 9. If it is 0, printf is used to display that both the strings are equal. If it is a non-zero value again printf is used to display that the given strings are not identical. Output :

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 : ");

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


scanf("%s",&a); printf("RESULT : %s",strlwr(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. 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 strlwr() comes under it. 4. main() function is the place where C program execution begins. 5. A char type array a[30] is declared. 6. User input for array a is received using scanf. 7. C in-built function strlwr() is used to display the given string in lower case. Output :

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 : ");

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


scanf("%s",&a); printf("RESULT : %s",strupr(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. 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 strupr() comes under it. 4. main() function is the place where C program execution begins. 5. A char type array a[30] is declared. 6. User input for array a is received using scanf. 7. C in-built function strupr() is used to display the given string in upper case. Output :

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() {

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


char a[30],*b; printf("Enter a string : "); scanf("%s",&a); b=strdup(a); printf("Entered String in a : %s",a); printf("\nDuplicated string : %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 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

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


#include<stdio.h> #include<conio.h> #include<string.h> void main() { char a[30],b[30],c[30]; printf("Enter string one : "); scanf("%s",&a); printf("Enter string two : "); scanf("%s",&b); strcat(a,b); printf("Concatinated String : %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. 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 strcat() 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 and b using scanf. 7. C in-built function strcat() is used to join the two strings(data) from array variable a & b. 8. When the array a is printed the concatenated string is displayed. Output :

13) strrev() in C :-This function is sued to reverse the characters in a given string. Syntax : strrev(string);

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


str_rev.c #include<stdio.h> #include<conio.h> #include<string.h> void main() { char a[30]; printf("Enter string : "); scanf("%s",&a); strrev(a); printf("Reversed String : %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. 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 strrev() comes under it. 4. main() function is the place where C program execution begins. 5. A char type array a[30] is declared. 6. scanf is used to receive user input to array a. 7. Then C in-built function strrev() is used to receive the string in array a and the same is displayed using printf. Output :

14) strset() in C :This function replaces all the characters of a string with a given symbol or character. Syntax : strset(string,symbol);

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


str_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); strset(a,b); 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. 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 strset() comes under it. 4. main() function is the place where C program execution begins. 5. A char type array a[30] is declared. 6. A variable b of type char is declared. 7. gets() is used to receive user input for array a. 8. scanf is used to receive a character symbol to variable b. 9. C in-built function strset() is used to replace all the characters in array a with symbol received in variable b. Output :

206 FUNDAMENTAL OF COMPUTER PROGRAMMING

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.

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


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 strnset() comes under it. 4. main() function is the place where C program execution begins. 5. A char type array a[30] is declared. 6. A variable b of type char is declared. 7. gets() is used to receive user input for array a. 8. scanf is used to receive a character symbol to variable b. 9. C in-built function strnset() is used to replace the character in array a with symbol received in variable b upto a specified length. In this case it is 2. Output :

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));

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


ptr=a; printf("%d",ptr); free(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. stdlib.h is used because malloc() comes under it. 4. int type variable a and pointer *ptr are declared. 5. Variable a is assigned a value of 10. 6. malloc() is used to allocate memory to pointer ptr. 7. The size given through malloc() to ptr is sizeof(int). 8. Now ptr is assigned the value of a. ptr=a; so the value 10 is assigned to ptr, for which, we dynamically allocated memory space using malloc. 9. The value in ptr is displayed using printf 10. Then allocated memory is freed using the C in-built function free(). Output :

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>

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


#include<conio.h> #include<stdlib.h> void main() { int *ptr,a[6]={1,2,3,4,5,6}; int i; ptr=(int*)calloc(a[6]*sizeof(int),2); for(i=0;i<7;i++) { printf("\n %d",*ptr+a[i]); } free(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. stdlib.h is used because malloc() comes under it. 4. A Pointer *ptr of type int and array a[6] is declared. 5. Array a[6] is assigned with 6 values. 6. Another variable i of type int is declared. 7. Calloc() is used to allocate memory for ptr. 6 blocks of memory is allocated with each block having 2 bytes of space. 8. Now variable i is used in for to cycle the loop 6 times on incremental mode. 9. On each cycle the data in allocated memory in ptr is printed using *ptr+a[i]. 10. Then the memory space is freed using free(ptr). Output :

Pre processors in C

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


#define in C :It is used to predefine a string for a identifier. Syntax : #define identifier string define.c #include<stdio.h> #include<conio.h> #define N 10 #define stop() getch() #define show printf #define getme scanf void main() { int a; show("Enter a No : "); getme("%d",&a); if(a>N) { show("The Entered No is greater than 10.."); } else { show("The No u have Entered is Less than 10.."); } stop(); } 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. Macro N is defined a value of 10. 4. stop() is defined by C in-build function getch(). 5. show is defined by C in-build statement printf. 6. getme is defined by C in-build statement scanf. 7. main () function is the place where C program execution begins. 8. int type variable a is declared 9. show in the printf is used to prompt the user to enter input data. 10. They are received in variable a using macro getme in the place of printf. 11. A if condition is used to check a>N (i.e) a>10

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


12. If the entered value is greater than 10 show is used to display The Entered No is greater than 10 13. Else the display The No u have Entered is less than 10. 14. Now Macro stop() is used in the place of getch() to wait for user key press. Output :

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(); }

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


add.h #include<stdio.h> void sum(int x,int y) { int z; z=x+y; printf("Sum Result : %d",z); } 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. A user defined header file add.h is included. 4. main() is the place where the program execution begins. 5. Two int type variable a & b are declared. 6. scanf is used to receive user input for a & b. 7. the function call is made with user-defined function sum() with two arguments a & b. 8. function sum() is pre-written in add.h header file. 9. A int type variable z is declared inside function sum() 10. Both the arguments are received to function sum() through the arguments x & y. 11. They are added and result is stored in z. 12. And displayed using printf. Output :

#ifdef in C : #ifdef is used to check whether a identifier is assigned a value. Syntax :

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


#ifdef identifier { statements; } #else { statements; } #endif #undef in C :Sometimes we have to restrict the defined macros to some part/module of our program. #undef is used to undefined a defined macro. Syntax : #undef identifier ifdef_undef.c #include<stdio.h> #include<conio.h> #define N 100 #ifdef N #undef N #define N 10 #endif void main() { printf("%d",N); 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. Macro N is defined a value of 100. 4. ifdef is used to check if N is defined. #ifdef N 5. If it is defined N is undefined using #undef N 6. And N is again defined this time with value of 10.

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


7. main() is the place where the program execution starts. 8. printf is sued to display N and the result is 10. Output :

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.

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


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. 4. Data type int is defined to nos. 5. Data type char is defined to alpha. 6. Now variable n is declared of type nos and assigned a value of 5. 7. Also array a[0] of type alpha is declared and assigned a value of hellow 8. Now n & nos are displayed using printf. Output :

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.

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


4. argc holds the total number of arguments received from command line and argv[] holds the actual arguments itself. 5. int type variable i is declared. 6. printf is used to display argc, which returns the number of arguments received from command line. 7. for loop is used to display all the arguments received in argv[]. Output :

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.

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


Syntax for fopen() in C fp=fopen(file_name with extension,mode);

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

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


fclose() is used to close a file in C. Syntax for fclose() fclose(fp);

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 :

206 FUNDAMENTAL OF COMPUTER PROGRAMMING

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!='~')

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


{ c=getche(); fputc(c,fp); } fclose(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 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);

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


while(!feof (fp)) { printf("%c",getc(fp)); } 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 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: ");

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


scanf("%s",&a); printf("Enter the New file name: "); scanf("%s",&b); rename(a,b); printf("\n File %s successfully renamed to %s in the disk..",a,b); 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. 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);

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


printf("%s",a); remove(a); printf("\n File %s successfully removed from disk..",a); 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 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

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


Preprocessor directives:-

Directive #define #undef #include #ifdef #endif #ifndef #if #else

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

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


Simple macro substitution:Simple string replacement is commonly used to define constants example:#define pi 3.1415926 Writing macro definition in capitals is a convention not a rule a macro definition can include more than a simple constant value it can include expressions as well. Following are valid examples: #define AREA 12.36 Macros as arguments:The preprocessor permits us to define more complex and more useful form of replacements it takes the following form. # define identifier(f1,f2,f3..fn) string. Notice that there is no space between identifier and left parentheses and the identifier f1,f2,f3 . Fn is analogous to formal arguments in a function definition. There is a basic difference between simple replacement discussed above and replacement of macro arguments is known as a macro call A simple example of a macro with arguments is # define CUBE (x) (x*x*x) If the following statements appears later in the program, volume=CUBE(side); The preprocessor would expand the statement to volume =(side*side*side) Nesting of macros: We can also use one macro in the definition of another macro. That is macro definitions may be nested. Consider the following macro definitions # define SQUARE(x)((x)*(x)) Undefining a macro:A defined macro can be undefined using the statement # undef identifier.

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


This is useful when we want to restrict the definition only to a particular part of the program. File inclusion: The preprocessor directive "#include file name can be used to include any file in to your program if the function s or macro definitions are present in an external file they can be included in your file In the directive the filename is the name of the file containing the required definitions or functions alternatively the this directive can take the form #include< filename > Without double quotation marks. In this format the file will be searched in only standard directories. The c preprocessor also supports a more general form of test condition #if directive. #if constant expression { statement-1; statemet2 . . } #endif the constant expression can be a logical expression such as test < = 3 etc C preprocessor The C preprocessor or cpp is the macro preprocessor for the C and C++ computer programming languages. The preprocessor provides the ability for the inclusion of header files, macro expansions, conditional compilation, and line control.In many C implementations, it is a separate program invoked by the compiler as the first part of translation.The language of preprocessor directives is agnostic to the grammar of C, so the C preprocessor can also be used independently to process other kinds of text files. Phases reprocessing is defined by the first four (of eight) phases of translation specified in the C Standard. 1. Trigraph replacement: The preprocessor replaces trigraph sequences with the characters they represent. 2. Line splicing: Physical source lines that are continued with escaped newline sequences are spliced to form logical lines. 3. Tokenization: The preprocessor breaks the result into preprocessing tokens and whitespace. It replaces comments with whitespace.

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


4. Macro expansion and directive handling: Preprocessing directive lines, including file inclusion and conditional compilation, are executed. The preprocessor simultaneously expands macros and, in the 1999 version of the C standard, handles _Pragma operators. The preprocessor replaces the line #include <stdio.h> with the text of the file 'stdio.h', which declares the printf() function among other things.This can also be written using double quotes, e.g. #include "stdio.h". If the filename is enclosed within angle brackets, the file is searched for in the standard compiler include paths. If the filename is enclosed within double quotes, the search path is expanded to include the current source directory. C compilers and programming environments all have a facility which allows the programmer to define where include files can be found. This can be introduced through a command line flag, which can be parameterized using a makefile, so that a different set of include files can be swapped in for different operating systems, for instance. By convention, include files are given a .h extension, and files not included by others are given a .c extension. However, there is no requirement that this be observed. Occasionally you will see files with other extensions included: files with a .def extension may denote files designed to be included multiple times, each time expanding the same repetitive content; #include "icon.xbm" is likely to refer to an XBM image file (which is at the same time a C source file). #include often compels the use of #include guards or #pragma once to prevent double inclusion. Conditional compilation:The #if, #ifdef, #ifndef, #else, #elif and #endif directives can be used for conditional compilation. #if VERBOSE >= 2 print("trace message"); #endif Most compilers targeting Microsoft Windows implicitly define _WIN32.[1] This allows code, including preprocessor commands, to compile only when targeting Windows systems. A few compilers define WIN32 instead. For such compilers that do not implicitly define the _WIN32 macro, it can be specified on the compiler's command line, using -D_WIN32. #ifdef __unix__ /* __unix__ is usually defined by compilers targeting Unix systems */ # include <unistd.h> #elif defined _WIN32 /* _Win32 is usually defined by compilers targeting 32 or 64 bit Windows systems */ # include <windows.h> #endif The example code tests if a macro __unix__ is defined. If it is, the file <unistd.h> is then included. Otherwise, it tests if a macro _WIN32 is defined instead. If it is, the file <windows.h> is then included.A more complex #if example can use operators, for example something like:

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


#if !(defined __LP64__ || defined __LLP64__) || defined _WIN32 && !defined _WIN64 // we are compiling for a 32-bit system #else // we are compiling for a 64-bit system #endif Translation can also be caused to fail by using the #error directive: #if RUBY_VERSION == 190 # error 1.9.0 not supported #endif Macro definition and expansion There are two types of macros, object-like and function-like. Object-like macros do not take parameters; function-like macros do. The generic syntax for declaring an identifier as a macro of each type is, respectively: #define <identifier> <replacement token list> // object-like macro #define <identifier>(<parameter list>) <replacement token list> // function-like macro, note parameters The function-like macro declaration must not have any whitespace between the identifier and the first, opening, parenthesis. If whitespace is present, the macro will be interpreted as object-like with everything starting from the first parenthesis added to the token list. A macro definition can be removed with "#undef": #undef <identifier> // delete the macro

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:

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


#define RADTODEG(x) ((x) * 57.29578) This defines a radians-to-degrees conversion which can be inserted in the code where required, i.e., RADTODEG(34). This is expanded in-place, so that repeated multiplication by the constant is not shown throughout the code. The macro here is written as all uppercase to emphasize that it is a macro, not a compiled function.The second x is enclosed in its own pair of parentheses, avoiding calculations in the wrong order if an expression instead of a single value is passed. For example, the expression RADTODEG(r + 1) is expanded correctly as ((r + 1) * 57.29578), instead of (r + 1 * 57.29578) which gives precedence to the multiplication without them. Similarly, the outer pair of parentheses maintain correct order of operation, such as in 1 / RADTODEG(r), which expands to 1 / ((r) * 57.29578) instead of the erroneous 1 / (r) * 57.29578 without them. Special macros and directives:Certain symbols are required to be defined by an implementation during preprocessing. These include __FILE__ and __LINE__, predefined by the preprocessor itself, which expand into the current file and line number. For instance the following: // debugging macros so we can pin down message origin at a glance #define WHERESTR "[file %s, line %d]: " #define WHEREARG __FILE__, __LINE__ #define DEBUGPRINT2(...) fprintf(stderr, __VA_ARGS__) #define DEBUGPRINT(_fmt, ...) DEBUGPRINT2(WHERESTR _fmt, WHEREARG, __VA_ARGS__) //... DEBUGPRINT("hey, x=%d\n", x); prints the value of x, preceded by the file and line number to the error stream, allowing quick access to which line the message was produced on. Note that the WHERESTR argument is concatenated with the string following it. The values of __FILE__ and __LINE__ can be manipulated with the #line directive. The #line directive determines the line number and the file name of the line below. Example:#line 314 "pi.c" printf("line=%d file=%s\n", __LINE__, __FILE__); generates the printf function: printf("line=%d file=%s\n", 314, "pi.c"); Source code debuggers refer also to the source position defined with __FILE__ and __LINE__. This allows source code debugging, when C is used as target language of a compiler, for a totally different language. The first C Standard specified that the macro __STDC__ be defined to 1 if

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


the implementation conforms to the ISO Standard and 0 otherwise, and the macro __STDC_VERSION__ defined as a numeric literal specifying the version of the Standard supported by the implementation. Standard C++ compilers support the __cplusplus macro. Compilers running in non-standard mode must not set these macros, or must define others to signal the differences.Other Standard macros include __DATE__, the current date, and __TIME__, the current time.The second edition of the C Standard, C99, added support for __func__, which contains the name of the function definition within which it is contained, but because the preprocessor is agnostic to the grammar of C, this must be done in the compiler itself using a variable local to the function. Macros that can take a varying number of arguments (variadic macros) are not allowed in C89, but were introduced by a number of compilers and standardised in C99. Variadic macros are particularly useful when writing wrappers to functions taking a variable number of parameters, such as printf, for example when logging warnings and errors. One little-known usage pattern of the C preprocessor is known as X-Macros. An X-Macro is a header file. Commonly these use the extension ".def" instead of the traditional ".h". This file contains a list of similar macro calls, which can be referred to as "component macros". The include file is then referenced repeatedly. Many compilers define additional, non-standard, macros, although these are often poorly documented. A common reference for these macros is the Pre-defined C/C++ Compiler Macros project, which lists "various pre-defined compiler macros that can be used to identify standards, compilers, operating systems, hardware architectures, and even basic run-time libraries at compile-time". Token concatenation The ## operator concatenates two tokens into one token, as in this example: #define DECLARE_STRUCT_TYPE(name) typedef struct name##_s name##_t DECLARE_STRUCT_TYPE(g_object); // Outputs typedef struct g_object_s g_object_t; User-defined compilation errors The #error directive outputs a message through the error stream. #error "error message" Implementations Compiler-specific preprocessor features The #pragma directive is a compiler specific directive which compiler vendors may use for their own purposes. For instance, a #pragma is often used to allow suppression of specific error

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


messages, manage heap and stack debugging and so on. A compiler with support for the OpenMP parallelization library can automatically parallelize a for loop with #pragma omp parallel for.C99 introduced a few standard #pragma directives, taking the form #pragma STDC ..., which are used to control the floating-point implementation.

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

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


$(macroname:string1=string2) Macro substitution is case sensitive and is literal; string1 and string2 cannot invoke macros. Substitution does not modify the original definition. You can substitute text in any predefined macro except $$@.No spaces or tabs precede the colon; any after the colon are interpreted as literal. If string2 is null, all occurrences of string1 are deleted from the macro's definition string.

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

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


max(i++, j++) /* WRONG */ will increment the larger twice. Some care also has to be taken with parentheses to make sure the order of evaluation is preserved; consider what happens when the macro #define square(x) x * x /* WRONG */ is invoked as square(z+1). Nonetheless, macros are valuable. One practical example comes from <stdio.h>, in which getchar and putchar are often defined as macros to avoid the run-time overhead of a function call per character processed. The functions in <ctype.h> are also usually implemented as macros. Names may be undefined with #undef, usually to ensure that a routine is really a function, not a macro: #undef getchar int getchar(void) { ... } Formal parameters are not replaced within quoted strings. If, however, a parameter name is preceded by a # in the replacement text, the combination will be expanded into a quoted string with the parameter replaced by the actual argument. This can be combined with string concatenation to make, for example, a debugging print macro: #define dprint(expr) printf(#expr " = %g\n", expr) When this is invoked, as in dprint(x/y) the macro is expanded into printf("x/y" " = &g\n", x/y); and the strings are concatenated, so the effect is printf("x/y = &g\n", x/y); Within the actual argument, each " is replaced by \" and each \ by \\, so the result is a legal string constant. The preprocessor operator ## provides a way to concatenate actual arguments during macro expansion. If a parameter in the replacement text is adjacent to a ##, the parameter is replaced by the actual argument, the ## and surrounding white space are removed, and the result is rescanned. For example, the macro paste concatenates its two arguments: #define paste(front, back) front ## back so paste(name, 1) creates the token name1. Code generation (compiler):In computer science, code generation is the process by which a compiler's code generator converts some intermediate representation of source code into a form (e.g., machine code) that can be readily executed by a machine.Sophisticated compilers typically perform multiple passes over various intermediate forms. This multi-stage process is used because many algorithms for code optimization are easier to apply one at a time, or because the input to one optimization relies on the processing performed by another optimization. This organization also facilitates the

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


creation of a single compiler that can target multiple architectures, as only the last of the code generation stages (the backend) needs to change from target to target. (For more information on compiler design, see Compiler.) The input to the code generator typically consists of a parse tree or an abstract syntax tree. The tree is converted into a linear sequence of instructions, usually in an intermediate language such as three address code. Further stages of compilation may or may not be referred to as "code generation", depending on whether they involve a significant change in the representation of the program. (For example, a peephole optimization pass would not likely be called "code generation", although a code generator might incorporate a peephole optimization pass.) Major tasks in code generation:In addition to the basic conversion from an intermediate representation into a linear sequence of machine instructions, a typical code generator tries to optimize the generated code in some way.Tasks which are typically part of a sophisticated compiler's "code generation" phase include:

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

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


generating less efficient code, JIT code generation can take advantage of profiling information that is available only at runtime. The fundamental task of taking input in one language and producing output in a non-trivially different language can be understood in terms of the core transformational operations of formal language theory. Consequently, some techniques that were originally developed for use in compilers have come to be employed in other ways as well. For example, YACC (Yet Another Compiler Compiler) takes input in Backus-Naur form and converts it to a parser in C. Though it was originally created for automatic generation of a parser for a compiler, yacc is also often used to automate writing code that needs to be modified each time specifications are changed. Many integrated development environments (IDEs) support some form of automatic source code generation, often using algorithms in common with compiler code generators, although commonly less complicated. (See also: Program transformation, Data transformation.) Reflection:In general, a syntax and semantic analyzer tries to retrieve the structure of the program from the source code, while a code generator uses this structural information (e.g., data types) to produce code. In other words, the former adds information while the latter loses some of the information. One consequence of this information loss is that reflection becomes difficult or even impossible. To counter this problem, code generators often embed syntactic and semantic information in addition to the code necessary for execution. Intermediate language:In computer science, an intermediate language is the language of an abstract machine designed to aid in the analysis of computer programs. The term comes from their use in compilers, where a compiler first translates the source code of a program into a form more suitable for codeimproving transformations, as an intermediate step before generating object or machine code for a target machine. The design of an intermediate language typically differs from that of a practical machine language in three fundamental ways:

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.

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


Intermediate representation An intermediate representation (IR) is a data structure that is constructed from input data to a program, and from which part or all of the output data of the program is constructed in turn. Use of the term usually implies that most of the information present in the input is retained by the intermediate representation, with further annotations or rapid lookup features. A canonical example is found in most modern compilers, where the linear human-readable text representing a program is transformed into an intermediate graph data structure that allows flow analysis and re-arrangements before starting to create the list of actual CPU instructions that will do the work. Use of an intermediate representation allows compiler systems like LLVM to be targeted by many different source languages, and support generation for many different target architectures. Languages Though not explicitly designed as an intermediate language, C's nature as an abstraction of assembly and its ubiquity as the de facto system language in Unix-like and other operating systems has made it a popular intermediate language: Eiffel, Sather, Esterel, some dialects of Lisp (Lush, Gambit), Haskell (Glasgow Haskell Compiler), Squeak's Smalltalk-subset Slang, Cython, Seed7, Vala, and others make use of C as an intermediate language. Variants of C have been designed to provide C's features as a portable assembly language, including one of the two languages called C-- and the C Intermediate Language. Sun Microsystem's Java bytecode is the intermediate language used by all compilers targeting the Java Virtual Machine. The JVM can then do just-in-time compilation to get executable machine code to improve performance. Similarly, Microsoft's Common Intermediate Language is an intermediate language designed to be shared by all compilers for the .NET Framework, before static or dynamic compilation to machine code. The GNU Compiler Collection (GCC) uses internally several intermediate languages to simplify portability and cross-compilation. Among these languages are

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-

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


Latin above hexadecimal 7f) are syntactically incorrect when used for identifier names (even if some compilers may accept such identifiers). Comments, strings and character literals should not contain non-ASCII characters. Non-ASCII characters and control characters (hexadecimal 0 to 1f, with the exception of newline, carriage return, tabulator and formfeed) may confuse editors or may even lead to unexpected results on some compilers (e.g. ^Z misinterpreted as end-of-file, most significant bit stripped on non-ASCII characters, etc.). There is no means of notation of the encoding type of a source file (unlike with mail messages). C offers nice ASCII-notations for non-ASCII characters, e.g. '\xe8'. Coding language:To let the sources be globally readable, the lingua franca of computer science, english, should exclusively be used. As with other parts of the C coding guidelines: the smaller the scope context, the less strict the rule. Customizing your program's user interface to a local language (i.e. internationalization in the stricter sense) can be done with locales and e.g. the gettext() family of functions. These functions let you use compiled text databases for the different ISO language codes, while leaving your C sources still readable, i.e. (english) strings are still present in the code. Identifier names Identifier names are used to name functions, variables, types (typedefs, structs, unions, enums), type members, macros, etc. There are of course many styles of choosing identifier names. One important rule is to be consequent about naming. The smaller the scope of a name, the less important a good choice of the name is. E.g. it is less important to chose a speaking and somewhat systematic name for a small scope index variable8 than it is for an exported library function. Using capable development environments (the ones that let you jump to definition and declaration of a function) makes it less important to express type and package membership in a function name. The aspect of which natural language to use for names has already been covered. Name styles There are several methods to get readable names:

use of underscore characters(e.g. get_name) use of upper case initials (e.g. GetName)

206 FUNDAMENTAL OF COMPUTER PROGRAMMING

use of natural language context (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).

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


Compiler warnings I demand that you can compile your sources without warnings at the highest compiler warning level. The time saved by using the compiler's hints is typically more than the time spent to keep the sources warning-less. Some third party libraries or even compilation systems(!) may include header files that produce annoying warnings when compiled with the highest warning level. I recommend to encapsulate the offending interface declarations in a code layer that meets the warning-less requirement If the source code is to be distributed and will be used on a variety of systems, it should be revised for warning-less compile on several compilers and/or computer/operating systems. You may also want to do cross-compiles. Compiler warnings may be a hint of incompatibilities. E.g. the warning "possible bad alignment" may not be an error on CISC CPU architecture systems, but will be one on RISC systems. Compiling C code as C++ code may reveal C/C++ incompatibilities, specially with assignments from and to void*. Style warnings Some compiler warnings reveal bad coding style rather than errors or incompatibilities. These bad styles should be avoided. The warning "assignment in conditional expression" can be avoided by using while((p = next()) != 0) instead of while(p = next()). The warning "conditional expression is constant" can be avoided by using for(;;) instead of while(1). The "unreferenced parameter" warning is a tough one in the C language. Suggestions were: casting to void (does not suppress the warning on all compilers) and self assignment (looks weird and lets me think of a "statement has no effect" warning). Asserts (assert.h) may produce "statement has no effect" warnings in the release version. This one seems to be tough. The "comparison of signed and unsigned values" warning appears if signed and unsigned values are mixed in a less/greater expression. One approach is not to use unsigned values at all. strlen() may unfortunately require an int cast. Lint lint is a traditional Unix development tool, originally designed for K&R1. It allows

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)

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


Metrics Metrics are a means to quantify some code characteristics. These quantifications can be used to achieve a desired level of commenting or modularization, etc. Simple metrics count e.g. the

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

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


Nested expressions C is an orthogonal language. It allows to chain and nest expressions. This evokes the following problems:

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

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


Header files that are intern to a software component should be included with #include "header.h", header files that are extern to the component should be included with #include <header.h>. I tend to prefer the extern include, if a header file can be seen to declare stuff that's independent of the component, despite the fact that usually -I. compiler options are necessary to indicate where to find the header files. Header files must be included by both the implementing module and the calling module(s). Note that the inclusion in the implementing module is not enforced by the compiler and the linker will link independently of actual function parameter types. As mentioned above, it's wrong to declare static functions in a header file or to not define functions as static that are only used in one module. Header files should use include guards to enable (intended or unintended) multiple inclusion: #ifndef header_h #define header_h ... #endif Header files must not be included by an absolute path (e.g. /usr/include/header.h), paths can be specified in compiler options (-L/usr/include). Using relative paths is correct (e.g. sys/header.h), however using .. seems confusing (e.g. ../header.h). Code order There are two traditional styles of code order (i.e. order of functions in a source file). Pascal style defines a function before it is referenced. C style defines a function after it is referenced. There are some aspects to consider about the order of the code in a source file:

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

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


fp = fopen(file, "r"); if(fp != 0) process(fp); else return -1; It is more readable since it doesn't add one layer of indentation per condition and the 'process' part above may be large and tear the blocks quite apart. Conditional compiling The opinions about conditional compiling differ. Programmers either

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

application scope file scope function scope block scope

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

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


Variables can have all four kinds of scope: application scope, file scope, function scope, block scope. The variable scope should be as small as possible. The opinions about using variable declarations in block scope differ. Typically, there is no overhead (stack pointer operations) involved with block scope variables, space for the deepest possible block allocation gets reserved at function entry. Application scope leads to global variables, which generally should be avoided. Use functions to access the data (getX() and setX()) instead. Application scope or file scope (as well as static data in functions) lets the functions that access the data only be useable by a single thread. A reference to a calling functions buffer should be used instead of global or static data to avoid multithreading problems and buffer overwrite problems (e.g. as with localtime()). Scope of types Types should be limited to file scope or application scope in my opinion, since it is a rare case that only one method (function) acts on a type (that is then in function scope). Scope of macros macro encapsulating code fragments as #undef m #define m ... ...code... #undef m have been seen. They allow to hide macros from the rest of the source file. However, the general problems with macro names remain. Error prone constructs C keeps, unlike some other languages, some error prone constructs ready. As a sample, Java doesn't pose problems with explicit casts, array sizes, buffer sizes, macros and less problems with error checking (through the use of exceptions). Lisp e.g. doesn't pose problems with number ranges. Explicit casts Compilers do not generate errors or warnings on semantically false explicit casts. The explicit casts are accepted as is. Use explicit casts as rarely as possible. It's good to think whether an explicit casts is necessary and what the compiler will do with it.

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


The C language allows implicit conversions from T* to void* and vice versa. There is no explicit cast needed in C to convert from void*. malloc() is a sample of an often used function that returns void*. Array size There are several methods to refer to an array size (sample array being int a[32];):

32 SIZE (a macro used for the array definition) sizeof(a)/sizeof(*a)

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.

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


Macro parameters Macro parameters must be protected to ensure operator precedence. #define sqr(x) x*x sqr(a+b) will have unwanted side effects, where #define sqr(x) ((x)*(x)) sqr(a+b) will have less side effects. Note the protection of the parameters and the result. Macro side effects Side effects are inevitable if macro parameters appear more than once, example:#define max(a,b) ((a)>(b)?(a):(b)) k = max(i++,j++); The task of a macro can be implemented in a function, if not in a performance critical part of the code. Looking at the compiler output will show whether function inlining (as compiler optimization step) produces the same result that would be expected from macro expansion. Sign extension Sign extension must be considered if a signed char is converted to a short or long or a signed short is converted to a long. A typical sample is the sign extension from character to integer: char* p; ... printf("0x%02x", *p); may rather print 0xffffffe4 than an intended 0xe4. The character needs a cast to unsigned before the conversion: printf("0x%02x", (unsigned char)*p); Optimizer errors Sometimes hard-to-track errors origin from errors in the compiler optimizer step. The optimizer may e.g. look at a variable as invariant and produce erroneous code. There are two considerations:

Do most of the development without optimization. Look at the assembly output if you suspect errors.

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


When (and if) switching to optimized release code, test cases must be run to check integrity. Numbers Numbers (numeric constants) should not appear in the code. Explicitly used numbers should be limited to 0, 1 and -1. Define the numbers as constants, macros or enums outside the functions. They should especially not appear in the code if they're meaningful for limitations or performance of an algorithm (e.g. if they limit some input size). Counterexamples are

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

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


shorts and longs. Sample: struct {short a; long b;}; will most probably be eight bytes of size, not six. Floats Avoid floating point numbers (double, float) if possible. Reasons being :

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) ...

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


if(p == 0) ... if(p == NULL) ...

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

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


between. Goto labels can be adjusted to the left margin (i.e. top level block), one indent level less than the next statement, or on the same level as the next statement. The first two styles are more readable. Be consequent about placing the labels. Comments A programmer may decide to create only comments on lines of their own. You might include some evident information in every C source file:

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() {}

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


Like all C language functions, first comes the function's name, main, then comes a set of parentheses, and finally comes a set of braces, also called curly braces. If your C program contains only this line of code, you can run it. It won't do anything, but that's perfect because the program doesn't tell the computer to do anything. Even so, the operating system found the main() function and was able to pass control to that function which did nothing but immediately return control right back to the operating system. It's a perfect, flawless program.

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.

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


The enumerators are necessarily distinct, even though some languages may allow the same enumerator to be listed twice in the type's declaration. The enumerators need not be complete or compatible in any sense. For example, an enumerated type called color may be defined to consist of the enumerators RED, GREEN, ZEBRA, MISSING, and BACON. In some languages, the declaration of an enumerated type also defines an ordering of its members. Some enumerator types may be built into the language. The Boolean type, for example is often a pre-defined enumeration of the values FALSE and TRUE. Many languages allow the user to define new enumerated types. Values and variables of an enumerated type are usually implemented as fixed-length bit strings, often in a format and size compatible with some integer type. Some languages, especially system programming languages, allow the user to specify the bit combination to be used for each enumerator. In type theory, enumerated types are often regarded as tagged unions of unit types. Since such types are of the form , they may also be written as natural numbers. Some early programming languages did not originally have enumerated types. If a programmer wanted a variable, for example myColor, to have a value of red, the variable red would be declared and assigned some arbitrary value, usually an integer constant. The variable red would then be assigned to myColor. Other techniques assigned arbitrary values to strings containing the names of the enumerators. These arbitrary values were sometimes referred as magic numbers since there often was no explanation as to how the numbers were obtained or whether their actual values were significant. These magic numbers could make the source code harder for others to understand and maintain. Enumerated types, on the other hand, made the code more self-documenting. Depending on the language, the compiler could automatically assign default values to the enumerators thereby hiding unnecessary detail from the programmer. These values may not even be visible to the programmer. Enumerated types can also prevent a programmer from writing illogical code such as performing mathematical operations on the values of the enumerators. If the value of a variable that was assigned an enumerator were to be printed, some programming languages could also print the name of the enumerator rather than its underlying numerical value. Conceptually speaking, an enumerated type is similar to a list of nominals, since each possible value of the type is assigned a distinctive natural number. A given enumerated type is thus a concrete implementation of this notion. When order is meaningful and/or used for comparison, then an enumerated type becomes an ordinal type. C and syntactically similar languages The original K&R dialect of the C programming language did not have enumerated types, but they were added in the ANSI standard for C, which became C89. In C, enumerations are created by explicit definitions, which use the enum keyword and are reminiscent of struct and union definitions:

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


enum cardsuit { CLUBS, DIAMONDS, HEARTS, SPADES }; struct card { enum cardsuit suit; short int value; } hand[13]; enum cardsuit trump; C exposes the integer representation of enumeration values directly to the programmer. Integers and enum values can be mixed freely, and all arithmetic operations on enum values are permitted. It is even possible for an enum variable to hold an integer that does not represent any of the enumeration values. In fact, according to the language definition, the above code will define CLUBS, DIAMONDS, HEARTS, and SPADES as constants of type int, which will only be converted (silently) to enum cardsuit if they are stored in a variable of that type. C also allows the programmer to choose the values of the enumeration constants explicitly, even without type. For example, enum cardsuit { CLUBS = 1, DIAMONDS = 2, HEARTS = 4, SPADES = 8 }; could be used to define a type that allows mathematical sets of suits to be represented as an enum cardsuit by bitwise logic operations. C# Enumerated types in the C# programming language preserve most of the "small integer" semantics of C's enums. Some arithmetic operations are not defined for enums, but an enum value can be explicitly converted to an integer and back again, and an enum variable can have values that were not declared by the enum definition. For example, given enum Cardsuit { Clubs, Diamonds, Spades, Hearts }; the expressions CardSuit.Diamonds + 1 and CardSuit.Hearts - CardSuit.Clubs are allowed directly (because it makes sense to step through the sequence of values or ask how many steps

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


there are between two values), but CardSuit.Hearts*CardSuit.Spades is deemed to make less sense and is only allowed, if the values are first converted to integers. The enumeration definition defines names for the selected integer values and is syntactic sugar, as it is possible to assign to an enum variable other integer values that are not in the scope of the enum definition. C++ C++ has enumeration types that are directly inherited from C's and work mostly like these, except that an enumeration is a real type in C++, giving additional compile-time checking. Also (as with structs) the C++ "enum" keyword is automatically combined with a "typedef", so that instead of calling the type "enum name", one simply calls it "name." This can be simulated in C using a typedef: "typedef enum {TYPE1, TYPE2} name;" C++11 provides a second, "type-safe" enumeration type, which is not implicitly converted to an integer type. This is specified by the phrase "enum class". For example: enum class Color {Red, Green, Blue}; Java The J2SE version 5.0 of the Java programming language added enumerated types whose declaration syntax is similar to that of C's: enum Cardsuit { CLUBS, DIAMONDS, SPADES, HEARTS }; ... Cardsuit trump; The Java type system, however, treats enumerations as a type separate from integers, and intermixing of enum and integer values is not allowed. In fact, an enum type in Java is actually a special compiler-generated class rather than an arithmetic type, and enum values behave as global pre-generated instances of that class. Enum types can have instance methods and a constructor (the arguments of which can be specified separately for each enum value). All enum types implicitly extend the Enum abstract class. An enum type cannot be instantiated directly. Internally, each enum value contains an integer, corresponding to the order in which they are declared in the source code, starting from 0. The programmer cannot set a custom integer for an enum value directly, but one can define overloaded constructors that can then assign arbitrary values to self-defined members of the enum class. Defining getters allows then access to those self-defined members. The internal integer can be obtained from an enum value using the ordinal () method, and the list of enum values of an enumeration type can be obtained in order using the values() method. It is generally discouraged for programmers to convert enums to integers and vice versa. Enumerated types are Comparable, using the internal integer; as a result, they can be sorted.

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


The Java standard library provides utility classes to use with enumerations. The EnumSet class implements a Set of enum values; it is implemented as a bit array, which makes it very compact and as efficient as explicit bit manipulation, but safer. The EnumMap class implements a Map of enum values to object. It is implemented as an array, with the integer value of the enum value serving as the index. C Identifiers "Identifiers" or "symbols" are the names you supply for variables, types, functions, and labels in your program. Identifier names must differ in spelling and case from any keywords. You cannot use keywords (either C or Microsoft) as identifiers; they are reserved for special use. You create an identifier by specifying it in the declaration of a variable, type, or function. In this example, result is an identifier for an integer variable, and main and printf are identifier names for functions. #include <stdio.h> int main() { int result; if ( result != 0 ) printf_s( "Bad file handle\n" ); } Once declared, you can use the identifier in later program statements to refer to the associated value. The first character of an identifier name must be a nondigit (that is, the first character must be an underscore or an uppercase or lowercase letter). ANSI allows six significant characters in an external identifier's name and 31 for names of internal (within a function) identifiers. External identifiers (ones declared at global scope or declared with storage class extern) may be subject to additional naming restrictions because these identifiers have to be processed by other software such as linkers.

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.

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


1. The case of the alphabetic character is significant. Using "INDEX" for a variable is not the same as using "index" and neither of them is the same as using "InDex" for a variable. All three refer to different variables.

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

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


atomic number, corresponding one-to-one with element name Australian Business Number CAGE code CAS registry number CODEN Digital object identifier (DOI, doi) DIN standard number E number EC number Employer Identification Number (EIN) Global Trade Item Number Group identifier International Chemical Identifier International Standard Book Number (ISBN) International Standard Serial Number (ISSN) ISO standard number, e.g., ISO 8601 Library of Congress Control Number personal identification number Personal identification number (Denmark) U.S. international many scopes, e.g., specific computer systems international ISBN-13 is part of the EAN Namespace; international scope international international U.S., with some international bibliographic usefulness many scopes, e.g., banks, governments Denmark international (via ISV) Australian U.S. and NATO originated in U.S.; today international (via ISV) originated in U.S.; today international Handle System Namespace, international scope originated in Germany; today international originated in E.U.; may be seen internationally

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


Product batch number Serial Item and Contribution Identifier U.S., with some international bibliographic usefulness many scopes, e.g., company-specific, government-specific

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

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


We have already looked at the most basic of assignment operators, the = operator. This assignment operator simply assigns the result of an expression to a variable. In essence, the = assignment operator takes two operands. The left hand operand is the variable to which a value is to be assigned and the right hand operand is the value to be assigned. The right hand operand is, more often than not, an expression which performs some type of arithmetic or logical evaluation, the result of which will be assigned to the variable. The following examples are all valid uses of the assignment operator: int x; // declare the variable x = 10; // Assigns the value 10 to a variable named x x = y + z; // Assigns the result of variable y added to variable z to variable x x = y; // Assigns the value of variable y to variable x Assignment operators may also be chained to assign the same value to multiple variables. For example, the following code example assigns the value 20 to the x, y and z variables: int x, y, z; x = y = z = 20; Objective-C Arithmetic Operators Objective-C provides a range of operators for the purpose of creating mathematical expressions. These operators primarily fall into the category of binary operators in that they take two operands. The exception is the unary negative operator (-) which serves to indicate that a value is negative rather than positive. This contrasts with the subtraction operator (-) which takes two operands (i.e. one value to be subtracted from another). For example: int x = -10; // Unary - operator used to assign -10 to a variable named x x = y - z; // Subtraction operator. Subtracts z from y

The following table lists the primary Objective-C arithmetic operators: Operator Description -(unary) Negates the value of a variable or expression * / Multiplication Division

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


+ % Addition Subtraction Modulo

Table:- the primary Objective-C arithmetic operators

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:

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


Operator Description x += y x -= y x *= y x /= y x %= y x &= y x |= y x ^= y Add x to y and place result in x Subtract y from x and place result in x Multiply x by y and place result in x Divide x by y and place result in x Perform Modulo on x and y and place result in x Assign to x the result of logical AND operation on x and y Assign to x the result of logical OR operation on x and y Assign to x the result of logical Exclusive OR on x and y

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:

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


int x = 9; int y; y = ++x; In the next example, however, the value of x (9) is assigned to variable y before the decrement is performed. After the expression is evaluated the value of y will be 9 and the value of x will be 8. int x = 9; int y; y = x--; Comparison Operators In addition to mathematical and assignment operators, Objective-C also includes set of logical operators useful for performing comparisons. These operators all return a Boolean (BOOL) true (1) or false (0) result depending on the result of the comparison. These operators are binary operators in that they work with two operands. Comparison operators are most frequently used in constructing program flow control logic. For example an if statement may be constructed based on whether one value matches another: if (x == y) // Perform task The result of a comparison may also be stored in a BOOL variable. For example, the following code will result in a true (1) value being stored in the variable result: BOOL result; int x = 10; int y = 20; result = x < y; Clearly 10 is less than 20, resulting in a true evaluation of the x < y expression. The following table lists the full set of Objective-C comparison operators: Operator Description x == y x>y x >= y Returns true if x is equal to y Returns true if x is greater than y Returns true if x is greater than or equal to y

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


x<y x <= y x != y Returns true if x is less than y Returns true if x is less than or equal to y Returns true if x is not equal to y

Table:- comparison operators

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:

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


if ((10 < 20) ^ (20 < 10)) NSLog (@"Expression is true"); If both operands evaluated to be true or both were false the expression would return false. The Ternary Operator Objective-C uses something called a ternary operator to provide a shortcut way of making decisions. The syntax of the ternary operator (also known as the conditional operator) is as follows: [condition] ? [true expression] : [false expression] The way this works is that [condition] is replaced with an expression that will return either true (1) or false (0). If the result is true then the expression that replaces the [true expression] is evaluated. Conversely, if the result was false then the [false expression] is evaluated. Let's see this in action: int x = 10; int y = 20; NSLog(@"Largest number is %i", x > y ? x : y ); The above code example will evaluate whether x is greater than y. Clearly this will evaluate to false resulting in y being returned to the NSLog call for display to the user: 2009-10-07 11:14:06.756 t[5724] Largest number is 20 Bitwise Operators In the chapter entitled Objective-C 2.0 Data Types we talked about the fact that computers work in binary. These are essentially streams of ones and zeros, each one referred to as a bit. Bits are formed into groups of 8 to form bytes. As such, it is not surprising that we, as programmers, will occasionally end up working at this level in our code. To facilitate this requirement, Objective-C provides a range of bit operators. Those familiar with bitwise operators in other languages such as C, C++, C# and Java will find nothing new in this area of the Objective-C language syntax. For those unfamiliar with binary numbers, now may be a good time to seek out reference materials on the subject in order to understand how ones and zeros are formed into bytes to form numbers. Other authors have done a much better job of describing the subject than we can do within the scope of this book. For the purposes of this exercise we will be working with the binary representation of two numbers. Firstly, the decimal number 171 is represented in binary as: 10101011

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


Secondly, the number 3 is represented by the following binary sequence: 00000011 Now that we have two binary numbers with which to work, we can begin to look at the Objective-C's bitwise operators: Bitwise AND The Bitwise AND is represented by a single ampersand (&). It makes a bit by bit comparison of two numbers. Any corresponding position in the binary sequence of each number where both bits are 1 results in a 1 appearing in the same position of the resulting number. If either bit position contains a 0 then a zero appears in the result. Taking our two example numbers, this would appear as follows: 10101011 AND 00000011 ======== 00000011 As we can see, the only locations where both numbers have 1s are the last two positions. If we perform this in Objective-C code, therefore, we should find that the result is 3 (00000011): int x = 171; int y = 3; int z; z = x & y; // Perform a bitwise AND on the values held by variables x and y NSLog(@"Result is %i", z); 2009-10-07 15:38:09.176 t[12919] Result is 3 Bitwise OR The bitwise OR also performs a bit by bit comparison of two binary sequences. Unlike the AND operation, the OR places a 1 in the result if there is a 1 in the first or second operand. The operator is represented by a single vertical bar character (|). Using our example numbers, the result will be as follows: 10101011 OR 00000011 ======== 10101011

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


If we perform this operation in an Objective-C example we see the following: int x = 171; int y = 3; int z; z = x | y; NSLog(@"Result is %i", z);

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:

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


10101011 Left Shift one bit ======== 01010110 In Objective-C the bitwise left shift operator is represented by the '<<' sequence, followed by the number of bit positions to be shifted. For example, to shift left by 1 bit: int x = 171; int z; z = x << 1; NSLog(@"Result is %i", z); When compiled and executed, the above code will display a message stating that the result is 342 which, when converted to binary, equates to 101010110. Bitwise Right Shift A bitwise right shift is, as you might expect, the same as a left except that the shift takes place in the opposite direction. Note that since we are shifting to the right there is no opportunity to retain the lower most bits regardless of the data type used to contain the result. As a result the low order bits are discarded. Whether or not the vacated high order bit positions are replaced with zeros or ones depends on whether the sign bit used to indicate positive and negative numbers is set or not and, unfortunately, on the particular system and Objective-C implementation in use. 10101011 Right Shift one bit ======== 01010101 The bitwise right shift is represented by the '>>' character sequence followed by the shift count: int x = 171; int z; z = x >> 1; NSLog(@"Result is %i", z); When executed, the above code will report the result of the shift as being 85, which equates to binary 01010101. Compound Bitwise Operators As with the arithmetic operators, each bitwise operator has a corresponding compound operator that allows the operation and assignment to be performed using a single operator:

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


Operator Description x &= y x |= y x ^= y x <<= n x >>= n Perform a bitwise AND of x and y and assign result to x Perform a bitwise OR of x and y and assign result to x Perform a bitwise XOR of x and y and assign result to x Shift x left by n places and assign result to x Shift x right by n places and assign result to x

Table:- Compound Bitwise Operators

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

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


4 A a; 5 B b=a;

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

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


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

More on printf & scanf Format Specifiers :

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);

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


} a equals 72 a equals H b equals 65 b equals A The reason why this works is because a character constant is just an integer from 0 to 255. Two or More Format Specifiers:

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!

Minimum Field Width:

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);

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


return 0; } Output: Printing 123 using %0d displays 123 Printing 123 using %1d displays 123 Printing 123 using %2d displays 123 Printing 123 using %3d displays 123 Printing 123 using %4d displays 123 Printing 123 using %5d displays 123 Printing 123 using %6d displays 123 Printing 123 using %7d displays 123 Printing 123 using %8d displays 123 Printing 123 using %9d displays 123 Notice that in the first 4 cases, 123 is displayed in the same way as when you normally

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

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


parameter(s). The input string is by default read from the standard input, but variants exist that read the input from other sources. Usage The scanf function, which is found in C, reads input for numbers and other datatypes from standard input (often a command line interface or similar kind of a text user interface). The following shows code in C that reads a variable number of unformatted decimal integers from the console and prints out each of them on a separate line:

#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)

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


{ char word[20]; if (scanf("%19s", &word) == 1) puts(word); return 0; } No matter what the datatype the programmer wants the program to read, the arguments (such as &n above) must be pointers pointing to memory. Otherwise, the function will not perform correctly because it will be attempting to overwrite the wrong sections of memory, rather than pointing to the memory location of the variable you are attempting to get input for. As scanf is designated to read only from standard input, many programming languages with interfaces, such as PHP, have derivatives such as sscanf and fscanf but not scanf itself. Format string specifications The formatting placeholders in scanf are more or less the same as that in printf, its reverse function. There are rarely constants (i.e. characters that are not formatting placeholders) in a format string, mainly because a program is usually not designed to read known data. The exception is one or more whitespace characters, which discards all whitespace characters in the input. Some of the most commonly used placeholders follow:

%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.

206 FUNDAMENTAL OF COMPUTER PROGRAMMING

%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

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


exploitable for buffer overflows. Another potential problem is to allow dynamic formatting strings, for example formatting strings stored in configuration files or other user controlled files. In this case the allowed input length of string sizes can not be specified unless the formatting string is checked beforehand and limitations are enforced. Related to this are additional or mismatched formatting placeholders which do not match the actual vararg list. These placeholders might be partially extracted from the stack, contain undesirable or even insecure pointers depending on the particular implementation of varargs.

Topic beyond the syllabus


History of Computers:A computer is a general purpose device that can be programmed to carry out a finite set of arithmetic or logical operations. Since a sequence of operations can be readily changed, the computer can solve more than one kind of problem. Conventionally, a computer consists of at least one processing element, typically a central processing unit (CPU) and some form of memory. The processing element carries out arithmetic and logic operations, and a sequencing and control unit that can change the order of operations based on stored information. Peripheral devices allow information to be retrieved from an external source, and the result of operations saved and retrieved. The first electronic digital computers were developed between 1940 and 1945 in the United Kingdom and United States. Originally they were the size of a large room, consuming as much power as several hundred modern personal computers (PCs). In this era mechanical analog computers were used for military applications. Modern computers based on integrated circuits are millions to billions of times more capable than the early machines, and occupy a fraction of the space. Simple computers are small enough to fit into mobile devices, and mobile computers can be powered by smallbatteries. Personal computers in their various forms are icons of the Information Age and are what most people think of as "computers". However, the embedded computers found in many devices from mp3 players to fighter aircraft and from toys to industrial robots are the most numerous.

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

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


though, like some mechanical aids to computing, which were very successful and survived for centuries until the advent of the electronic calculator, like the Sumerian abacus, designed around 2500 BC of which a descendant won a speed competition against a modern desk calculating machine in Japan in 1946,the slide rules, invented in the 1620s, which were carried on five Apollo space missions, including to the moon and arguably the astrolabe and the Antikythera mechanism, an ancient astronomical computer built by the Greeks around 80 BC.The Greek mathematician Hero of Alexandria (c. 1070 AD) built a mechanical theater which performed a play lasting 10 minutes and was operated by a complex system of ropes and drums that might be considered to be a means of deciding which parts of the mechanism performed which actions and when.This is the essence of programmability. Around the end of the 10th century, the French monk Gerbert d'Aurillac brought back from Spain the drawings of a machine invented by the Moors that answered either Yes or No to the questions it was asked.Again in the 13th century, the monks Albertus Magnus andRoger Bacon built talking androids without any further development (Albertus Magnus complained that he had wasted forty years of his life when Thomas Aquinas, terrified by his machine, destroyed it). In 1642, the Renaissance saw the invention of the mechanical calculator a device that could perform all four arithmetic operations without relying on human intelligence.The mechanical calculator was at the root of the development of computers in two separate ways. Initially, it was in trying to develop more powerful and more flexible calculators that the computer was first theorized byCharles Babbage and then developed. Secondly, development of a lowcost electronic calculator, successor to the mechanical calculator, resulted in the development by Inte lof the first commercially available microprocessor integrated circuit.

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

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


nevertheless his son, Henry Babbage, completed a simplified version of the analytical engine's computing unit (the mill) in 1888. He gave a successful demonstration of its use in computing tables in 1906. This machine was given to the Science museum in South Kensington in 1910. In the late 1880s, Herman Hollerith invented the recording of data on a machine-readable medium. Earlier uses of machine-readable media had been for control, not data. "After some initial trials with paper tape, he settled on punched cards ..." To process these punched cards he invented the tabulator, and the keypunch machines. These three inventions were the foundation of the modern information processing industry. Large-scale automated data processing of punched cards was performed for the 1890 United States Census by Hollerith's company, which later became the core of IBM. By the end of the 19th century a number of ideas and technologies, that would later prove useful in the realization of practical computers, had begun to appear: Boolean algebra, the vacuum tube (thermionic valve), punched cards and tape, and the teleprinter. During the first half of the 20th century, many scientific computing needs were met by increasingly sophisticated analog computers, which used a direct mechanical or electrical model of the problem as a basis for computation. However, these were not programmable and generally lacked the versatility and accuracy of modern digital computers. The ENIAC, which became operational in 1946, is considered to be the first general-purpose electronic computer. EDSAC was one of the first computers to implement the stored-program (von Neumann) architecture. The AtanasoffBerry Computer (ABC) was the world's first electronic digital computer, albeit not programmable. Atanasoff is considered to be one of the fathers of the computer.Conceived in 1937 by Iowa State College physics professor John Atanasoff, and built with the assistance of graduate student Clifford Berry, the machine was not programmable, being designed only to solve systems of linear equations. The computer did employ parallel computation. A 1973 court ruling in a patent dispute found that the patent for the 1946 ENIAC computer derived from the AtanasoffBerry Computer.

Semiconductors and microprocessors


Computers using vacuum tubes as their electronic elements were in use throughout the 1950s, but by the 1960s they had been largely replaced by transistor-based machines, which were smaller, faster, cheaper to produce, required less power, and were more reliable. The first

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


transistorised computer was demonstrated at the University of Manchester in 1953.In the 1970s, integrated circuit technology and the subsequent creation ofmicroprocessors, such as the Intel 4004, further decreased size and cost and further increased speed and reliability of computers. By the late 1970s, many products such as video recorders contained dedicated computers called microcontrollers, and they started to appear as a replacement to mechanical controls in domestic appliances such as washing machines. The 1980s witnessed home computers and the now ubiquitous personal computer. With the evolution of the Internet, personal computers are becoming as common as the television and the telephone in the household.

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.

206 FUNDAMENTAL OF COMPUTER PROGRAMMING

History of computing hardware:-

Calculators First generation (mechanical/electromechanical) Programmable devices

Antikythera mechanism, Difference engine, Norden bombsight

Jacquard loom, Analytical engine, Harvard Mark I, Z3

Calculators

AtanasoffBerry Computer, IBM 604, UNIVAC 60, UNIVAC 120

Second generation (vacuum tubes) Programmable devices

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

IBM 7090, IBM 7080, IBM System/360, BUNCH

PDP-8, PDP-11, IBM System/32, IBM System/36

Minicomputer Fourth generation (VLSI integrated circuits)

VAX, IBM System i

4-bit microcomputer

Intel 4004, Intel 4040

8-bit microcomputer

Intel 8008, Intel 8080, Motorola 6800, Motorola 6809, MOS

206 FUNDAMENTAL OF COMPUTER PROGRAMMING


Technology 6502, Zilog Z80

16-bit microcomputer

Intel 8088, Zilog Z8000, WDC 65816/65802

32-bit microcomputer

Intel 80386, Pentium, Motorola 68000, ARM architecture

64-bit microcomputer

Alpha, MIPS, PARISC, PowerPC, SPARC, x86-64

Embedded computer

Intel 8048, Intel 8051

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

Table:- History of computing hardware