0% found this document useful (0 votes)
4 views

Module 1

Fyug second semester C programming

Uploaded by

ABDUL MAJEED.K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
4 views

Module 1

Fyug second semester C programming

Uploaded by

ABDUL MAJEED.K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 22
History of C 1. Developed by ~ Dennis Ritchie at Bell Labs in 1972. 2. Evolved from —B and BCPL programming languages. 3. Purpose — Designed for system programming, especially for UNIX OS. 4, Standardization — ANSI C (1989), ISO C (1990), and later versions (C99, C11, C18). 5. Influence ~ Basis for modern languages like C++, Java, Python, and JavaScript. Importance of C 1. Foundation of Programming — Forms the base for learning other languages, 2. System-Level Programming — Used in OS development (e.g.. Linux, Windows) 3. Efficiency & Performance — Faster execution with low-level memory access. 4, Portability — Can run on different hardware platforms. 5. Rich Library Support — Provides built-in functions for various applications. 6 Embedded Systems — Widely used in microcontrollers and hardware programming. 7. Flexibility ~ Supports both structured and low-level programming. Features of ¢ + Easy'to lean + Structured language + It produces efficient programs + Itean handle low-level activities + Itcan be compiled on a variety of computers. BASIC §] _Documentation section Link s Definition section Global declaration section main () Function section t ion. Declaration part Executable part ] ‘Subprogram section Function 1 Function 2 (User defined functions) Function n |. Documentation section: The documentation section consists of a set of comment lines giving the name of the program, the author and other details, which the programmer would like to use later 2. Link section: The link section provides instructions to the compiler to link functions from the system library such as using the #include directive 3. Definition section: The definition section defines all symbolic constants such using the define direct 4, Global declaration section: There are some variables that are used in more than one function. Such variables are called global variables and are declared in the global declaration section that is outside of all the functions. This section also declares all the user-defined fimetions. 5. main () function section: ‘ery C program must have one main function section. ‘This section contains two parts: declaration part and executable part 1. Declaration part: The declaration part declares all the variables used in the executable part 2. Executable part: There is at least one statement in the executable part. These ‘Wo parts must appear between the opening and cl ‘The program execution begins at the opening brace and ends at the clo ing brace. The closing brace of the main function is the logical end of the program. All statements in the declaration and executable part end with a semicolon. 6. Subprogram section: If the program is a multi-function program then the subprogram section contains all the user-defined fiuncttons that are called in the main () function. User-defined functions are generally placed immediately after the main () function, although they may appear in any order. Character Set in C A character set is the set of characters that C recognizes and uses in programming, 1. Letters — Alphabets (A-Z, 0-2) 2. Digits Numbers (0-9) 3. Special Symbols — Used in operations (+-*/%=<>,5.0. 1) 0) 4. White Spaces ce, tab (\1), newline (\n), ete. ‘Tokens in C (Smallest units in a C program) A token is the smallest meaningful unit in a program. C tokens are the basic buildings blocks in C language which are constructed together to write a C program, Each and every smallest indi dual unit in a C program is known as C tokens 1. Keywords ~ Predefined reserved words in C with special meanings (¢.¢.. int, float, if, else, retum). 2. Identifiers — The name given to variables, functions, and arrays (e.g., sum, main). It must start with a letter or underscore (_) and cannot be a keyword, 3. Constants - Fixed values that do not change during execution (e.g., 10, 3.14, A’). 4. Operators — Symbols used for mathematical or logical operations (e.g, +,-,*./%). 5. Strings — A sequence of characters enclosed in double quotes (e.2., ello") 6. Special Symbols — Symbols with specific purposes like {} (10). 1. Keywords Ckeywonds are the words that convey a special meaning to the ¢ compiler. The keywords cannot be used as variable names. ‘The list of C keywords is given below: auto break case char const continue default do double else enum, extern float for goto if int long register retum short signed sizeof static struct switch typedef union unsigned void volatile while 2. IDENTIFIERS ‘+ Identifiers are names given to variables, functions, and arrays in C. © They are user-defined names consisting of letters, digits, and an underscore ( [19 Rules for Naming Identifiers: Vv Must begin with a letter (A-7. or a-7) or an underscore (_) only. v Can only contain letters, digits (0-9), or an underscore (_). V Special characters (e.g., @, $, #) are not allowed V Cannot be a C keyword (¢.g., int, float, return, etc.). V Cannot contain spaces. ¥ Can be up to 31 characters long (only the first 31 are significant). 09 Examples of Valid Identifiers: 1 student_name [ Marks123 (_tempVariable 1 128name (starts with a number) (float (keyword) [I user name (contains space) 3. Constants in C (Fixed values that remain unchanged) A constant is a fixed value whose value cannot be changed during program execution, 1. Integer Constants — Whole numbers (10, -25, 0). 2. Floating-point Constants — Numbers with decimal points (3.14, 0.001), 3. Character Constants — A single character enclosed in single quotes (A, '5)). 4. String Constants — A sequence of characters enclosed in double quotes ("Hello*), 5. Symbolic Constants — Defined using “define (¢.2., #define PI 3.14 to represent 2). @) Integer Constants Cbefinition: Whole numbers without fractional parts. (+ or= sign. Oo ‘+ Decimal Integer Constants (Base 10): Uses digits 0-9. © Examples: 341, 0, 8972 ‘© Octal Integer Constants (Base 8): Starts with 0, uses digits 0-7. © Examples: 010, 0424, 0540 «Hexadecimal integer Constants (Base 16): Starts with Ox or OX, uses digits 0-9 and letters ACF (A=10, B>I,....F°15). © Examples: 0xD, OX84, OxbD b. Real Constants (Floating-Point Constants) (Definition: Numbers with fractional parts. Can be written in: ‘© Fractional (Decimal) Form: 0105, 0905, 56205, 0.015 ‘+ Exponent Form (Scientific Notation): mantissa e exponent © Examples: 252185, 0.15E-10, -3e18 ¢ Character Constants Definition: A single character enclosed in single quotes (' examples: CIASCH Values: Every haracter has a numerical ASCH value. © Example: '’ has ASCII value 65. Escape Characters/ Escape Sequences allows us to have certain non graphic characters in character constants. Non graphic characters are those characters that cannot be typed directly from keyboard, for example, tabs, carriage return, ete. These non graphic characters can be represented by using escape sequences represented by a backslash() followed by one or more characters Escape Sequence Description a ‘Audible alert(bel) b Backspace F Form feed n ‘New line T ‘Carriage retum t Horizontal tab v Vertical tab v Backslash a Double quotation mark : Single quotation mark 1 ‘Question mark Null d. String constants String constants are sequence of characters enclosed within double quotes. For example, “hello” “abe” “123” Every sting constant is automatically terminated with a special character ‘\0" called the mull character which represents the end of the string, 4. Special Symbols ‘The following special symbols are used in C having some special meaning and thus, cannot be used for some other purpose. UO0.5: 98 Braces{}: These opening and ending curly braces marks the start and end of a block of code containing more than one executable statement. Parentheses(): These special symbols are used to indicate function calls and function parameters, Brackets[]: Opening and closing brackets are used as array element reference. These indicate single and multidimensional subscripts, 5. Variables in C (Named storage locations in memory) A variable is a name given to a memory location where data is stored and can be changed during execution + Every variable has a specific type, which determines v Memory size and layout ¥ Range of values it can store ¥ Operations that can be performed on it, ‘+ Can store different types of data (integer, float, char). Variable Naming Rules v Can contain letters, digits, and underscore (_) only. Vv Must start with a letter or an underscore (_) only. (¢.2., total. com). ¥ Case-sensitive (¢.g., age and Age are different) © Cannot be a keyword (e.g, int is not allowed as a variable name), ‘+ Must be declared before use (¢.g., int num) Example: int age float pi 5; ‘age’ is a variable storing an integer value 25 3.14; //'pi' is a variable storing a floating-point value Basic Variable Types in C [Type Description kar [Stores a single character (1 byte, integer type). [it [Stores an integer (whole number) lacat_ [Stores a single-precision floating-point number. {ioubie Stores a double-precision floating-point number. oid [Represents absence of a type (used in functions). Other variable types include Enumeration, Pointer, Array, Structure, and Union. Variable Definition/Declaration in C Definition: + Specifies data type and allocates memory for the variable, = Syntax: datatype variable_list © datatype + Valid C data type (c.g,, int, char, float) © variable_list + One or more variable names, separated by commas. Examples inti j Defines three integer variables i, j, and k float height, weight; / Defines two floating-point variables Variable Initialization (Variables can be assigned an initial value when declared. © Syntax: type variable name = value + Examples: intd=3.£= 5; // Integer variables initialized with values char Character variable Data Types in C (Specifies the type of data a variable can hold) A data type determines the type and size of data a variable can store 1. Primary Data Types «int — Stores integer values (10, '* float ~ Stores decimal values (3.14, -0 01). © char ~ Stores a single character (4'). ‘© void ~ Represents "no value," mainly used for functions. These are the fundamental data types in C, used for storing simple values. Data Type [Size (bytes)| Range fthar I byte 128 to 127 (Signed) | 0 to 255 (unsigned) ft [2 or 4 bytes [32,768 to 32,767 (2 bytes) /-2, 147,483,648 to 2,147,483,647 (A bytes) faoat reyes PAE-38 wo 34EI3S [foubie [8 bytes __[L.7E-308 to 1.7E=308 oid bytes [No value (used in functions) (Examples: char grade ~ int age = 25, float pi~ 3.14; double largediabe 2. Derived Data Types * Array 87654321, A collection of similar data types (int ar . © Pointer — Stores the memory address of another variable (int *p:) * Structure — Groups different data types (struct { int a; char b; }:). ‘© Union — Shares memory between members (union {int a: float b.}:) ‘These are built from primary data types using special features. Derived Type Description Array {Stores multiple values of the same type (e.g., mt an{10):) Pointer [Stores address of another variable (int *pt;) [Function [Contains reusable blocks of code (int sum(int int.) (Examples: int marks[5] = (90, 85, 88, 92, 753, // Array int *pte~ &marks[0}; // Pointer to an integer 3. User-Defined Data Types © typedef — Used to create a new name for existing types (typedef unsigned int wink). ‘© enum — Defines a set of named integer constants (enum days (Sun, Mon, Tue}:). These are custom data types created using structures, unions, or enums. User-Defined Type Description hiruet [Groups different types of variables together fanton| [Similar to struct, but shares memory between members Jena [Defines named integer constants a User-defined data types allow eustom data structures to make programs more readable and maintainable. Two important user-defined types in C are typedet and ens 1. typedef (Type Definition) V typedef is used to create a new name (alias) for an existing data type. v This makes the code shorter, more readable, and easier to modify. (Example: typedef unsigned int uint, // Now ‘uint’ is an alias for ‘unsigned int’ tint age = 25. // Equivalent to unsigned int age = 25: 19 Use Case: Instead of writing uasigned int every time, we can simply use uit (Using typedef with structures: typedef struct { char name(20]; int age: } Student, ‘Student s1 = {"Alice", 20}, (19 Advantage: Instead of writing struct Student, we can simply use Student 2. enum (Enumeration) V cnum defines a set of named integer constants. ¥ Each value in an enum is automatically assigned integer values (starting from 0 by default). Example: enum Days {Sun, Mon, Tue, Wed, Thu, Fri, Sat}; enum Days today = Wed, // today is assigned 3 (since Sun=0, Mon=1, Tue=2, Wed=3) custom Values in Enut enum Colors {Red = 1, Green Blue= 5}; enum Colors myColor = Green; // myColor is assigned 3 5. Type Qualifiers in C Type qualifiers modify how variables are stored and used in memory () Signed & Unsigned Qualifiers V signed (default) —> Supports both negative & positive values. ¥ unsigned —> Stores only positive values, doubles the positive range. | Data Type |Size (bytes)] Range kignedint [4 2, 147 483,648 to 2,147 483,647 finsigned int [4 to 4,294,967, 295, q 12810 127 funsigned char [I to 255 (Example: signed int num] ~ 100; (/ Can store negative and positive unsigned int nam2 = 200; // Only positive values, (ii) Short & Long Qualifiers ¥ short + Reduces memory size. ¥ long — Increases range for large values. Data Type |Size (bytes) Range fhonimt [2 32,768 to 32,767 fing int — ‘aor 8 2, 147,483,648 to 2,147,483,647 (or more) long long int [8 -9,223,372,036,854,115,808 to 9,223,372,036,854,775,807 Example: short int smallivum = 32767, // Uses 2 bytes long int larzeNum = 100000; // Uses 4 or $ bytes Tong long int hygeNVum = 9999999999; // Uses 8 bytes Operators in C Operators in C are symbols that perform operations on variables and values. They help in arithmetic calculations, logical operations, bit manipulations, and more. C language offers many types 1. Arithmetic operators f operators. They are, 2. Assignment operators Relational operators Logical operators Bit wise operators Conditional operators (temary operators) Increment/decrement operators, aN awe Special operators 1. Arithmetic Operators These operators perform mathematical calculations like addition, subtraction, multiplication, and division. [Operator Definition Result FF [Adds two values pb F ISubtracts second value from first P IMultiplies two values pe> 50 V [Divides first value by second a/b Iz fe (Gives remainder of division pep lo 2. Relational (Comparison) Operators ‘These operators compare two values and return true (1) or false (0). [Operator] Definition Example (a=10,b=5) | Result hhecks if two values are equal Dp (false) = |Checks iF two values are nat equal hr (true) > |Checks if first value is greater la>b h hecks if first value is smaller ace lb |Checks if first value is greater or equal h |Checks if first value is smaller or equal lo 3. Logical Operators Used for logical operations that return true (1) or false (0). [Operator] Definition Example ( Result IReturns true if both conditions are| Jes [2 ss» lb rue [Returns true if at least one condition is true Reverses the logical state Ta lp 4. Bitwise Operators ‘These operators perform bit-level operations on numbers. [Operator] Definition Example (a =5 (010), b=3 (0011) Result fz jitwise AND bab Fr litwise OR a litwise XOR ~e F jsitwise NOT left Shift (multiplies by 2)|> << 1 fo (1010) = Right Shift (divides by 2) [2 >>2 5S. Assignment Operators Used to assign values to variables. [Operator] Definition Example (a =10) [Equivalent to’ Assigns a value |Adds and assigns ibtracts and assigns |Multipties and assigns Divides and assigns |Modulus and assigns 6 In crement & Decrement Operators Used to inerease or decrease the value of a variable by 1 [Operator] Definition Example (a=5) |Result lincrements by 2 [2+ (Post) 5 lincrements by 1 la (Pre) [Decrements by 1) [2== (Post) Is lDecrements by 1) -—a (Pre) Difference Between Postfix (a+-+) & Prefix (++a) (19 a ++ — First use then increase. (19 ++ — First increase then use. Example int x= 55 printf ("96 printf "6d", ++ 7. Conditional (Ternary) Operator A shorthand for itelse conditions. Syntax: ,sc+t)2 [/ Output: 5 (uses first, then increments) + /f Output: 7 (increments first, then uses) condition ? exp sion_if_true t expression if false; Example: int 10, intimin = (x Logical Expressions — Expressions that use logical operators (<<, ||, Example: (a>b) 66 (zb Pointer Expressions — Expressions that work with memory addresses. © Example: ptr = a7, *pte = 10 2. COperator Precedence and Associativity (19 Operator precedence determines which operator is evaluated first in an expression, (19 Associativity defines the direction in which operators of the same precedence are evaluated. + Left to Right (L > R) or Right to Left (R > L) Operator Description Associativity ()___ [Parentheses (function call) (see Note 1) left-to-right L] [Brackets (array subscript) : lember selection via object name fe Member selection via pointer +++ _Jpostfis increment/decrement (see Note 2) =5—__ [Prefixincrement/decrement right-to-left += Unary plusiminus 1~ |Logical negation/bitwise complement (ype) [Cast (convert value to temporary value of type) IDereference & [Address (of operand) sizeof _ [Determine size in bytes on this implementation * 7% _ [Multiplication/division’modulus Teft-to-right = [Addition/subtraction Teft-to-right « [Bitwise shift left, Bitwise shift right Teft-to-right <== Relational less than less than or equal to Teft-to-right [Relational greater than’ greater than or equal to [Relational is equal tois not equal 0 Teft-to-right & __ [Bitwise AND Tefi-to-right [Bitwise exclusive OR Teft-to-right |___[Bitwise inclusive OR Teft-to-right ILogical AND Teft-to-right [Logical OR Teft-to-right [Temary conditional right-to-left [Assignment right-to-left | Addition/subtraction assignment IMultiptication ‘division assignment |Modulus/bitwise AND assignment [Bitwise exclusive/inclusive OR assignment = FE _JBitwise exclusive/inclusive OR assignment Gdanina qhepdaltcrsipirassignsyent left-to-right Parentheses are also used to group sub-expressions to force a different precedence: such parenthetical expressions can be nested and are evaluated from inner to outer. Note 2: Postfix increment/decrement have high precedence, but the actual increment or decrement of the operand is delayed (to be -omplished sometime before the statement completes execution), So in the statement y =x * 2+45 the current value of % is used to evaluate the expression (i.c., 2+ evaluates to z) and 2 only incremented after all else is done. Evaluation of Expressions in C + 1. Parentheses First: © Expressions within parentheses () are evaluated first. © They override the default operator precedence. + 2. Left-to-Right Evaluation (When No Parentheses): © If'there are no parentheses, the expression is generally evaluated from lef to right. + 3. Two Priority Levels of Arithmetic Operators: © High Priority Operators: + Multiplication (+), Division (/), and Modulus (3) © Low Priority Operators: + Addition (+) and Subtraction (-) + 4, Two-Pass Evaluation Procedure: © First Pass (High Priority): + Scan the expression from left to right. + Apply multiplication, division, and modulus operations as they are encountered © Second Pass (Low Priority): + After high priority operations are resolved, scan the expression again from left to right + Apply addition and subtraction operations as they are encountered +S. Examp! © Consider the expression: 19 +2 *5 + First Pass: + Evaluate 2*5 + 10 + Expression becomes: 20 + + Second Pass: * Evaluate 10 +10 > 2 + Then evaluate 20-3 17 ‘These points summarize how C evaluates arithmetic expressions, emphasizing the importance of operator precedence, associativity, and the use of parentheses to control evaluation order. Type Conversions in C a. What Are Type Conversions? ‘¢ Definition: Changing a variable from one data type to another. ‘© Purpose: To ensure that operations are performed correctly when different data types are mixed. . Types of Conversions 1. Implicit Type Conversion (Automatic Conversion) © What It Is: The compiler automatically converts data types without explicit instructions from the programmer. in an arithmetic operation +1 //'alis implicitly converted to float. + Follows the usual arithmetic conversion rules. + Happens when mixing different data types in an expression. Ensures that the conversion maintains as much precision as possible. 2. Explicit Type Conversion (Casting) © What It Is: The programmer manually converts one data type to another using a cast. CopyEdit float £ - 3.147 int L~ (int) £2 // fis explicitly converted to an int. © Use Cases: + When you need to control or force a specific conversion. + When implicit conversion might lead to loss of precision or unintended results. Type Promotion and Conversion Rules ‘* Type Promotion: When operands in an expression are converted to a common data type. «Conversion Hierarchy: In expressions, lower-ranked types are promoted to higher-ranked types. © Forexample: char > int > float > double ‘Mathematical Functions in C ‘a. What Are Mathematical Functions? ‘+ Definition: Predefined functions provided by the C standard library (typically in ) to perform common mathematical operations. + Purpose: Simplify the execution of mathematical computations. ». Commonly Used Mathematical Functions © double sqrt (double x) ; © Purpose: Returns the square root of ::. Exampl get (16.0) retums 4.0 ‘* double pow (double bas. double exponent) ; Purpose: Raises base to the power of ex; Exampl 3-0) retums s * double sin (double x) © Purpose: Returns the sine of x: (where »: is in radians). 0 Example: sin (3.14159 / 2) approximates 1.0. © double cos (double x) ; © Purpose: Returns the cosine of :: (where «is in radians). o Exampl 15 (0.0) returns 1.0 + doubie tan (double x) ; ‘© Purpose: Returns the tangent of »: (where « is in radians) Example: an (3.14159 / 4) approximates 1.0. + double log (double x) > © Purpose: Returns the natural logarithm (base e) of « og (2-71 © Exampl 8) approximates 1.0. ‘+ double exp (double x) ; (0 Purpose: Returns = raised to the power of © Example: ¢xp (1.0) retums approximately 2.71928 © double fabs (double x) ; (0 Purpose: Returns the absolute value of «. returns 1. Reading and Writing a Character a. Reading a Character + Function Used: ar ( ‘© Purpose: Reads the next available character from the standard input (keyboard). 0 Usage: CopyEdit intcn; hb har () // Reads one character and stores its ASCII value in ch Note: + gotchar () returns an int to accommodate the special end-of-file marker (202). * Itreads a single character at a time. b. Writing a Character © Function Used: ar ( 0 Purpose: Writes a character to the standard output (screen). Usage: CopyEdit int ch ~'As putchar (ch) + // Prints the character ‘A’ Note: + putchar () prints one character at a time. F if an error occurs. + Itreturns the character printed, or 2. Formatted Input a. Using scanf () for Formatted Input ‘© Purpose: Reads formatted input from the standard input (keyboard), © Syntax: CopyBdl t scanf |"format_specifier", variable) + ‘+ Common Format Specifiers: © td—Reads an integer. &£—Reads a floating-point number. © te—Reads a single character. 5 —Reads a string (sequence of characters) until a whitespace is encountered. = Exampl CopyBdit int pum; float £7 char chs char ctr (50); scanf ("%éd", num) ; // Reads an integer scanf ("94", sf); // Reads afloat scanf("%c", ch); // Reads a character (note: space before %c to skip any whitespace) scanf ("%és", str); // Reads a string (no ampersand needed for arrays) b. Important Points for scant () ‘+ Address Operator: For variables (except arrays), use the « operator to pass their address. ‘© Whitespace Handling: © Be careful with &< and &= as they may capture or skip whitespace; use spaces in the format string if needed. ‘+ Input Buffer: © scant () reads input until a whitespace is encountered for $= and may leave the newline character in the buffer. 3. Formatted Output a. Using print £() for Formatted Output ‘© Purpose: Prints formatted output to the standard output (screen). © Syntax: CopyBdit printf ("format_string", valu ‘+ Common Format Specifiers: © tdl—Prints an integer. \£—Prints a floating-point number (default prints 6 digits after the decimal point). © te Prints a single character. © As —Prints a string. = Example: CopyEdit int nun = 10; float f =3.14; char char ete | = "Hello, World!"; printf ("Integer: 96d\n", cum); // Prints: Integer: 10 printf ("Float: %f\n", £); _// Prints: Float: 3.140000 printf ("Character: %c\n", ch) 7 _// Prints: Character: A printf ("String: %s\n", str): // Prints: String: Hello, World! bb. Formatting Options in print £() © Feld Width: © Example: $52 prints an integer in a field of S characters. ‘© Precision: © For floats: ¢.2£ prints a floating-point number with 2 decimal places. Left/Right Alignment: © Aminus sign before the field width (e.g,, ¢=5a) left-aligns the output, Example with Field Width and Precision: CopyBait printf("Number: %5d\n", num) s _// Right-aligns the integer in a S-character field printf(*Float:%-10.2f\n", £); // Left-aligns the float in a 10-character field with 2 decimals

You might also like