Full Transcript

Computer Programming Contents C Fundamentals- – Introduction to C – Decision Control Structures – Loop Control Structures Data Types, Functions and Pointers in C The C Preprocessor and Arrays- – Arrays – Pointers – Multidime...

Computer Programming Contents C Fundamentals- – Introduction to C – Decision Control Structures – Loop Control Structures Data Types, Functions and Pointers in C The C Preprocessor and Arrays- – Arrays – Pointers – Multidimensional Arrays Strings, Structures and I/O Bitwise Operators, Secondary Data Types & Linked Lists Learning Objectives – Understand Data and Data Types – Implement Structured Data Types like Arrays, Records, and (Disjoint) Unions, and perform operations on them. – Implement Dynamic Memory Management, Dynamic Allocation and Deallocation, Incremental Allocation, Incrementally allocated Lists (linked lists) and perform operations on them. – Understand code modularity and practice it to improve reusability Books “The Waite Group’s Turbo C Programming for PC”, Robert Lafore, SAMS Teach Yourself C : Herbert Schildt Programming in ANSI C- E. Balagurusamy What is C? C A language written by Brian Kernighan and Dennis Ritchie. This was to be the language that UNIX was written in to become the first "portable" language. In recent years C has been used as a general- purpose language because of its popularity with programmers. Why use C? Mainly 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 Mainly because of the portability that writing standard C programs can offer History In 1972 Dennis Ritchie at Bell Labs writes C and in 1978 the publication of The C Programming Language by Kernighan & Ritchie caused a revolution in the computing world In 1983, the American National Standards Institute (ANSI) established a committee to provide a modern, comprehensive definition of C. The resulting definition, the ANSI standard, or "ANSI C", was completed late 1988. Why C Still Useful? C provides:  Efficiency, high performance and high quality  flexibility and power  many high-level and low-level operations  middle level  Stability and small size code  Provide functionality through rich set of function libraries  Gateway for other professional languages like C  C++  Java C is used:  System software Compilers, Editors, embedded systems  data compression, graphics and computational geometry, utility programs  databases, operating systems, device drivers, system level routines  there are zillions of lines of C legacy code  Also used in application programs Software Development Method Requirement Specification – Problem Definition Analysis – Refine, Generalize, Decompose the problem definition Design – Develop Algorithm Implementation – Write Code Verification and Testing – Test and Debug the code Development with C Four stages  Editing: Writing the source code by using some IDE or editor  Preprocessing or libraries: Already available routines  compiling: translates or converts source to object code for a specific platform source code -> object code  linking: resolves external references and produces the executable module  Portable programs will run on any machine but…..  Note! Program correctness and robustness are most important than program efficiency Programming languages Various programming languages Some understandable directly by computers Others require “translation” steps – Machine language Natural language of a particular computer Consists of strings of numbers(1s, 0s) Instruct computer to perform elementary operations one at a time Machine dependant Programming languages Assembly Language – English like abbreviations – Translators programs called “Assemblers” to convert assembly language programs to machine language. – E.g. add overtime to base pay and store result in gross pay LOAD BASEPAY ADD OVERPAY STORE GROSSPAY Programming languages High-level languages – To speed up programming even further – Single statements for accomplishing substantial tasks – Translator programs called “Compilers” to convert high-level programs into machine language – E.g. add overtime to base pay and store result in gross pay grossPay = basePay + overtimePay History of C Evolved from two previous languages – BCPL , B BCPL (Basic Combined Programming Language) used for writing OS & compilers B used for creating early versions of UNIX OS Both were “typeless” languages C language evolved from B (Dennis Ritchie – Bell labs) ** Typeless – no datatypes. Every data item occupied 1 word in memory. History of C Hardware independent Programs portable to most computers Dialects of C – Common C – ANSI C ANSI/ ISO 9899: 1990 Called American National Standards Institute ANSI C Case-sensitive C Standard Library Two parts to learning the “C” world – Learn C itself – Take advantage of rich collection of existing functions called C Standard Library Avoid reinventing the wheel Basics of C Environment C systems consist of 3 parts – Environment – Language – C Standard Library Development environment has 6 phases – Edit – Pre-processor – Compile – Link – Load – Execute Steps in learning C Character Tokens Instructions Programs Set C Character Set C Character Set Source Execution Character Set Character Set Alphabets Digits Special White Escape Characters Spaces Sequence C Character Set (Cont) Source Character Set – It is used to construct the statements in the program. Executable Character Set – These characters are employed at the time of execution i.e. they have effects only when the program is being executed. Source Character Set Letters a to z ,A to Z Digits 0 to 9 Special Characters !@#$%^&*()_-+ = \ | { } [ ] etc,. White Spaces Blank Space ,Horizontal tab, New line, Vertical tab etc,. Special characters Comma , Period or dot. Semicolon ; Colon : Apostrophe ‘ Quotation mark “ Exclamation mark ! Vertical bar | Back Slash \ Tilde ~ Underscore - Dollar $ Question mark ? Ampersand & Caret ^ Asterisk * Minus - Addition + Lesser than < Greater than > Parenthesis () Bracket [] Braces {} Percentage % Hash # Equal to = At the rate @ Executable Character Set Characters Escape Sequence Back Space \b Horizontal Space \t Vertical Space \v Newline \n C Tokens The smallest element in the C language is the token. It may be a single character or a sequence of characters. C Tokens (Cont) C Tokens Identifiers Keywords Constants Strings operators spI symbol Eg:main, Eg: int, Eg:17, Eg: “ab” Eg: + Eg: # avg for 15.5 - $% Executing a C Program Creating the Program Compilation Linking Execution Executing a C Program (Cont) Enter the program in a C editor. Save the program (File  Save) or F2. Use the extension.c for saving the file. Eg: sample.c Compile the program(Compile  Compile) or Alt+F9. Run the program(Run  Run) or Ctrl+F9. Executing C program using UNIX Enter the program in vi editor. Save the file using :wq Use the extension.c for saving the file. Eg: sample.c Compile the program. Eg: cc sample.c (or) gcc sample.c Run the program using a.out. Structure of C program DOCUMENTATION SECTION PREPROCESSOR SECTION DEFINITION SECTION GLOBAL DECLARATION SECTION main() { Declaration part; Executable Part; } sub program section { Body of the subprogram; } Documentation Section – It contains the comment lines. Preprocessor Section – It is used to link library files. Global Declaration Section – The Global declaration section comes at the beginning of the program and they are visible to all parts of the program. Declaration Section – It describes the data to be used within the function. Executable Part – It contains the valid statements. C Programs  C program may have many functions.  One and only one of the functions MUST BE named main.  main is the starting point for the program.  main and other functions in a program are divided into two sections, declaration section and statement section. Preprocessor Directives Special instructions to the preprocessor that tells how to prepare the program for compilation E.g: include : tells the processor to include information from selected libraries known as header files e.g. Comments (Program documentation)  The compiler simply ignores comments when it translates the program into executable code.  To identify a comments, C uses opening comment tokens. Comments (Cont)  Comments can appear anywhere in a program.  Comments are also found wherever it is necessary to explain a point about a code.  Comments cannot be nested in C i.e. you cannot have comments inside comments. C program Comments # include Preprocessor Section Global Declaration void main () { Local declaration printf (“Hello World! \n”); Statements } Output : Hello World C Tokens Identifiers Keywords Constants Operators Special symbols Identifiers Identifiers are names given to various program elements such as variables, functions and arrays etc,. Eg: #define N 10 #define a 15 Here N and a are user defined identifiers. Rules for naming identifier First character must be alphabetic or underscore. Must consist only of alphabetic characters, digits, or underscores. Only the first 31 characters of an identifier are significant and are recognized by the compiler. Cannot use a keywords or reserved word (e.g. main, include, printf & scanf etc.). No space are allowed between the identifiers etc,. C is case sensitive, e.g. My_name  my_name. Examples of Valid and Invalid Names Valid Names Invalid Names a a1 $sum student_name stdntNm 2names _aSystemName _anthrSysNm stdnt Nmbr TRUE FALSE int Variables Variable is an identifier that is used to represent some specified type of information. Eg: x=3 Here x is variable. Keywords It is a reserved words. Cannot be used for anything else. Examples: – int – while – for etc,. Keywords Auto register Continue Double typedef For Int Char signed Struct extern void Break return Default Else union Goto Long Const sizeof Switch Float do Case short If Enum unsigned Static While Constants It is an entity whose value does not changes during the execution. Eg: x=3 Here 3 is a constant. Types Numeric constants Character constant Constants Constants Numeric Constants Character Constants Integer Real Single String Constant Constant Character Constant Constant Numeric constants Integer constants It is formed using a sequence of digits. Decimal - 0 to 9. Octal - 0 to 7. Hexa - 0 to 9 ,A to F Eg: 10,75 etc. Rules for defining Integer Constant It must have atleast one digit. Decimal point are not allowed. No blank space or commas are allowed. It can be either positive or negative. Etc,. Numeric constants Real constants It is formed using a sequence of digits but it contain decimal point. length, height, price distance measured in real number Eg: 2.5, 5.11, etc. Character constants Single character constant – A character constant is a single character they also represented with single digit or a single special symbol which is enclosed in single quotes. – Eg: ‘a’, ‘8’,’_’etc. Character constants String constants String constant are sequence of characters enclosed with in double quote. Eg: “Hello” ,”444”,”a” etc,. Operators An operator is a symbol that specifies an operation to be performed on the operands. Eg: a + b + is an operator. a,b are operands. Data Types  A Data type is the type of data that are going to access within the program. Standard Data Types These Standard type can be used to build more complex data types called Derived Types (e.g. pointers, array, union etc.). Data types Data type Size(bytes) Range Format string Char 1 -128 to 127 %c int 2 -32,768 to 32,767 %d Float 4 3.4 e-38 to 3.4 e+38 %f Double 8 1.7 e-308 to 1.7 e+308 %lf integer  A number without a fraction part : integral number.  C supports three different sizes of the integer data type :  short int  int  long int Floating Point  A floating-point type is a number with a fractional part, e.g. 56.78  Floating point numbers are stored using 4 Byte.  Types  Float  Double  long double character Character are generally stored using 8 bits(1 Byte) of the internal storage. Character ASCII code value a 97(decimal) or 01100001(binary) x 120(decimal) or 01111000(binary) void  The void type has no values and no operations.  Both the set of values and the set of operations are empty. Variable’s Declaration  To create a variable, you must specify the type and then its identifier : float price; int a,b; char code; Entire Data types in c: Data type Size(bytes) Range Format string Char 1 128 to 127 %c Unsigned char 1 0 to 255 %c Short or int 2 -32,768 to 32,767 %i or %d Unsigned int 2 0 to 65535 %u Long 4 -2147483648 to 2147483647 %ld Unsigned long 4 0 to 4294967295 %lu Float 4 3.4 e-38 to 3.4 e+38 %f or %g Double 8 1.7 e-308 to 1.7 e+308 %lf Long Double 10 3.4 e-4932 to 1.1 e+4932 %lf Types of Operator Arithmetic operator Relational operator Logical operator Assignment operator Increment or decrement operator(unary) Bitwise operator Conditional operator Arithmetic operator It is used to carry out arithmetic operations like addition, subtraction etc, Eg: + , - , * , / etc, Sample program #include // Header File #include int b=10; //Global Declaration void main ( ) { int a,c; //Local Declaration clrscr( ); scanf(“%d”,&a); printf(“ \n The sum of the two values:”); c = a+b; printf(“%d”,c); getch( ); } Division operator on Different Data Type Operation Result Example int/int int 5/2 = 2 int/real real 5/2.0 = 2.5 real/int real 5.0/2 = 2.5 real/real real 5.0/2.0 = 2.5 Sample program #include #include void main ( ) { int a=10,b=4,c; float d=3,e; clrscr( ); c = a/b; printf(" \n value a/b is:%d",c); e = a/d; printf("\n value a/d is:%f",e); getch( ); } Output value a/b is:2 value a/d is:3.333333 Relational operator It is used to compare two or more operands. Eg :< , > , =, != etc,. 5 < 9 which will return 1 Logical operator It is used to combine the result of two or more condition. AND(&&) OR (||) NOT (!) are Logical operators. Eg: (i>10)&&(j>5). (i>10)||(j>5) etc,. Sample program #include #include void main ( ) { int a=10,b=3,c=5,e; clrscr( ); if(a>b) // relational operator { printf(" \n a is bigger than b"); } if((a>b)&&(a>c)) //Logical operator { printf(" \n a is biggest"); } getch( ); } Output a is bigger than b a is biggest Assignment operator It is used to assign a value or expression etc to a variable. Eg: a =10. a=b a = b + c etc,. Assignment operator(Cont) Compound operator It is also used to assign a value to a variable. Eg: x + = y means x = x + y Nested operator It is used for multiple assignment. Eg: i = j = k = 0; Sample program #include #include int b=10; void main ( ) { int a=3,b=5; clrscr( ); a+=b; // a= a+b printf(" \n The sum of the two values:%d",a); getch( ); } Output The sum of the two values:8 Increment or decrement operator(Unary) It is used to Increment or decrement an operand. Eg: ++x (Pre Increment), x++ (Post Increment), --x (Pre Decrement), x-- (Post Decrement). Sample Program #include #include void main ( ) { int a=5; clrscr( ); printf(" \n Post increment Value:%d",a++); printf(" \n Pre increment Value:%d",++a); printf(" \n Pre decrement Value:%d",--a); printf(" \n Post decrement Value:%d",a--); getch( ); } Output Post increment Value:5 Pre increment Value:7 Pre decrement Value:6 Post decrement Value:6 Bitwise operator It is used to manipulate data at bit level. Eg: a=5 i.e 0000 0101 b=4 i.e 0000 0100 Then a & b = 0000 0100 a | b = 0000 0101 etc,. Sample program #include #include void main ( ) { int a=5,b=4,c; //char a=5,b=4,c; clrscr( ); c = a&b; printf(" \n value a&b is:%d",c); getch( ); } Output value a&b is:4 Conditional Operator (or) Ternary Operator It is used to checks the condition and execute the statement depending on the condition. Eg: C = a > b ? a:b Sample Program #include #include void main ( ) { int a=5,b=8,c; clrscr( ); c = a>b?a:b; //Conditional operator printf(" \n The Larger Value is%d",c); getch( ); } Output The Larger Value is 8 Special Operator comma operator ( , ) sizeof operator pointer operator (& , *) etc,. #include #include void main ( ) { int c; clrscr( ); printf(" \n size of int is:%d",sizeof c); getch( ); } Output size of int is: 2 Expression An expression represent data item such as variable, constant are interconnected using operators. Eg: Expression C Expression a+b+c a+b+c a2+b2 a*a + b*b Operator Precedence & Associativity The arithmetic expressions evaluation are carried out based on the precedence and associativity. The evaluation are carried in two phases. – First Phase: High Priority operators are evaluated. – Second Phase: Low Priority operators are evaluated. Precedence Operator High *,/,% Low +,- Example 5 - 20/4 + 3*3 – 1 =5-5+9–1 =0+9–1 =9–1 =8 Example 5 – (20/4) + 3*(3 – 1) = 5 - 5 + 3*2 =5-5+6 =6 Type Conversion Converting the type of an expression from one type to another type. Eg: x = (int)10.45 Sample Program #include #include void main ( ) { int c; clrscr( ); c=(int)10.45; printf("\nOutput is:%d",c); getch( ); } OUTPUT Output is:10 Input/Output Function Input/Output Function Formatted Unformatted Input Output Input Output scanf() printf() getc() putc() fscanf() fprintf() gets() puts() getchar() putchar() Formatted Input/Output  C uses two functions for formatted input and output.  Formatted input : reads formatted data from the keyboard.  Formatted output : writes formatted data to the monitor. Formatted Input and Output Standard Output  The standard output file is the monitor.  Like the keyboard, it is a text file.  When you need to display data that is not text, it must be converted into to the text before it is written to the screen. Format of printf Statement Formatted Input (scanf) The standard formatted input function in C is scanf (scan formatted). scanf consists of :  a format string.  an address list that identifies where data are to be placed in memory. scanf ( format string, address list ); (“%c….%d…..%f…..”, &a,….&i,…..,&x…..) Format of scanf Statement Character Test Function It is used to test the character taken from the input. isalpha(ch) isdigit(ch) islower(ch) isupper(ch) tolower(ch) toupper(ch) etc,. Decision Making It is used to change the order of the program based on condition. Categories: – Sequential structure – Selection structure – Iteration structure – Encapsulation structure Decision Making (cont) Sequential structure – In which instructions are executed in sequence. Selection structure – In which instruction are executed based on the result of some condition. Iteration structure – In which instruction are executed repeatedly. Encapsulation structure – In which some compound structure are used. SELECTION STRUCTURE It allows the program to make a choice from alternative paths. C provide the following selection structures – IF statement – IF … ELSE statement – Nested IF … ELSE statement – IF … ELSE ladder IF Statement Syntax IF (condition is true) { True If condition Statements; Statements False } #include Example #include void main ( ) { int a; clrscr( ); printf("\nEnter the number:"); scanf("%d",&a); if(a>10) { printf(" \n a is greater than 10"); } getch( ); } Output Enter the number: 12 a is greater than 10 IF…ELSE Statement Syntax IF (condition) { If True False True statements; Condition } ELSE True False { statements statements False statements; } #include #include void main ( ) { int a; clrscr( ); printf("\nEnter the number:"); scanf("%d",&a); if(a>10) { printf(" \n a is greater than 10"); } else { printf(" \n a is less than 10"); } getch( ); } NESTED IF… ELSE If Condition 1 False True Statements If True False Condition 2 True False statements statements NESTED IF… ELSE Syntax IF (condition1) { IF (condition2) { True statements; } ELSE { False statements; } } ELSE { False statements; } IF…ELSE LADDER TRUE Condition FALSE 1 TRUE Condition FALSE Statements 2 TRUE Condition FALSE Statements 3 Statements Statements Syntax IF…ELSE LADDER IF (condition1) { statements; } else if (condition2) { statements; } else if (condition3) { statements; } else { statements; } #include Example #include void main() { int m1,m2,m3; float avg; printf("\nEnter the marks:"); scanf("%d%d%d",&m1,&m2,&m3); avg=(m1+m2+m3)/3; printf("\n The average is:%f",avg); printf("\n The Grade is:"); if(avg>=60) { printf("First class"); } else if(avg>=50) { printf("Second class"); } else if(avg>=35) { printf("Thrid class"); } else { printf("Fail"); } getch(); } Output Enter the marks:65 75 70 The average is:70.000000 The Grade is: First class Looping structure It is used to execute some instructions several time based on some condition. – WHILE – Do…WHILE – For WHILE Loop Syntax. WHILE (condition) { False condition. Body of the loop; True. } Body of The loop Example #include #include void main() { int i=1,fact=1,n; printf("\nEnter the Number:"); scanf("%d",&n); while(i0) { r=n%10; sum=sum+r; n=n/10; } printf("sum of the digits is:%d",sum); } Output Enter the no:156 sum of the digits is:12 Reverse of a number #include #include void main() { int r=0,sum=0,n; printf("\nEnter the no:"); scanf("%d",&n); while(n>0) { r=n%10; sum=sum*10+r; n=n/10; } printf("Reverse of the number is:%d",sum); getch(); } Output Enter the no:567 Reverse of the number is:765 Fibonacci Series #include #include void main() { int f=0,f1=-1,f2=1,n,i; printf("\nEnter the number:"); scanf("%d",&n); while(f=0) { r1=(-b+sqrt(d))/(2*a); r2=(-b-sqrt(d))/(2*a); printf(" \nThe roots are %d,%d",r1,r2); } else { printf(" \nThe roots are imaginary"); } getch( ); } Output Enter the value of a:4 Enter the value of b:5 Enter the value of c:6 The roots are imaginary

Use Quizgecko on...
Browser
Browser