PROGRAMMING FOR PROBLEM SOLVING UNIT - I
THE PURPOSE OF LEARNING THIS COURSE IS TO:  CLR -1: Think and evolve a logically to construct an algorithm into a flowchart and a pseudocode that can be programmed  CLR -2: Utilize the logical operators and expressions to solve problems in engineering and real-time  CLR -3: Store and retrieve data in a single and multidimensional array  CLR -4: Utilize custom designed functions that can be used to perform tasks and can be repeatedly used in any application  CLR -5: Create storage constructs using structure and unions. Create and Utilize files to store and retrieve information  CLR -6: Create a logical mindset to solve various engineering applications using programming constructs in C
LEARNING RESOURCES 1. Zed A Shaw, Learn C the Hard Way: Practical Exercises on the Computational Subjects You Keep Avoiding (Like C), Addison Wesley, 2015 2. W. Kernighan, Dennis M. Ritchie, The C Programming Language, 2nd ed. Prentice Hall, 1996 3. Bharat Kinariwala, Tep Dobry, Programming in C, eBook 4. http://www.c4learn.com/learn-c-programming-language/
EVOLUTION OF PROGRAMMING & LANGUAGES  A Computer needs to be given instructions in a programming language that it understands.  Programming Language  controls the behavior of computer  It is defined through the use of syntactic and semantic rules  Used to facilitate communication about the task of organizing and manipulating information
EVOLUTION OF PROGRAMMING & LANGUAGES
PROBLEM SOLVING THROUGH PROGRAMMING  Computer based problem solving is a systematic process of designing, implementing and using programming tools during the problem solving stage.  This method enables the computer system to be more intuitive with human logic than machine logic.  Final outcome of this process is software tools which is dedicated to solve the problem under consideration.  Software is just a collection of computer programs and programs are a set of instructions which guides computer’s hardware.  These instructions need to be well specified for solving the problem.  After its creation, the software should be error free and well documented. Software development is the process of creating such software, which satisfies end user’s requirements and needs.
PROBLEM SOLVING THROUGH PROGRAMMING  The following six steps must be followed to solve a problem using computer.  Problem Analysis  Program Design - Algorithm, Flowchart and Pseudocode  Coding  Compilation and Execution  Debugging and Testing  Program Documentation
PROGRAMMING PROCESS • Defining the Problem • Planning the Solution • Coding the Program • Testing the Program • Documenting the Program
PROBLEM SOLVING THROUGH PROGRAMMING  Problem Analysis  Problem analysis is the process of defining a problem and decomposing overall system into smaller parts to identify possible inputs, processes and outputs associated with the problem.  This task is further subdivided into six subtasks namely:  Specifying the Objective  Specifying the Output  Specifying Input Requirements  Specifying Processing Requirements  Evaluating the Feasibility  Problem Analysis Documentation
PROBLEM SOLVING THROUGH PROGRAMMING  Program Design  This process of dividing a program into modules and then into sub-modules is known as “top down” design approach.  Dividing a program into modules (functions) breaks down a given programming task into small, independent and manageable tasks.
PROBLEM SOLVING THROUGH PROGRAMMING  Coding (Programming)  The coding process can be done in any language (high level and low level). The actual use of computer takes place in this stage in which the programmer writes a sequence of instructions ready for execution.  Good program possess following characteristics :  Comment clauses in the program help to make the program readable and understandable by people other than the original programmer.  It should be efficient.  It must be reliable enough to work under all reasonable conditions to provide a correct output.  It must be able to detect unreasonable error conditions and report them to the end user or programmer without crashing the system.  It should be easy to maintain and support after installation.
PROBLEM SOLVING THROUGH PROGRAMMING  Compilation and Execution Process  A source code must go through several steps before it becomes an executable program.  In the first step the source code is checked for any syntax errors.  After the syntax errors are traced out a source file is passed through a compiler which first translates high level language into object code (A machine code not ready to be executed).  A linker then links the object code with pre-compiled library functions, thus creating an executable program. This executable program is then loaded into the memory for execution.
PROBLEM SOLVING THROUGH PROGRAMMING  Debugging and Testing  Debugging is the process of finding errors and removing them from a computer program, otherwise they will lead to failure of the program.  Testing is performed to verify that whether the completed software package functions or works according to the expectations defined by the requirements.
PROBLEM SOLVING THROUGH PROGRAMMING  Program (Programmer's and User's) Documentation  The program documentation is the process of collecting information about the program. The documentation process starts from the problem analysis phase to debugging and testing. Documentation consists two types of documentation, they are:  Programmer's Documentation  User's Documentation
ALGORITHM  An algorithm is a set of well-defined instructions to solve a particular problem. It takes a set of input and produces a desired output.  For example,  An algorithm to add two numbers:  Take two number inputs  Add numbers using the + operator  Display the result
QUALITIES OF GOOD ALGORITHMS  Input and output should be defined precisely.  Each step in the algorithm should be clear and unambiguous.  Algorithms should be most effective among many different ways to solve a problem.  An algorithm shouldn't include computer code. Instead, the algorithm should be written in such a way that it can be used in different programming languages.
ALGORITHM 1: ADD TWO NUMBERS ENTERED BY THE USER Step 1: Start Step 2: Declare variables num1, num2 and sum. Step 3: Read values num1 and num2. Step 4: Add num1 and num2 and assign the result to sum. sum←num1+num2 Step 5: Display sum Step 6: Stop
ALGORITHM 2: FIND THE LARGEST NUMBER AMONG THREE NUMBERS Step 1: Start Step 2: Declare variables a,b and c. Step 3: Read variables a,b and c. Step 4: If a > b If a > c Display a is the largest number. Else Display c is the largest number. Else If b > c Display b is the largest number. Else Display c is the greatest number. Step 5: Stop
FLOWCHART  A flowchart is a graphical representations of steps.  It was originated from computer science as a tool for representing algorithms and programming logic but had extended to use in all other kinds of processes.
FLOWCHART SYMBOLS Symbol Symbol Name Purpose Start/Stop Used at the beginning and end of the algorithm to show start and end of the program. Process Indicates processes like mathematical operations. Input/ Output Used for denoting program inputs and outputs. Decision Stands for decision statements in a program, where answer is usually Yes or No. Arrow Shows relationships between different shapes. On-page Connector Connects two or more parts of a flowchart, which are on the same page. Off-page Connector Connects two parts of a flowchart which are spread over different pages.
GUIDELINES FOR DEVELOPING FLOWCHARTS  These are some points to keep in mind while developing a flowchart −  Flowchart can have only one start and one stop symbol  On-page connectors are referenced using numbers  Off-page connectors are referenced using alphabets  General flow of processes is top to bottom or left to right  Arrows should not cross each other
EXAMPLE FLOWCHARTS  Here is the flowchart for going to the market to purchase a pen.
EXAMPLE FLOWCHARTS  average of two numbers.
PSEUDOCODE  Pseudo code is simply an implementation of an algorithm in the form of annotations and informative text written in plain English.  Pseudo code is not actual programming language.  It has no syntax like any of the programming language and thus can’t be compiled or interpreted by the computer.
USE PSEUDO CODE  It allows the designer to focus on the logic of the algorithm without being distracted by details of language syntax.  It describe the entire logic of the algorithm so that implementation becomes a routine mechanical task of translating line by line into source code.
ADVANTAGES OF PSEUDO CODE  Improves the readability of any approach. It’s one of the best approaches to start implementation of an algorithm  Acts as a bridge between the program and the algorithm or flowchart  Also works as a rough documentation, so the program of one developer can be understood easily when a pseudo code is written out. In industries, the approach of documentation is essential. And that’s where a pseudo-code proves vital  The main goal of a pseudo code is to explain what exactly each line of a program should do, hence making the code construction phase easier for the programmer
CONVENTIONS TO WRITE PSEUDO CODE
CONVENTIONS TO WRITE PSEUDO CODE
CONVENTIONS TO WRITE PSEUDO CODE (Operations based on some specific condition)
CONVENTIONS TO WRITE PSEUDO CODE (to evaluate a test condition and iterate over the loop body until the condition returns True)
CONVENTIONS TO WRITE PSEUDO CODE (to allow the value of a variable or expression to change the control flow of program execution via a multiway branch.)
CONVENTIONS TO WRITE PSEUDO CODE (to iterate the statements or a part of the program several times.)
CONVENTIONS TO WRITE PSEUDO CODE (to repetitively execute a subject statement until a condition is true.)
CONVENTIONS TO WRITE PSEUDO CODE
GUIDELINES FOR WRITING PSEUDO CODE  Write only one Statement per line  Example – Pseudo Code for calculating Salary  READ name, hourly rate, hours worked, deduction rate  Gross pay = hourly rate * hours worked  deduction = gross pay * deduction rate  net pay = gross pay – deduction  WRITE name, gross, deduction, net pay
GUIDELINES FOR WRITING PSEUDO CODE  Capitalize Initial Keyword  Keywords to be written in capital letters  Examples: READ, WRITE, IF, ELSE, WHILE, REPEAT, PRINT  Indent to show Hierarchy  Indentation shows the structure boundaries  Sequence  Selection  Looping
GUIDELINES FOR WRITING PSEUDO CODE  End Multiline structures  Each structure must end properly  Example: IF statement must end with ENDIF  Keep Statements Language independent  Resist the urge to write Pseudo Code in any programming language
PSEUDOCODE TO FIND THE SUM OF TWO NUMBERS. begin numeric nNum1,nNum2,nSum display "ENTER THE FIRST NUMBER : " accept nNum1 display "ENTER THE SECOND NUMBER : " accept nNum2 compute nSum=nNum1+nNum2 display "SUM OF THESE NUMBER : " nSum end
PSEUDOCODE TO FIND THE LARGEST OF TWO NUMBERS. BEGIN NUMERIC nNum1,nNum2 DISPLAY "ENTER THE FIRST NUMBER : " INPUT nNum1 DISPLAY "ENTER THE SECOND NUMBER : " INPUT nNum2 IF nNum1 > nNum2 DISPLAY nNum1 + " is larger than "+ nNum2 ELSE DISPLAY nNum2 + " is larger than " + nNum1 END
WHY TO STUDY C PROGRAMMING  Low level programming becomes especially important in the Internet of Things (IoT) and wearable devices, where efficiency in power consumption is actually the most important consideration.  Secondly, all of the high-level languages are built off of low-level languages. You’ll need low-level programming to sustain and keep developing those high-level languages.  While there is a big push to be able to use high level language to be able to write low level things like drivers for graphics cards, low level languages are still needed for performance.  For example, everything relating to encoding or decoding and encryption will probably use low level programming, with C and probably some assembly to use extended instruction (like AVX, SSE, etc). Basically, everything that needs high-performance and fine tuning will require a bit of low level programming.
HISTORY & EVOLUTION OF C  C – General Purpose Programming Language  Developed by Dennis Ritchie in 1972  Developed at Bell Laboratories  Principles taken from BCPL and CPL  Structured Programming Language  C Program  Collection of Functions supported by C library Father of C Programming
EVOLUTION OF C LANGUAGE 1960 1967 1970 1972 1978 1989 1990 1999
WHY THE NAME “C” WAS GIVEN ?  Many of C’s principles and ideas were derived from the earlier language B  BCPL and CPL are the earlier ancestors of B Language (CPL is common Programming Language)  In 1967, BCPL Language ( Basic CPL ) was created as a scaled down version of CPL  As many of the features were derived from “B” Language the new language was named as “C”.
CHARACTERISTICS OF ‘C’  Low Level Language Support  Structured Programming  Efficient use of Pointers  Extensible  Program Portability  Memory Management
DISADVANTAGES OF C  C Programming Language doesn't support Object Oriented Programming(OOP)  C doesn't perform Run Time Type Checking. It only does compile time type checking. At run time, C doesn't ensure whether correct data type is used instead it perform automatic type conversion.  C doesn't support the concept of Exception handling.
STRUCTURE OF C PROGRAM // Structure of C Program #include <stdio.h> #include <conio.h> void main() { //Program Statement; //call user_subprogram() } void user_subprogram() { //Program Statement; } 1. //Document section 2. #Pre-processor section 3. Global declaration; 4. Main() program 5. #user defined Sub programs() Pre processor Section Main Program User defined Sub Program Entry Point Document Section
DOCUMENTATION SECTION  Used for providing Comments  Comment treated as a single white space by Compiler  Ignored at time of Execution: Not Executable  Comment: Sequence of Characters given between /* and */  Example: Program Name, Statement description  /* Program to Find Area of a Circle*/
PRE-PROCESSOR SECTION  Also called as Preprocessor Directive  Also called as Header Files  Not a part of Compiler  Separate step in Compilation Process  Instructs Compiler to do required Preprocessing  Begins with # symbol  Preprocessor written within < > #include <stdio.h> #include <conio.h> #include <math.h> #include <stdlib.h> #define PI 3.1412
GLOBAL DECLARATION SECTION  Used to Declare Global variable (or) Public variable  Variables are declared outside all functions  Variables can be accessed by all functions in the program  Same variable used by more than one function
MAIN( ) SECTION  main( ) written in all small letters (No Capital Letters)  Execution starts with a Opening Brace : {  Divided into two sections: Declaration & Execution  Declaration : Declare Variables  Executable: Statements within the Braces  Execution ends with a Closing Brace : }  Note: main( ) does not end with a semicolon
LOCAL DECLARATION SECTION  Variables declared within the main( ) program  These variables are called Local Variables  Variables initialized with basic data types
C PROGRAMMING FUNDAMENTALS
C PROGRAMMING FUNDAMENTALS
C PROGRAMMING FUNDAMENTALS • C program broken into many C tokens • Building Blocks of C program
SINGLE LINE AND MULTILINE COMMENTS  Used to provide information about lines of code  Provide clarity to the C source code  Allows others to betterunderstand what the code was intended to  Helps in debugging the code  Important in large projects containing hundreds or thousands of lines of source code  Types – Single line and multiline comment
 Represented by double slash //  Multi Line comment represented by /* comment statements */ SINGLE LINE AND MULTI LINE COMMENT #include<stdio.h> int main( ){ //printing information printf("Hello C"); return 0; } #include<stdio.h> int main( ){ /*printing information Multi Line Comment*/ printf("Hello C"); return 0; }
