Docsity

Introduction to C Programing, Study notes of Information Systems

Partial preview of the text

Download Introduction to C Programing and more Study notes Information Systems in PDF only on Docsity!

= Page - 1 Introduction to C Programming. What is C? Cisa general - purpose, procedural computer programming language supporting structured programming, lexical variable scope, and recursion, with a static type sal It was developed in the early 1970s by 2 Ritchie at Bell Labs. It is widely used for system programming , including developing operating systems (like UNIX), compilers, and embedded systems. an Exam Tip e Features: Simple Remember C is a | ° Efficient. foundational language | - Portable for OS development eh an si & competitive coding! e lad- aN + Structured — © Rich Library. Libraries ’ Executabl nt Preprocessor |->| Compiler Assembler |—>| Linker }—> (exe/a- out - ICS} CamScanner Page - 2 Introduction to C Programming. History of C - C was developed at Bell Labs in 1972. - It was designed by Dennis Ritchie as an evolution of the | - Derived from an earlier language called BCPL (Basic Combined Programming Language). - Unix operating system was rewritten in C, demonstrating its power and efficiency. Key Features of C 9SOgar Rathod + Procedural Language - C follows the procedural paradigm, using functions to structure code. ° Static Type System - Every variable has a specific data type that is known at compile time. * Low-Level Access — Allows manipulation of bits, bytes, and addresses for system-level programming. « Fast & Efficient - C code is fast due to minimal runtime overhead, making it suitable for performance-critical applications. + Powerful Standard Library - C has a rich set of built-in functions for performing a variety of common tasks. + Portability — C programs can be compiled and run on many different platforms with little or no modification. ICS} CamScanner Page - 4 Introduction to C Programming. Variables and Data Types Variables in C must be declared before they can be used. A variable declaration specifies a data type and a name for the variable. Here are some common data types in C: Dato Type Description Size | Example jink Integer type | 4 bytes int age = 25; float | Floating-point 4 bytes float weight = 6s. Sf; | sibeeresn Oo | number = char Single character } 4 byte ‘char grade = “A”; double | Double precision | 8 bytes double pi = 3.14159; | floating-point. void | No value (used | — - zi ica | with functions) | Mint Geeta, he te _Bool BoA (true/false) 1 ae —Bool isHappy = 1; Pesos oe value. pa b= <2 on Note: » C is case-sensitive. This means “Age”, AGE”, and “ age” ” would be considered different variables. Variable Declaration Syntox: data_type variable_name = value; Example: int age = 25; & Helpful Tip: Use meaningful variable names. Eg, use “height” instead of “h” for better readability. ICS} CamScanner _ OO —_— rl etttt~— ——— Page -5 Introduction to C Programming Input and Output inc Tn C, input and output operations are carried out using standard library functions. Here are the primary functions used : ‘@printfO Function Usage: printf (format_string, arguments) ; =< © Format specifiers begin with % to represent varifabte. types within the format string. | Format Specifier [= integer n= aaa Example hod | Floating-point | printf ("D'", %sln", name); Ag | String printf(‘Zd", & age); | 5 Example: int age = 25; float height = 5.9; printf(“Age: %d. Height: %.1f feet.in’, age, height); Output: Age: 25, Height: 5.9 feet. @: scanfQ Function Bam Tp Usage: scanf(format_string, &variables); | Remember to is &" before = | variable names in “scanf’ td #include provide the address of 1 Include standard library the variable for storing the int mainO { input value. int age; // Declare an integer variable printf ("Enter your age: ");// Output prompt scanf("%d", &age); printf ("You are %d years old.\n”, age; // Output result | return O; } Output Enter your age: 25 You are 25 years old. be Page -7 Introduction to C Programming. Control Structures in C Control structures allow you to manage the flow of a program. They include conditional statements and loops to control the execution of code blocks: @ Conditional Statements Conditional statements are used for r decision-making. — if if Statement _ jaa Usage: if (condition) ra * if (x >0)¢ /* code */ printf (Positive\n’); ca , |. Soe if-else Statement ie Usage: if (condition) { /* code if true */ if (x >o)¢ /* code if false */ Printf('Positive\n"); } ‘if-else if-else Ste Statement Usage: if (condition1) { /* code if condition Lis true «/ | if (x >0) € /* code if condition2 is true ¥/ on Hy 7* code if all conditions are false * else { ‘ printfCZeroin); @: Loops: } Loops allow repetitive execution of a block of code. The primary loops in C. 2} e for er Used to execute a block of code a specific number of times. e Onile Loop Executes a block of code as long as a condition is true. ° © do-whil Li Executes a block of code once, then repeats as le as os contin | is true. ‘@ Note: Control structures ¢ are fundamental for writing Flexible and efficient ; programs. _ = | ICS} CamScanner = Page ~ 8 Introduction to C Programming. Loops in C Loops are used to execute a block of code repeatedly. In C, there are three primary types of loops: ° for Loop ‘s for Loop + while Loop Q: for Loop Usage: for (initialization; condition; increment) { ° Example for (int i = O; i<5;i++) Output: O}2 3.4 printfC%d , i); = paleesey } Output: 01234 @ while Loop Usage: while (condition) { | e Example: - int i = O; Output: 01234 while (i < 5) { printfC%d , i); fe i+t+5 @ do-while Loop Loops allow repetitive loop, the do-while loop guarantees at least one iteration of the code block. | Uniike the while loop, the do-while loop guarantees at least one iteration of the | code block. _ © Example: int i = O; | Output: 01234 do { printfC%d , iD; e fonbieveiis i++; Output: 01234 ) while Ci < 5); | @ Tip - | \ Se Fage - 10 Introduction to C Programming. _ Arrays inc Arrays are used to store multiple values of the same data type. An array isa collection of elements that can be accessed using an index. @Syntox: | data_type array_namelsize]; fe Zee ey A function in C has the following components: le Return Tupe: Specifies the type of value the function returns (eq, int, float) } © array_name: The identifier used to call the array © size: | Inputs to the function, specified inside parertheses (optional) @ Example: | Syntax: dato_type array_name[size]= {valuet, value2, ...}; ? int numbers[5] = {10, 20, 30, 40, 50}; | Output: 01234 | 10 | 20 | 30 | 40 | so [ so oO. 1 2 3 3 4 g Example: Usage: data_type array_name[size] = {value1, value2, ... 3; int numbers[5] = {10, 20, 30, 40, 50}; printf C'Second element: %d\n’, numbers[1]); // Access the second element. Output: O12 34 @ Note: Array indexing starts at O, so the first element is at index O, the second at index 1, and soon. | ICS} CamScanner @'Syntox: Page - 11 Introduction to C Programming. More on Arrays Arrays in C can be maniplated in various ways. Here are some common operations and concepts related to arrays: | Array Initialization: Arrays can be intialized at the time of declaration. ° ew data_type areyunamelsee)= aA values; -value2,, aoe HS * A function in C has the following components: > data_type: The coe © array_name: ‘The identifier used to call the array | ‘@ Example: [Santon data_type array_name[size] = = { valuet, value2, ...3; ata type of the demenis (eg., int, float) 2 | | int numbers[5] = {10, 20, 30, 40, 50); | | // Cashee:\nt 4 value — & 7; index tO Output: ¢ o1234 “@Array Length: The length (number of elements) of an array can be determined using: length = sizef' (array_name) / sizef Cdata_type); : =f int numbers[S] = {10, 20, 30, 40, 50); | int length = sizef(numbers) / sizefC numbers[o]); | printf ("Array length: %d\n", length); Output: Array length: 5 g Note: ; aie nae Be careful when accessing arrays. Accessing an index out of bounds (e.g., numbers[5]) can lead to undefined behavior or crashes. ICS} CamScanner —=_ Fage - 13 Introduction to C Programming. Dynamic Memory Allocation Dynamic memory allocation allows Programs to request and manage memory while the program is running. In C, we use the stdlib.h library functions to allocate and free memory dynamically: Syntax: malloc) Allocates a specfied number of bytes and returns a pointer to the allocated memory. © Syntax: pointer = (data_type*) malloc (size_in_bytes) ; e A function in C has the following components : } eC) int * arr; arr = (int*) malloc(S * sizofCint)); // Dynamically allocate an array x J if (arr '= NULL); arr(O] = 10; printfC'First element ; %d\n”, arr[o]); free (arr); // Free dynamically allocated memory Output: First element: 10 ‘Pointer and Address-of Operator ‘@ Dereferencing Pointer The address-of operator (&) gives Frees dynamically allocated memory, the memory address of a variable. releasing it for future use. | free ( pointer_name) : Output: First element: 10 oe Note: Failing to free dynamically allocated memory can lead to memory leaks. Page - 14 Introduction to C Programming. More on Dynamic Memory Allocation Beyond malloc) and free(), the reallocQ function can be used to resize previously allocated memory blocks. Q'Syntox: pointer = realloc (pointer, new_size); / Feode */ | e A function in C has the following components: © Syntax: pointer = (data_type*) malloc (size_in_bytes) ; « A function in C has the following components: | int * arr; | arr = (int*®) malloe(3 * sizof(int)); // Allocate an array of 3 integers | if (arr 1 = NULL); | arr[O] = 10; | arr[2] = 20; arr = realloc.Carr, 5* sizdzoFCint)), // Resize the array to hold 5 integers | if (arr t= NULL)$ | arr(3] = 40; ine | arr(4] = 50; printf (Elements in the array: a) | Output: First element: 10 | Program © (ee Progtait oj1/2]3]/4 ° 123 4 Pointer "arr" points here Tip:-Always check if realloc() siccessfully He New size reallocated the memory before using it. 1o|20|30|30] | |s0 Tip: realloc® can be used to grow or shrink. | a ee an array of dynamically allocated memory | Heap Memory to a new size. | @: Note: | | | Foiling to free dynamically allocated memory can lead to memory leaks. AGE = 48 Introduction to C Programming. Examples of Conditionals Here are three examples illustrating the use of conditional statements in C. '@ if Statement ° Executes a block of code if a condition is true. | Syntax: pointer = rea\loc(pointer, new_size); ieee <2 | int num = (5; | if Gnum > o){ | printfCThe number is positive.\n'); | } | Output: The number is positive. ig if-else Statement * Executes one block of code if a condition is true, and another block if it is false. \; Syntax: int num = 42; ar if Cnum 4 2 == o){ i] | printfCThe number is even.\n'); [Program |, [o1 1|2]3]4]) } else { Oat 23 4°) | printfCThe number is odd.\n"); 10 | 20] 20| 40/50 } o 12 3 6 | Output: Non positive. Heap Memory | '@ if-else if-else Statement: + Example: Check whether a number is positive, negative, or zero. Ore Consider all possible conditions to ensure your program behaves correctly under different inputs. ICS} CamScanner Try, _Fage -17 Introduction to C Programming. The switch Statement Here are three examples illustrating the use of conditional statements in C. @ if Statement * Executes a block of code if a condition is true. | ‘Syntax: switch (variable) © A faction name con to Print the doy number. * Switch (variable) { | case voluei: | (F code for value1 } | break; | i € code «/ 3 | Output: The number is positive. gQ if-else Statement: * Executes one block of code if a condition is true, and anather block if it is false. : | | Syntax: [Progam sopra ]314 \ int num = 42; \ 6 23.4 | if (num ¥% 2 == O/{ printfC The number is even.\n"); 10 |20 1221S 0\50 Oo i 2 3.4 | } else { printfC'Non positive \n"); Heap Memory | | Output: Wednesday Co Heap Memory > Output: Wednesday Qg Note: Its impuder al\ possible conditions to ensure your program behaves correctly under different inputs.