KEYWORDS  Keywords – Conveys special meaning to Compiler  32 keywords  Cannot be used as variable names
CONSTANTS  Definition :Value does not change during execution  Can be a Number (or) a Letter
VARIABLES / IDENTIFIERS  Identifier for a memory location where data is stored  Value changes during execution  Rules for Identifiers  Combination of alphabets, digits (or) underscore  First character should be a Alphabet  No special characters other than underscore can be used  No comma / spaces allowed within variable name  A variable name cannot be a keyword  Variable names are case sensitive  Variable name length cannot be more than 31 characters
VARIABLE DECLARATION  A variable must be declared before it is used  Declaration consists of a data type followed by one or more variable names separated by commas. datatype variable_name; Syntax Examples int a, b, c, sum; float avg; char name;
VARIABLE INITIALIZATION  Assigning a value to the declared variable  Values assigned during declaration / after declaration Examples int a, b, c; a=10, b=20, c=30; int a=10 ,b=10, c=10;
SCOPE OF VARIABLES  There are three places where variables can be declared  Inside a function or a block which is called local variables  Outside of all functions which is called global variables  In the definition of function parameters which are called formal parameters (Example: int sum( int x, int y);)
SCOPE OF VARIABLES  A scope in any programming is a region of the program where a defined variable can have its existence and beyond that variable it cannot be accessed  Variable Scope is a region in a program where a variable is declared and used  The scope of a variable is the range of program statements that can access that variable  A variable is visible within its scope and invisible outside it
SCOPE OF VARIABLES : LOCAL VARIABLES  Variables that are declared inside a function or block are called local variables  They can be used only by statements that are inside that function or block of code  Local variables are created when the control reaches the block or function containing the local variables and then they get destroyed after that  Local variables are not known to functions outside their own
SCOPE OF VARIABLES : LOCAL VARIABLES #include <stdio.h> int main ( ) { /* local variable declaration */ int a, b; int c; /* actual initialization */ a = 10; b = 20; c = a + b; printf ("value of a = %d, b = %d and c = %dn", a, b, c); return 0; }
SCOPE OF VARIABLES : GLOBAL VARIABLES  Defined outside a function, usually on top of the program  Hold their values throughout the lifetime of the program  Can be accessed inside any of the functions defined for the program  Can be accessed by any function  That is, a global variable is available for use throughout the entire program after its declaration
SCOPE OF VARIABLES : GLOBAL VARIABLES #include <stdio.h> /* global variable declaration */ int g; int main ( ) { /* local variable declaration */ int a, b; /* actual initialization */ a = 10; b = 20; g = a + b; printf ("value of a = %d, b = %d and g = %dn", a, b, g); return 0; }
BINDING  A Binding is an association between an entity and an attribute  Between a variable and its type or value  Between a function and its code  Binding time is the point at which a binding takes place  Types of Binding  Design Time  Compile Time  Link Time  Run Time
BINDING  Design Time  Binding decisions are made when a language is designed  Example  Binding of + to addition in C  Compile Time  Bindings done while the program is compiled  Binding variables to datatypes  Example  int a; float b; char c;
BINDING  Link Time  Compiled code is combined into a full program for C  Example  Global and Static variables are bound to addresses  Run Time  Any binding that happens at run time is called Dynamic  Any binding that happens before run time is called Static  Values that are dynamically bound can change
DATATYPES  Defines a variable before use  Specifies the type of data to be stored in variables  Basic Data Types – 4 Classes  int – Signed or unsigned number  float – Signed or unsigned number having Decimal Point  double – Double Precision Floating point number  char – A Character in the character Set
DATATYPES
INTEGER DATA TYPE  Whole numbers with a range  No fractional parts  Integer variable holds integer values only  Keyword: int  Memory: 2 Bytes (16 bits) or 4 Bytes (32 bits)  Qualifiers: Signed, unsigned, short, long  Examples: 34012, 0, -2457
FLOATING POINT DATA TYPE  Numbers having Fractional part  Float provides precision of 6 digits  Integer variable holds integer values only  Keyword: float  Memory: 4 Bytes (32 bits)  Examples: 5.6, 0.375, 3.14756
DOUBLE DATA TYPE  Also handles floating point numbers  Double provides precision of 14 digits  Integer variable holds integer values only  Keyword: float  Memory: 8 Bytes (64 bits) or 10 Bytes (80 bits)  Qualifiers: long, short
CHARACTER DATA TYPE  handles one character at a time  Keyword: char  Memory: 1 Byte (8 bits)
EXPRESSIONS  Expression : An Expression is a collection of operators and operands that represents a specific value/operation.  Operator : A symbol which performs tasks like arithmetic operations, logical operations and conditional operations  Operands : The values on which the operators perform the task  Expression Types in C  Infix Expression  Postfix Expression  Prefix Expression
EXPRESSIONS  Infix Expression  The operator is used between operands  General Structure : Operand1 Operator Operand2  Example : a + b  Postfix Expression  Operator is used after operands  General Structure : Operand1 Operand2 Operator  Example : ab+  Prefix Expression  Operator is used before operands  General Structure : Operator Operand1 Operand2  Example : +ab
EXPRESSIONS
INPUT AND OUTPUT FUNCTIONS  Ability to Communicate with Users during execution  Input Operation  Feeding data into program  Data Transfer from Input device to Memory  Output Operation  Getting result from Program  Data Transfer from Memory to Output device  Header File : #include<stdio.h>
FORMATTED INPUT / OUTPUT STATEMENTS  Reads and writes all types of data values  Arranges data in particular format  Requires Format Specifier to identify Data type  Basic Format Specifiers  %d – Integer  %f – Float  %c – Character  %s - String
SCANF ( ) FUNCTION  Reads all types of input data  Assignment of value to variable during Runtime scanf(“Control String/Format Specifier”, &arg1, &arg2,… &argn) Syntax
PRINTF ( ) FUNCTION  To print Instructions / Output onto the Screen  Requires Format Specifiers & Variable names to print data printf(“Control String/Format Specifier”,arg1,arg2,… argn) Syntax
EXAMPLE 1 – USING PRINTF ( ) & SCANF ( ) FUNCTION #include<stdio.h> void main( ) { int a; printf(“Enter the Value of a:”); scanf("%d", &a); printf("Value of a is %d", a); }
EXAMPLE 1 – USING PRINTF ( ) & SCANF ( ) FUNCTION #include<stdio.h> void main( ) { int a, b, c; printf("Enter the Value of a, b & c: "); scanf("%d %d %d", &a, &b, &c); printf(“Value of a, b & c is %d %d %d”, a, b, c); }
TRY IT OUT YOURSELF ! WRITE A C PROGRAM TO:  Add two numbers  To Multiply two floating point numbers  To compute Quotient and Remainder  To Swap two numbers
UNFORMATTED INPUT / OUTPUT STATEMENTS  Works only with Character Data type  No need of Format Specifier  Unformatted Input Statements  getch(): It will Accepts a Keystroke and never displays it.(So that it can be used in password). That is, It Never echoes the character on screen. The Arguments to the function is any key on keyboard ,not necessarily be a character.  getchar(): It will accepts a character from keyboard & Displays it immediately. On reading any character, getchar() need to hit any key for proceeding. The argument is a character i.e alphabet(A-Z).  gets ( ) – Accepts any string from Keyboard until Enter Key is pressed
UNFORMATTED INPUT / OUTPUT STATEMENTS  Unformatted Output Statements  putch()– Prints only the any alphabets  putchar ( ) – Prints any character including escape sequences  puts ( ) – Prints a String to Monitor (Output Device)
OPERATORS IN C  C supports rich set of built in Operators  Used to manipulate Constants (Data) & Variables  Part of Mathematical (or) Logical expressions  Operator – Definition  Symbol (or) Special character that instructs the compiler to perform mathematical (or) Logical operations
ARITHMETIC OPERATORS  An arithmetic operator performs mathematical operations such as addition, subtraction, multiplication, division etc on numerical values (constants and variables). Operator Meaning of Operator + addition or unary plus - subtraction or unary minus * multiplication / division % remainder after division (modulo division)
EXAMPLE – ARITHMETIC OPERATORS #include <stdio.h> int main() { int a = 9,b = 4, c; c = a+b; printf("a+b = %d n",c); c = a-b; printf("a-b = %d n",c); c = a*b; printf("a*b = %d n",c); c = a/b; printf("a/b = %d n",c); c = a%b; printf("Remainder when a divided by b = %d n",c); return 0; }
ASSIGNMENT OPERATORS  An assignment operator is used for assigning a value to a variable. The most common assignment operator is = Operator Example Same as = a = b a = b += a += b a = a+b -= a -= b a = a-b *= a *= b a = a*b /= a /= b a = a/b %= a %= b a = a%b
EXAMPLE – ASSIGNMENT OPERATORS #include <stdio.h> int main() { int a = 5, c; c = a; // c is 5 printf("c = %dn", c); c += a; // c is 10 printf("c = %dn", c); c -= a; // c is 5 printf("c = %dn", c); c *= a; // c is 25 printf("c = %dn", c); c /= a; // c is 5 printf("c = %dn", c); c %= a; // c = 0 printf("c = %dn", c); return 0; }
INCREMENT AND DECREMENT OPERATORS  Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. These two operators are unary operators, meaning they only operate on a single operand.
EXAMPLE – INCREMENT AND DECREMENT OPERATORS int main(){ int a = 10, b = 20,c=30,d=40; printf("a++ = %d n", a++); printf("%d n",a); printf("--b = %d n", b--); printf("%d n",b); printf("++c = %d n", ++c); printf("%d n",c); printf("--d = %d n", --d); printf("%d n",d); return 0;} a++ = 10 11 --b = 20 19 ++c = 31 31 --d = 39 39
RELATIONAL OPERATORS  A relational operator checks the relationship between two operands. If the relation is true, it returns 1; if the relation is false, it returns value 0.  Relational operators are used in decision making and loops. Operator Meaning of Operator Example == Equal to 5 == 3 is evaluated to 0 > Greater than 5 > 3 is evaluated to 1 < Less than 5 < 3 is evaluated to 0 != Not equal to 5 != 3 is evaluated to 1 >= Greater than or equal to 5 >= 3 is evaluated to 1 <= Less than or equal to 5 <= 3 is evaluated to 0
EXAMPLE – RELATIONAL OPERATORS { int a = 5, b = 5, c = 10; printf("%d == %d is %d n", a, b, a == b); printf("%d == %d is %d n", a, c, a == c); printf("%d > %d is %d n", a, b, a > b); printf("%d > %d is %d n", a, c, a > c); printf("%d < %d is %d n", a, b, a < b); printf("%d < %d is %d n", a, c, a < c); printf("%d != %d is %d n", a, b, a != b); printf("%d != %d is %d n", a, c, a != c); printf("%d >= %d is %d n", a, b, a >= b); printf("%d >= %d is %d n", a, c, a >= c); 5 == 5 is 1 5 == 10 is 0 5 > 5 is 0 5 > 10 is 0 5 < 5 is 0 5 < 10 is 1 5 != 5 is 0 5 != 10 is 1 5 >= 5 is 1 5 >= 10 is 0 5 <= 5 is 1 5 <= 10 is 1
LOGICAL OPERATORS  An expression containing logical operator returns either 0 or 1 depending upon whether expression results true or false. Logical operators are commonly used in decision making in C programming. Operator Meaning Example && Logical AND. True only if all operands are true If c = 5 and d = 2 then, expression ((c==5) && (d>5)) equals to 0. || Logical OR. True only if either one operand is true If c = 5 and d = 2 then, expression ((c==5) || (d>5)) equals to 1. ! Logical NOT. True only if the operand is 0 If c = 5 then, expression !(c==5) equals to 0.
EXAMPLE – LOGICAL OPERATORS int main() { int a = 5, b = 5, c = 10, result; result = (a == b) && (c > b) && (a<c); printf("(a == b) && (c > b) is %d n", result); result = (a == b) || (c < b); printf("(a == b) || (c < b) is %d n", result); result = !(a != b); printf("!(a != b) is %d n", result); result = !(a == b); printf("!(a == b) is %d n", result); return 0; } (a == b) && (c > b) is 1 (a == b) || (c < b) is 1 !(a != b) is 1 !(a == b) is 0
BITWISE OPERATORS  During computation, mathematical operations like: addition, subtraction, multiplication, division, etc are converted to bit-level which makes processing faster and saves power.  Bitwise operators are used in C programming to perform bit-level operations. Operators Meaning of operators & Bitwise AND | Bitwise OR ^ Bitwise exclusive OR ~ Bitwise complement << Shift left >> Shift right Division Remainder (R) 112 / 2 = 56 0 56 / 2 = 28 0 28 / 2 = 14 0 14 / 2 = 7 0 7 / 2 = 3 1 3 / 2 = 1 1 1 / 2 = 0 1
BITWISE AND OPERATOR &  The output of bitwise AND is 1 if the corresponding bits of two operands is 1. If either bit of an operand is 0, the result of corresponding bit is evaluated to 0.  Let us suppose the bitwise AND operation of two integers 12 and 25. 12 = 00001100 (In Binary) 25 = 00011001 (In Binary) Bit Operation of 12 and 25 00001100 & 00011001 ________ 00001000 = 8 (In decimal) A B Q 0 0 0 0 1 0 1 0 0 1 1 1
EXAMPLE – BITWISE AND OPERATOR & #include <stdio.h> int main() { int a = 12, b = 25; printf("Output = %d", a&b); return 0; } Output = 8
BITWISE OR OPERATOR |  The output of bitwise OR is 1 if at least one corresponding bit of two operands is 1. In C Programming, bitwise OR operator is denoted by |. 12 = 00001100 (In Binary) 25 = 00011001 (In Binary) Bitwise OR Operation of 12 and 25 00001100 | 00011001 ________ 00011101 = 29 (In decimal)) A B Q 0 0 0 0 1 1 1 0 1 1 1 1
EXAMPLE – BITWISE OR OPERATOR | #include <stdio.h> int main() { int a = 12, b = 25; printf("Output = %d", a|b); return 0; } Output = 29
BITWISE XOR (EXCLUSIVE OR) OPERATOR ^  The result of bitwise XOR operator is 1 if the corresponding bits of two operands are opposite. It is denoted by ^. 12 = 00001100 (In Binary) 25 = 00011001 (In Binary) Bitwise XOR Operation of 12 and 25 00001100 ^ 00011001 ________ 00010101 = 21 (In decimal) A B Q 0 0 0 0 1 1 1 0 1 1 1 0
EXAMPLE – BITWISE XOR (EXCLUSIVE OR) OPERATOR ^ #include <stdio.h> int main() { int a = 12, b = 25; printf("Output = %d", a^b); return 0; } Output = 21
BITWISE COMPLEMENT OPERATOR ~  Bitwise compliment operator is an unary operator (works on only one operand). It changes 1 to 0 and 0 to 1. It is denoted by ~.  2's Complement  Two's complement is an operation on binary numbers. The 2's complement of a number is equal to the complement of that number plus 1.  For example: Binary number 1’s complement 2’s complement 001 110 111 010 101 110 011 100 101 100 011 100
EXAMPLE – BITWISE COMPLEMENT OPERATOR ~ #include <stdio.h> int main() { printf("Output = %dn",~35); printf("Output = %dn",~- 12); return 0; } Output = -36 Output = 11 • The bitwise complement of 35 (~35) is -36 instead of 220, but why? • For any integer n, bitwise complement of n will be -(n + 1). • Two's complement is an operation on binary numbers. The 2's complement of a number is equal to the complement of that number plus 1. For example:
RIGHT SHIFT OPERATOR  Right shift operator shifts all bits towards right by certain number of specified bits. It is denoted by >>. 212 = 11010100 (In binary) 212>>2 = 00110101 (In binary) [Right shift by two bits] 212>>7 = 00000001 (In binary) 212>>8 = 00000000 212>>0 = 11010100 (No Shift)
LEFT SHIFT OPERATOR  Left shift operator shifts all bits towards left by a certain number of specified bits. The bit positions that have been vacated by the left shift operator are filled with 0. The symbol of the left shift operator is <<. 212 = 11010100 (In binary) 212<<1 = 110101000 (In binary) [Left shift by one bit] 212<<0 = 11010100 (Shift by 0) 212<<4 = 110101000000 (In binary) =3392(In decimal)
EXAMPLE – SHIFT OPERATOR #include <stdio.h> int main() { int num=212, i; for (i=0; i<=2; ++i) printf("Right shift by %d: %dn", i, num>>i); printf("n"); for (i=0; i<=2; ++i) printf("Left shift by %d: %dn", i, num<<i); return 0; } Right Shift by 0: 212 Right Shift by 1: 106 Right Shift by 2: 53 Left Shift by 0: 212 Left Shift by 1: 424 Left Shift by 2: 848
OTHER OPERATORS  Comma Operator  Comma operators are used to link related expressions together.  For example: int a, c = 5, d;
THE SIZEOF OPERATOR  The sizeof is a unary operator that returns the size of data (constants, variables, array, structure, etc).
EXAMPLE – SIZE0F() OPERATOR #include <stdio.h> int main() { int a; float b; double c; char d; printf("Size of int=%lu bytesn",sizeof(a)); printf("Size of float=%lu bytes n",sizeof(b)); printf("Size of double=%lu bytes n",sizeof(c)); printf("Size of char=%lu byten",sizeof(d)); return 0; } Size of int = 4 bytes Size of float = 4 bytes Size of double = 8 bytes Size of char = 1 byte

Programming C ppt for learning foundations

  • 1.
    PROGRAMMING FOR PROBLEMSOLVING UNIT - I
  • 2.
    THE PURPOSE OFLEARNING THIS COURSE IS TO:  CLR -1: Think and evolve a logically to construct an algorithm into a flowchart and a pseudocode that can be programmed  CLR -2: Utilize the logical operators and expressions to solve problems in engineering and real-time  CLR -3: Store and retrieve data in a single and multidimensional array  CLR -4: Utilize custom designed functions that can be used to perform tasks and can be repeatedly used in any application  CLR -5: Create storage constructs using structure and unions. Create and Utilize files to store and retrieve information  CLR -6: Create a logical mindset to solve various engineering applications using programming constructs in C
  • 3.
    LEARNING RESOURCES 1. ZedA Shaw, Learn C the Hard Way: Practical Exercises on the Computational Subjects You Keep Avoiding (Like C), Addison Wesley, 2015 2. W. Kernighan, Dennis M. Ritchie, The C Programming Language, 2nd ed. Prentice Hall, 1996 3. Bharat Kinariwala, Tep Dobry, Programming in C, eBook 4. http://www.c4learn.com/learn-c-programming-language/
  • 4.
    EVOLUTION OF PROGRAMMING& LANGUAGES  A Computer needs to be given instructions in a programming language that it understands.  Programming Language  controls the behavior of computer  It is defined through the use of syntactic and semantic rules  Used to facilitate communication about the task of organizing and manipulating information
  • 5.
  • 6.
    PROBLEM SOLVING THROUGHPROGRAMMING  Computer based problem solving is a systematic process of designing, implementing and using programming tools during the problem solving stage.  This method enables the computer system to be more intuitive with human logic than machine logic.  Final outcome of this process is software tools which is dedicated to solve the problem under consideration.  Software is just a collection of computer programs and programs are a set of instructions which guides computer’s hardware.  These instructions need to be well specified for solving the problem.  After its creation, the software should be error free and well documented. Software development is the process of creating such software, which satisfies end user’s requirements and needs.
  • 7.
    PROBLEM SOLVING THROUGHPROGRAMMING  The following six steps must be followed to solve a problem using computer.  Problem Analysis  Program Design - Algorithm, Flowchart and Pseudocode  Coding  Compilation and Execution  Debugging and Testing  Program Documentation
  • 8.
    PROGRAMMING PROCESS • Definingthe Problem • Planning the Solution • Coding the Program • Testing the Program • Documenting the Program
  • 9.
    PROBLEM SOLVING THROUGHPROGRAMMING  Problem Analysis  Problem analysis is the process of defining a problem and decomposing overall system into smaller parts to identify possible inputs, processes and outputs associated with the problem.  This task is further subdivided into six subtasks namely:  Specifying the Objective  Specifying the Output  Specifying Input Requirements  Specifying Processing Requirements  Evaluating the Feasibility  Problem Analysis Documentation
  • 10.
    PROBLEM SOLVING THROUGHPROGRAMMING  Program Design  This process of dividing a program into modules and then into sub-modules is known as “top down” design approach.  Dividing a program into modules (functions) breaks down a given programming task into small, independent and manageable tasks.
  • 11.
    PROBLEM SOLVING THROUGHPROGRAMMING  Coding (Programming)  The coding process can be done in any language (high level and low level). The actual use of computer takes place in this stage in which the programmer writes a sequence of instructions ready for execution.  Good program possess following characteristics :  Comment clauses in the program help to make the program readable and understandable by people other than the original programmer.  It should be efficient.  It must be reliable enough to work under all reasonable conditions to provide a correct output.  It must be able to detect unreasonable error conditions and report them to the end user or programmer without crashing the system.  It should be easy to maintain and support after installation.
  • 12.
    PROBLEM SOLVING THROUGHPROGRAMMING  Compilation and Execution Process  A source code must go through several steps before it becomes an executable program.  In the first step the source code is checked for any syntax errors.  After the syntax errors are traced out a source file is passed through a compiler which first translates high level language into object code (A machine code not ready to be executed).  A linker then links the object code with pre-compiled library functions, thus creating an executable program. This executable program is then loaded into the memory for execution.
  • 13.
    PROBLEM SOLVING THROUGHPROGRAMMING  Debugging and Testing  Debugging is the process of finding errors and removing them from a computer program, otherwise they will lead to failure of the program.  Testing is performed to verify that whether the completed software package functions or works according to the expectations defined by the requirements.
  • 14.
    PROBLEM SOLVING THROUGHPROGRAMMING  Program (Programmer's and User's) Documentation  The program documentation is the process of collecting information about the program. The documentation process starts from the problem analysis phase to debugging and testing. Documentation consists two types of documentation, they are:  Programmer's Documentation  User's Documentation
  • 15.
    ALGORITHM  An algorithmis a set of well-defined instructions to solve a particular problem. It takes a set of input and produces a desired output.  For example,  An algorithm to add two numbers:  Take two number inputs  Add numbers using the + operator  Display the result
  • 16.
    QUALITIES OF GOODALGORITHMS  Input and output should be defined precisely.  Each step in the algorithm should be clear and unambiguous.  Algorithms should be most effective among many different ways to solve a problem.  An algorithm shouldn't include computer code. Instead, the algorithm should be written in such a way that it can be used in different programming languages.
  • 17.
    ALGORITHM 1: ADDTWO NUMBERS ENTERED BY THE USER Step 1: Start Step 2: Declare variables num1, num2 and sum. Step 3: Read values num1 and num2. Step 4: Add num1 and num2 and assign the result to sum. sum←num1+num2 Step 5: Display sum Step 6: Stop
  • 18.
    ALGORITHM 2: FINDTHE LARGEST NUMBER AMONG THREE NUMBERS Step 1: Start Step 2: Declare variables a,b and c. Step 3: Read variables a,b and c. Step 4: If a > b If a > c Display a is the largest number. Else Display c is the largest number. Else If b > c Display b is the largest number. Else Display c is the greatest number. Step 5: Stop
  • 19.
    FLOWCHART  A flowchartis a graphical representations of steps.  It was originated from computer science as a tool for representing algorithms and programming logic but had extended to use in all other kinds of processes.
  • 20.
    FLOWCHART SYMBOLS Symbol Symbol Name Purpose Start/Stop Usedat the beginning and end of the algorithm to show start and end of the program. Process Indicates processes like mathematical operations. Input/ Output Used for denoting program inputs and outputs. Decision Stands for decision statements in a program, where answer is usually Yes or No. Arrow Shows relationships between different shapes. On-page Connector Connects two or more parts of a flowchart, which are on the same page. Off-page Connector Connects two parts of a flowchart which are spread over different pages.
  • 21.
    GUIDELINES FOR DEVELOPINGFLOWCHARTS  These are some points to keep in mind while developing a flowchart −  Flowchart can have only one start and one stop symbol  On-page connectors are referenced using numbers  Off-page connectors are referenced using alphabets  General flow of processes is top to bottom or left to right  Arrows should not cross each other
  • 22.
    EXAMPLE FLOWCHARTS  Hereis the flowchart for going to the market to purchase a pen.
  • 23.
  • 24.
    PSEUDOCODE  Pseudo codeis simply an implementation of an algorithm in the form of annotations and informative text written in plain English.  Pseudo code is not actual programming language.  It has no syntax like any of the programming language and thus can’t be compiled or interpreted by the computer.
  • 25.
    USE PSEUDO CODE It allows the designer to focus on the logic of the algorithm without being distracted by details of language syntax.  It describe the entire logic of the algorithm so that implementation becomes a routine mechanical task of translating line by line into source code.
  • 26.
    ADVANTAGES OF PSEUDOCODE  Improves the readability of any approach. It’s one of the best approaches to start implementation of an algorithm  Acts as a bridge between the program and the algorithm or flowchart  Also works as a rough documentation, so the program of one developer can be understood easily when a pseudo code is written out. In industries, the approach of documentation is essential. And that’s where a pseudo-code proves vital  The main goal of a pseudo code is to explain what exactly each line of a program should do, hence making the code construction phase easier for the programmer
  • 27.
  • 28.
  • 29.
    CONVENTIONS TO WRITEPSEUDO CODE (Operations based on some specific condition)
  • 30.
    CONVENTIONS TO WRITEPSEUDO CODE (to evaluate a test condition and iterate over the loop body until the condition returns True)
  • 31.
    CONVENTIONS TO WRITEPSEUDO CODE (to allow the value of a variable or expression to change the control flow of program execution via a multiway branch.)
  • 32.
    CONVENTIONS TO WRITEPSEUDO CODE (to iterate the statements or a part of the program several times.)
  • 33.
    CONVENTIONS TO WRITEPSEUDO CODE (to repetitively execute a subject statement until a condition is true.)
  • 34.
  • 35.
    GUIDELINES FOR WRITINGPSEUDO CODE  Write only one Statement per line  Example – Pseudo Code for calculating Salary  READ name, hourly rate, hours worked, deduction rate  Gross pay = hourly rate * hours worked  deduction = gross pay * deduction rate  net pay = gross pay – deduction  WRITE name, gross, deduction, net pay
  • 36.
    GUIDELINES FOR WRITINGPSEUDO CODE  Capitalize Initial Keyword  Keywords to be written in capital letters  Examples: READ, WRITE, IF, ELSE, WHILE, REPEAT, PRINT  Indent to show Hierarchy  Indentation shows the structure boundaries  Sequence  Selection  Looping
  • 37.
    GUIDELINES FOR WRITINGPSEUDO CODE  End Multiline structures  Each structure must end properly  Example: IF statement must end with ENDIF  Keep Statements Language independent  Resist the urge to write Pseudo Code in any programming language
  • 38.
    PSEUDOCODE TO FINDTHE SUM OF TWO NUMBERS. begin numeric nNum1,nNum2,nSum display "ENTER THE FIRST NUMBER : " accept nNum1 display "ENTER THE SECOND NUMBER : " accept nNum2 compute nSum=nNum1+nNum2 display "SUM OF THESE NUMBER : " nSum end
  • 39.
    PSEUDOCODE TO FINDTHE LARGEST OF TWO NUMBERS. BEGIN NUMERIC nNum1,nNum2 DISPLAY "ENTER THE FIRST NUMBER : " INPUT nNum1 DISPLAY "ENTER THE SECOND NUMBER : " INPUT nNum2 IF nNum1 > nNum2 DISPLAY nNum1 + " is larger than "+ nNum2 ELSE DISPLAY nNum2 + " is larger than " + nNum1 END
  • 40.
    WHY TO STUDYC PROGRAMMING  Low level programming becomes especially important in the Internet of Things (IoT) and wearable devices, where efficiency in power consumption is actually the most important consideration.  Secondly, all of the high-level languages are built off of low-level languages. You’ll need low-level programming to sustain and keep developing those high-level languages.  While there is a big push to be able to use high level language to be able to write low level things like drivers for graphics cards, low level languages are still needed for performance.  For example, everything relating to encoding or decoding and encryption will probably use low level programming, with C and probably some assembly to use extended instruction (like AVX, SSE, etc). Basically, everything that needs high-performance and fine tuning will require a bit of low level programming.
  • 41.
    HISTORY & EVOLUTIONOF C  C – General Purpose Programming Language  Developed by Dennis Ritchie in 1972  Developed at Bell Laboratories  Principles taken from BCPL and CPL  Structured Programming Language  C Program  Collection of Functions supported by C library Father of C Programming
  • 42.
    EVOLUTION OF CLANGUAGE 1960 1967 1970 1972 1978 1989 1990 1999
  • 43.
    WHY THE NAME“C” WAS GIVEN ?  Many of C’s principles and ideas were derived from the earlier language B  BCPL and CPL are the earlier ancestors of B Language (CPL is common Programming Language)  In 1967, BCPL Language ( Basic CPL ) was created as a scaled down version of CPL  As many of the features were derived from “B” Language the new language was named as “C”.
  • 44.
    CHARACTERISTICS OF ‘C’ Low Level Language Support  Structured Programming  Efficient use of Pointers  Extensible  Program Portability  Memory Management
  • 45.
    DISADVANTAGES OF C C Programming Language doesn't support Object Oriented Programming(OOP)  C doesn't perform Run Time Type Checking. It only does compile time type checking. At run time, C doesn't ensure whether correct data type is used instead it perform automatic type conversion.  C doesn't support the concept of Exception handling.
  • 46.
    STRUCTURE OF C PROGRAM //Structure of C Program #include <stdio.h> #include <conio.h> void main() { //Program Statement; //call user_subprogram() } void user_subprogram() { //Program Statement; } 1. //Document section 2. #Pre-processor section 3. Global declaration; 4. Main() program 5. #user defined Sub programs() Pre processor Section Main Program User defined Sub Program Entry Point Document Section
  • 47.
    DOCUMENTATION SECTION  Usedfor providing Comments  Comment treated as a single white space by Compiler  Ignored at time of Execution: Not Executable  Comment: Sequence of Characters given between /* and */  Example: Program Name, Statement description  /* Program to Find Area of a Circle*/
  • 48.
    PRE-PROCESSOR SECTION  Alsocalled as Preprocessor Directive  Also called as Header Files  Not a part of Compiler  Separate step in Compilation Process  Instructs Compiler to do required Preprocessing  Begins with # symbol  Preprocessor written within < > #include <stdio.h> #include <conio.h> #include <math.h> #include <stdlib.h> #define PI 3.1412
  • 49.
    GLOBAL DECLARATION SECTION Used to Declare Global variable (or) Public variable  Variables are declared outside all functions  Variables can be accessed by all functions in the program  Same variable used by more than one function
  • 50.
    MAIN( ) SECTION main( ) written in all small letters (No Capital Letters)  Execution starts with a Opening Brace : {  Divided into two sections: Declaration & Execution  Declaration : Declare Variables  Executable: Statements within the Braces  Execution ends with a Closing Brace : }  Note: main( ) does not end with a semicolon
  • 51.
    LOCAL DECLARATION SECTION Variables declared within the main( ) program  These variables are called Local Variables  Variables initialized with basic data types
  • 52.
  • 53.
  • 54.
    C PROGRAMMING FUNDAMENTALS •C program broken into many C tokens • Building Blocks of C program
  • 55.
    SINGLE LINE ANDMULTILINE COMMENTS  Used to provide information about lines of code  Provide clarity to the C source code  Allows others to betterunderstand what the code was intended to  Helps in debugging the code  Important in large projects containing hundreds or thousands of lines of source code  Types – Single line and multiline comment
  • 56.
     Represented bydouble slash //  Multi Line comment represented by /* comment statements */ SINGLE LINE AND MULTI LINE COMMENT #include<stdio.h> int main( ){ //printing information printf("Hello C"); return 0; } #include<stdio.h> int main( ){ /*printing information Multi Line Comment*/ printf("Hello C"); return 0; }
  • 57.
    KEYWORDS  Keywords –Conveys special meaning to Compiler  32 keywords  Cannot be used as variable names
  • 58.
    CONSTANTS  Definition :Valuedoes not change during execution  Can be a Number (or) a Letter
  • 59.
    VARIABLES / IDENTIFIERS Identifier for a memory location where data is stored  Value changes during execution  Rules for Identifiers  Combination of alphabets, digits (or) underscore  First character should be a Alphabet  No special characters other than underscore can be used  No comma / spaces allowed within variable name  A variable name cannot be a keyword  Variable names are case sensitive  Variable name length cannot be more than 31 characters
  • 60.
    VARIABLE DECLARATION  Avariable must be declared before it is used  Declaration consists of a data type followed by one or more variable names separated by commas. datatype variable_name; Syntax Examples int a, b, c, sum; float avg; char name;
  • 61.
    VARIABLE INITIALIZATION  Assigninga value to the declared variable  Values assigned during declaration / after declaration Examples int a, b, c; a=10, b=20, c=30; int a=10 ,b=10, c=10;
  • 62.
    SCOPE OF VARIABLES There are three places where variables can be declared  Inside a function or a block which is called local variables  Outside of all functions which is called global variables  In the definition of function parameters which are called formal parameters (Example: int sum( int x, int y);)
  • 63.
    SCOPE OF VARIABLES A scope in any programming is a region of the program where a defined variable can have its existence and beyond that variable it cannot be accessed  Variable Scope is a region in a program where a variable is declared and used  The scope of a variable is the range of program statements that can access that variable  A variable is visible within its scope and invisible outside it
  • 64.
    SCOPE OF VARIABLES: LOCAL VARIABLES  Variables that are declared inside a function or block are called local variables  They can be used only by statements that are inside that function or block of code  Local variables are created when the control reaches the block or function containing the local variables and then they get destroyed after that  Local variables are not known to functions outside their own
  • 65.
    SCOPE OF VARIABLES: LOCAL VARIABLES #include <stdio.h> int main ( ) { /* local variable declaration */ int a, b; int c; /* actual initialization */ a = 10; b = 20; c = a + b; printf ("value of a = %d, b = %d and c = %dn", a, b, c); return 0; }
  • 66.
    SCOPE OF VARIABLES: GLOBAL VARIABLES  Defined outside a function, usually on top of the program  Hold their values throughout the lifetime of the program  Can be accessed inside any of the functions defined for the program  Can be accessed by any function  That is, a global variable is available for use throughout the entire program after its declaration
  • 67.
    SCOPE OF VARIABLES: GLOBAL VARIABLES #include <stdio.h> /* global variable declaration */ int g; int main ( ) { /* local variable declaration */ int a, b; /* actual initialization */ a = 10; b = 20; g = a + b; printf ("value of a = %d, b = %d and g = %dn", a, b, g); return 0; }
  • 68.
    BINDING  A Bindingis an association between an entity and an attribute  Between a variable and its type or value  Between a function and its code  Binding time is the point at which a binding takes place  Types of Binding  Design Time  Compile Time  Link Time  Run Time
  • 69.
    BINDING  Design Time Binding decisions are made when a language is designed  Example  Binding of + to addition in C  Compile Time  Bindings done while the program is compiled  Binding variables to datatypes  Example  int a; float b; char c;
  • 70.
    BINDING  Link Time Compiled code is combined into a full program for C  Example  Global and Static variables are bound to addresses  Run Time  Any binding that happens at run time is called Dynamic  Any binding that happens before run time is called Static  Values that are dynamically bound can change
  • 71.
    DATATYPES  Defines avariable before use  Specifies the type of data to be stored in variables  Basic Data Types – 4 Classes  int – Signed or unsigned number  float – Signed or unsigned number having Decimal Point  double – Double Precision Floating point number  char – A Character in the character Set
  • 72.
  • 73.
    INTEGER DATA TYPE Whole numbers with a range  No fractional parts  Integer variable holds integer values only  Keyword: int  Memory: 2 Bytes (16 bits) or 4 Bytes (32 bits)  Qualifiers: Signed, unsigned, short, long  Examples: 34012, 0, -2457
  • 74.
    FLOATING POINT DATATYPE  Numbers having Fractional part  Float provides precision of 6 digits  Integer variable holds integer values only  Keyword: float  Memory: 4 Bytes (32 bits)  Examples: 5.6, 0.375, 3.14756
  • 75.
    DOUBLE DATA TYPE Also handles floating point numbers  Double provides precision of 14 digits  Integer variable holds integer values only  Keyword: float  Memory: 8 Bytes (64 bits) or 10 Bytes (80 bits)  Qualifiers: long, short
  • 76.
    CHARACTER DATA TYPE handles one character at a time  Keyword: char  Memory: 1 Byte (8 bits)
  • 77.
    EXPRESSIONS  Expression :An Expression is a collection of operators and operands that represents a specific value/operation.  Operator : A symbol which performs tasks like arithmetic operations, logical operations and conditional operations  Operands : The values on which the operators perform the task  Expression Types in C  Infix Expression  Postfix Expression  Prefix Expression
  • 78.
    EXPRESSIONS  Infix Expression The operator is used between operands  General Structure : Operand1 Operator Operand2  Example : a + b  Postfix Expression  Operator is used after operands  General Structure : Operand1 Operand2 Operator  Example : ab+  Prefix Expression  Operator is used before operands  General Structure : Operator Operand1 Operand2  Example : +ab
  • 79.
  • 80.
    INPUT AND OUTPUTFUNCTIONS  Ability to Communicate with Users during execution  Input Operation  Feeding data into program  Data Transfer from Input device to Memory  Output Operation  Getting result from Program  Data Transfer from Memory to Output device  Header File : #include<stdio.h>
  • 81.
    FORMATTED INPUT /OUTPUT STATEMENTS  Reads and writes all types of data values  Arranges data in particular format  Requires Format Specifier to identify Data type  Basic Format Specifiers  %d – Integer  %f – Float  %c – Character  %s - String
  • 82.
    SCANF ( )FUNCTION  Reads all types of input data  Assignment of value to variable during Runtime scanf(“Control String/Format Specifier”, &arg1, &arg2,… &argn) Syntax
  • 83.
    PRINTF ( )FUNCTION  To print Instructions / Output onto the Screen  Requires Format Specifiers & Variable names to print data printf(“Control String/Format Specifier”,arg1,arg2,… argn) Syntax
  • 84.
    EXAMPLE 1 –USING PRINTF ( ) & SCANF ( ) FUNCTION #include<stdio.h> void main( ) { int a; printf(“Enter the Value of a:”); scanf("%d", &a); printf("Value of a is %d", a); }
  • 85.
    EXAMPLE 1 –USING PRINTF ( ) & SCANF ( ) FUNCTION #include<stdio.h> void main( ) { int a, b, c; printf("Enter the Value of a, b & c: "); scanf("%d %d %d", &a, &b, &c); printf(“Value of a, b & c is %d %d %d”, a, b, c); }
  • 86.
    TRY IT OUTYOURSELF ! WRITE A C PROGRAM TO:  Add two numbers  To Multiply two floating point numbers  To compute Quotient and Remainder  To Swap two numbers
  • 87.
    UNFORMATTED INPUT /OUTPUT STATEMENTS  Works only with Character Data type  No need of Format Specifier  Unformatted Input Statements  getch(): It will Accepts a Keystroke and never displays it.(So that it can be used in password). That is, It Never echoes the character on screen. The Arguments to the function is any key on keyboard ,not necessarily be a character.  getchar(): It will accepts a character from keyboard & Displays it immediately. On reading any character, getchar() need to hit any key for proceeding. The argument is a character i.e alphabet(A-Z).  gets ( ) – Accepts any string from Keyboard until Enter Key is pressed
  • 88.
    UNFORMATTED INPUT /OUTPUT STATEMENTS  Unformatted Output Statements  putch()– Prints only the any alphabets  putchar ( ) – Prints any character including escape sequences  puts ( ) – Prints a String to Monitor (Output Device)
  • 89.
    OPERATORS IN C C supports rich set of built in Operators  Used to manipulate Constants (Data) & Variables  Part of Mathematical (or) Logical expressions  Operator – Definition  Symbol (or) Special character that instructs the compiler to perform mathematical (or) Logical operations
  • 90.
    ARITHMETIC OPERATORS  Anarithmetic operator performs mathematical operations such as addition, subtraction, multiplication, division etc on numerical values (constants and variables). Operator Meaning of Operator + addition or unary plus - subtraction or unary minus * multiplication / division % remainder after division (modulo division)
  • 91.
    EXAMPLE – ARITHMETICOPERATORS #include <stdio.h> int main() { int a = 9,b = 4, c; c = a+b; printf("a+b = %d n",c); c = a-b; printf("a-b = %d n",c); c = a*b; printf("a*b = %d n",c); c = a/b; printf("a/b = %d n",c); c = a%b; printf("Remainder when a divided by b = %d n",c); return 0; }
  • 92.
    ASSIGNMENT OPERATORS  Anassignment operator is used for assigning a value to a variable. The most common assignment operator is = Operator Example Same as = a = b a = b += a += b a = a+b -= a -= b a = a-b *= a *= b a = a*b /= a /= b a = a/b %= a %= b a = a%b
  • 93.
    EXAMPLE – ASSIGNMENTOPERATORS #include <stdio.h> int main() { int a = 5, c; c = a; // c is 5 printf("c = %dn", c); c += a; // c is 10 printf("c = %dn", c); c -= a; // c is 5 printf("c = %dn", c); c *= a; // c is 25 printf("c = %dn", c); c /= a; // c is 5 printf("c = %dn", c); c %= a; // c = 0 printf("c = %dn", c); return 0; }
  • 94.
    INCREMENT AND DECREMENTOPERATORS  Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. These two operators are unary operators, meaning they only operate on a single operand.
  • 95.
    EXAMPLE – INCREMENTAND DECREMENT OPERATORS int main(){ int a = 10, b = 20,c=30,d=40; printf("a++ = %d n", a++); printf("%d n",a); printf("--b = %d n", b--); printf("%d n",b); printf("++c = %d n", ++c); printf("%d n",c); printf("--d = %d n", --d); printf("%d n",d); return 0;} a++ = 10 11 --b = 20 19 ++c = 31 31 --d = 39 39
  • 96.
    RELATIONAL OPERATORS  Arelational operator checks the relationship between two operands. If the relation is true, it returns 1; if the relation is false, it returns value 0.  Relational operators are used in decision making and loops. Operator Meaning of Operator Example == Equal to 5 == 3 is evaluated to 0 > Greater than 5 > 3 is evaluated to 1 < Less than 5 < 3 is evaluated to 0 != Not equal to 5 != 3 is evaluated to 1 >= Greater than or equal to 5 >= 3 is evaluated to 1 <= Less than or equal to 5 <= 3 is evaluated to 0
  • 97.
    EXAMPLE – RELATIONALOPERATORS { int a = 5, b = 5, c = 10; printf("%d == %d is %d n", a, b, a == b); printf("%d == %d is %d n", a, c, a == c); printf("%d > %d is %d n", a, b, a > b); printf("%d > %d is %d n", a, c, a > c); printf("%d < %d is %d n", a, b, a < b); printf("%d < %d is %d n", a, c, a < c); printf("%d != %d is %d n", a, b, a != b); printf("%d != %d is %d n", a, c, a != c); printf("%d >= %d is %d n", a, b, a >= b); printf("%d >= %d is %d n", a, c, a >= c); 5 == 5 is 1 5 == 10 is 0 5 > 5 is 0 5 > 10 is 0 5 < 5 is 0 5 < 10 is 1 5 != 5 is 0 5 != 10 is 1 5 >= 5 is 1 5 >= 10 is 0 5 <= 5 is 1 5 <= 10 is 1
  • 98.
    LOGICAL OPERATORS  Anexpression containing logical operator returns either 0 or 1 depending upon whether expression results true or false. Logical operators are commonly used in decision making in C programming. Operator Meaning Example && Logical AND. True only if all operands are true If c = 5 and d = 2 then, expression ((c==5) && (d>5)) equals to 0. || Logical OR. True only if either one operand is true If c = 5 and d = 2 then, expression ((c==5) || (d>5)) equals to 1. ! Logical NOT. True only if the operand is 0 If c = 5 then, expression !(c==5) equals to 0.
  • 99.
    EXAMPLE – LOGICALOPERATORS int main() { int a = 5, b = 5, c = 10, result; result = (a == b) && (c > b) && (a<c); printf("(a == b) && (c > b) is %d n", result); result = (a == b) || (c < b); printf("(a == b) || (c < b) is %d n", result); result = !(a != b); printf("!(a != b) is %d n", result); result = !(a == b); printf("!(a == b) is %d n", result); return 0; } (a == b) && (c > b) is 1 (a == b) || (c < b) is 1 !(a != b) is 1 !(a == b) is 0
  • 100.
    BITWISE OPERATORS  Duringcomputation, mathematical operations like: addition, subtraction, multiplication, division, etc are converted to bit-level which makes processing faster and saves power.  Bitwise operators are used in C programming to perform bit-level operations. Operators Meaning of operators & Bitwise AND | Bitwise OR ^ Bitwise exclusive OR ~ Bitwise complement << Shift left >> Shift right Division Remainder (R) 112 / 2 = 56 0 56 / 2 = 28 0 28 / 2 = 14 0 14 / 2 = 7 0 7 / 2 = 3 1 3 / 2 = 1 1 1 / 2 = 0 1
  • 101.
    BITWISE AND OPERATOR&  The output of bitwise AND is 1 if the corresponding bits of two operands is 1. If either bit of an operand is 0, the result of corresponding bit is evaluated to 0.  Let us suppose the bitwise AND operation of two integers 12 and 25. 12 = 00001100 (In Binary) 25 = 00011001 (In Binary) Bit Operation of 12 and 25 00001100 & 00011001 ________ 00001000 = 8 (In decimal) A B Q 0 0 0 0 1 0 1 0 0 1 1 1
  • 102.
    EXAMPLE – BITWISEAND OPERATOR & #include <stdio.h> int main() { int a = 12, b = 25; printf("Output = %d", a&b); return 0; } Output = 8
  • 103.
    BITWISE OR OPERATOR|  The output of bitwise OR is 1 if at least one corresponding bit of two operands is 1. In C Programming, bitwise OR operator is denoted by |. 12 = 00001100 (In Binary) 25 = 00011001 (In Binary) Bitwise OR Operation of 12 and 25 00001100 | 00011001 ________ 00011101 = 29 (In decimal)) A B Q 0 0 0 0 1 1 1 0 1 1 1 1
  • 104.
    EXAMPLE – BITWISEOR OPERATOR | #include <stdio.h> int main() { int a = 12, b = 25; printf("Output = %d", a|b); return 0; } Output = 29
  • 105.
    BITWISE XOR (EXCLUSIVEOR) OPERATOR ^  The result of bitwise XOR operator is 1 if the corresponding bits of two operands are opposite. It is denoted by ^. 12 = 00001100 (In Binary) 25 = 00011001 (In Binary) Bitwise XOR Operation of 12 and 25 00001100 ^ 00011001 ________ 00010101 = 21 (In decimal) A B Q 0 0 0 0 1 1 1 0 1 1 1 0
  • 106.
    EXAMPLE – BITWISEXOR (EXCLUSIVE OR) OPERATOR ^ #include <stdio.h> int main() { int a = 12, b = 25; printf("Output = %d", a^b); return 0; } Output = 21
  • 107.
    BITWISE COMPLEMENT OPERATOR~  Bitwise compliment operator is an unary operator (works on only one operand). It changes 1 to 0 and 0 to 1. It is denoted by ~.  2's Complement  Two's complement is an operation on binary numbers. The 2's complement of a number is equal to the complement of that number plus 1.  For example: Binary number 1’s complement 2’s complement 001 110 111 010 101 110 011 100 101 100 011 100
  • 108.
    EXAMPLE – BITWISECOMPLEMENT OPERATOR ~ #include <stdio.h> int main() { printf("Output = %dn",~35); printf("Output = %dn",~- 12); return 0; } Output = -36 Output = 11 • The bitwise complement of 35 (~35) is -36 instead of 220, but why? • For any integer n, bitwise complement of n will be -(n + 1). • Two's complement is an operation on binary numbers. The 2's complement of a number is equal to the complement of that number plus 1. For example:
  • 109.
    RIGHT SHIFT OPERATOR Right shift operator shifts all bits towards right by certain number of specified bits. It is denoted by >>. 212 = 11010100 (In binary) 212>>2 = 00110101 (In binary) [Right shift by two bits] 212>>7 = 00000001 (In binary) 212>>8 = 00000000 212>>0 = 11010100 (No Shift)
  • 110.
    LEFT SHIFT OPERATOR Left shift operator shifts all bits towards left by a certain number of specified bits. The bit positions that have been vacated by the left shift operator are filled with 0. The symbol of the left shift operator is <<. 212 = 11010100 (In binary) 212<<1 = 110101000 (In binary) [Left shift by one bit] 212<<0 = 11010100 (Shift by 0) 212<<4 = 110101000000 (In binary) =3392(In decimal)
  • 111.
    EXAMPLE – SHIFTOPERATOR #include <stdio.h> int main() { int num=212, i; for (i=0; i<=2; ++i) printf("Right shift by %d: %dn", i, num>>i); printf("n"); for (i=0; i<=2; ++i) printf("Left shift by %d: %dn", i, num<<i); return 0; } Right Shift by 0: 212 Right Shift by 1: 106 Right Shift by 2: 53 Left Shift by 0: 212 Left Shift by 1: 424 Left Shift by 2: 848
  • 112.
    OTHER OPERATORS  CommaOperator  Comma operators are used to link related expressions together.  For example: int a, c = 5, d;
  • 113.
    THE SIZEOF OPERATOR The sizeof is a unary operator that returns the size of data (constants, variables, array, structure, etc).
  • 114.
    EXAMPLE – SIZE0F()OPERATOR #include <stdio.h> int main() { int a; float b; double c; char d; printf("Size of int=%lu bytesn",sizeof(a)); printf("Size of float=%lu bytes n",sizeof(b)); printf("Size of double=%lu bytes n",sizeof(c)); printf("Size of char=%lu byten",sizeof(d)); return 0; } Size of int = 4 bytes Size of float = 4 bytes Size of double = 8 bytes Size of char = 1 byte

Editor's Notes

  • #40 All higher level languages like Python, Javascript, etc, are built out of C When you want to add new features to Python, that's called an extension. And those are actually written in C! For some of Holberton’s advanced assignments, students actually write the C code that goes underneath Python, and then test them together to see it working.
  • #44 C is intended to do low-level programming. It is used to develop system applications such as kernel, driver, etc. It also supports the features of a high-level language. That is why it is known as mid-level language. C is a structured programming language in the sense that we can break the program into parts using functions. So, it is easy to understand and modify. Functions also provide code reusability. C provides the feature of pointers. We can directly interact with the memory by using the pointers. We can use pointers for memory, structures, functions, array, etc. C language is extensible because it can easily adopt new features. Unlike assembly language, c programs can be executed on different machines with some machine specific changes. Therefore, C is a machine independent language. It supports the feature of dynamic memory allocation. In C language, we can free the allocated memory at any time by calling the free() function.