Week 1 - Introduction C Programming PDF

Summary

This document provides an introduction to C programming, covering fundamental concepts like data structures, computer organization, and different programming styles.

Full Transcript

CST8234 – C Programming Week 1 - Introduction About C Programming INTRODUCTION Developed in 1972 at Bell Labs One of the most established programming languages Initially known as ‘development language of UNIX’ C is one of the world’s most...

CST8234 – C Programming Week 1 - Introduction About C Programming INTRODUCTION Developed in 1972 at Bell Labs One of the most established programming languages Initially known as ‘development language of UNIX’ C is one of the world’s most senior computer programming languages Used to develop systems that demand performance such as OS, embedded systems, RTOS and Comms Systems Usage in Operating Systems Key role in major desktop OS (partially written in C): Windows, macOS, Linux Applications built with C Popular web browsers: Google Chrome, Mozilla Firefox Database management systems: Microsoft SQL Server, Oracle, MySQL 2 About C Programming Development Environments Microsoft Visual Studio 2019 Community Edition (Windows) Clang in Xcode (macOS) GCC (GNU Compiler Collection) in a shell (Linux) GCC in a Docker Container (running GCC) C11 and C18 Standards (bug fixes in 2018) Doesn’t support OO programming features 3 Key Characteristics 1) Procedural Language: Focuses on procedure or function-based programming. 2) Low-level Access: Provides direct access to memory and hardware, making it suitable for system-level programming. 3) Portability: Code written in C can be compiled and run on different machines with minimal modifications. 4) Standards-Based: Adheres to ANSI standards, ensuring consistency across different platforms. 5) Predictable Behavior: No unexpected garbage collection; memory management is under the programmer’s control. 6) Rich Library Support: Includes a standard library with numerous built-in functions for handling I/O, memory allocation, and more. 7) Structured Language: Supports structured programming with control flow constructs like loops, conditionals, and functions. 8) Static Typing: Requires explicit declaration of variable types, enhancing type safety and performance. 9) Modularity: Encourages code reuse through functions and modular programming practices. 10) Pointer Arithmetic: Allows direct manipulation of memory through pointers, offering fine- grained control over system resources. 4 Computer Organization 1) Logical Units Input Unit: Captures data and programs from input devices and makes them available for processing in other units Output Unit: Sends processed data to output devices, making it accessible outside the computer Memory Unit (Fast-access): Stores data received from the input unit for immediate processing. It also holds processed information until it is transferred to output devices. Data in memory is volatile and typically lost when power is off. Called: memory, primary memory, or RAM (Random Access Memory). Desktops and notebooks commonly have 8 to 16 GB of RAM, though it can be up to 128 GB GB (gigabytes) equals approximately one billion bytes; a byte is 8 bits, and a bit is a 0 or 1 are the measurement units 5 Computer Organization Arithmetic and Logic Unit (ALU): The “manufacturing” unit performs arithmetic calculations (addition, subtraction, etc.) and logical comparisons (e.g., checking if two values are equal). It is part of the CPU. Central Processing Unit (CPU): The “administrative” unit manages and coordinates the operations of the other units. It: Directs the input unit to load data into memory. Instructs the ALU to perform calculations using data from memory. Commands the output unit to send data from memory to output devices. Multicore Processors: Modern CPUs often feature multiple cores on a single chip, allowing for simultaneous operations. For example: Dual-core processors (2 CPUs), Quad-core processors (4 CPUs), Octa-core processors (8 CPUs) and Intel offers processors with up to 72 cores. 6 Computer Organization Secondary Storage Unit: The “long-term warehousing” unit provides high- capacity storage for programs and data not actively used. Information here is persistent and remains available even when the computer is off. Access Time: Secondary storage is slower to access than primary memory but is more cost-effective per byte. Capacity: Modern drives can hold terabytes (TB) of data, where 1 TB equals approximately one trillion bytes. Examples: Includes SSDs, USB flash drives, hard drives, and read/write Blu-ray drives. 7 Data Hierarchy in C The data hierarchy in C language refers to the organization of data from the smallest unit to more complex structures. Bit: The smallest unit of data, representing a binary state: 0 or 1. Field: Group of bits. For example: Person’s name or age. Character: Digits, letters and special symbols are known as characters. C uses the ASCII (American Standard Code for Information Interchange) character set by default. C also supports Unicode® characters composed of one, two, three or four bytes (8, 16, 24 or 32 bits, respectively). Records: Employee Record (ID #, Name, Address, etc.) Files: Group of related records. Some Oss view it as sequence of bytes (trillions of characters) Database: Collection of data organized for easy access and manipulation. 8 Programming Languages Overview 1) Machine Languages: The only language directly understood by a computer, defined by its hardware. Consists of binary code (strings of 1s and 0s) that instruct the computer to perform basic operations and is Machine-Dependent. 2) Assembly Languages: Uses English-like abbreviations to represent basic operations. Assembler programs translate assembly language instructions into machine language quickly 3) High Level Languages: Designed to simplify programming by using statements that resemble everyday English and common mathematical notation. Allows substantial tasks to be accomplished with single statements Compilers convert high-level source code into machine language C Language: Among the most widely used high-level programming languages, known for its efficiency and versatility 9 When Programming in C… When programming in C, you’ll typically use the following building blocks: ❑ C standard library functions ❑ open-source C library functions ❑ functions you create yourself, and ❑ functions other people have created and made available to you 10 The C Standard Library A collection of pre-written functions and macros provided as part of the C programming language standard. Purpose: Facilitates common tasks such as input/output operations, memory management, string manipulation, and mathematical computations. Header Files: Include ‘’ for standard input/output, ‘’ for memory allocation and process control, ‘’ for string operations, ‘’ for mathematical functions, etc. Standard Functions: Examples include ‘printf()’, ‘scanf()’, ‘malloc()’, ‘free()’, ‘strlen()’ and ‘sqrt()’. 11 Open-Source Libraries Libraries developed and maintained by the open-source community, available for free use and modification. Purpose: Extend the functionality of C programs by providing additional tools, utilities, and features not covered by the standard library. Examples: GNU C Library (glibc) libcurl: A library for transferring data with URLs, supporting multiple protocols such as HTTP, FTP, and more. SQLite: A lightweight, self-contained SQL database engine used for embedded database applications. 12 Combining Libraries C programs often utilize both the standard library and open- source libraries to leverage built-in and extended functionalities Installation: Open-source libraries may need to be installed and linked properly with C projects, often through package managers or manual installation 13 Other Programming Languages C++ Developed by Bjarne Stroustrup in the early 1980s at Bell Laboratories, C++ builds upon C with object-oriented programming capabilities Python An object-oriented language released in 1991 is used for data science and analytics Java Funded by Sun Microsystems in 1991; Java is an object-oriented language based on C++ Slogan: "Write once, run anywhere“ Widely used in enterprise applications, web servers, and consumer device applications R open-source language specialized in statistical computing and data visualization. 14 Other Programming Languages C# Derived from C++ and Java, C# is one of Microsoft’s primary object- oriented programming languages Designed to integrate web capabilities into computer applications JavaScript A scripting language used to enhance web pages with interactivity Many Python visualization libraries generate JavaScript for web display NodeJS: Enables JavaScript to be executed outside of web browsers Swift Created by Apple for iOS/macOS applications; open-source Incorporates elements from Objective-C, Java, C#, Ruby, Python, and others. 15 Typical C Program-Development Environment INVOLVES 1) Program-development Environment: The complete setup used for writing and managing C programs, including text editors, IDEs, and tools for debugging and testing 2) C Language: The programming language used to write the source code for C programs. 3) C Standard Library: A collection of pre-written functions and macros that provide common functionalities, such as input/output operations and memory management. 16 Integrated Development Environment 1) VSC: open-source code editor developed by Microsoft that supports a wide range of programming languages, including C. Built-in Git support for version control and source code management Download and install VS Code from the official website Build and Debug: Install GNU GCC Compiler. 2) Vim: open-source text editor Plugins: ‘vim-Cmake’ for CMake integration Build and Debug: Use external tools such as ‘make’ and ‘gdb’ 17 Running a C Code in a Linux Environment 1) Write your code Using your preferred IDE (refer previous slide) 2) Compile your code To compile your C code, you will use a compiler like ‘gcc’ (GNU Compiler Collection) or ‘clang’ gcc –o hello hello.c 3) Run the Compiled Program Once the code is compiled, you can run the executable from the terminal:./hello Ensure gcc or clang is installed: sudo apt-get install gcc For Debian/Ubuntu-based distributions sudo apt-get install clang 18 Common ‘gcc’ Command-Line Arguments 1) ‘-g’ : Includes debugging information in the compiled code, which is essential for using debugging tools like 2) ‘-c’: Compiles the source file into an object file ‘.o’ without linking. This option is useful when you want to compile separately and link later. 3) ‘-wall’ : Enables all the standard warning messages that help identify potential issues in the code. This helps in catching possible errors early 4) ‘-wextra’ : Issues additional warning messages beyond those provided by ‘wall’. 5) ‘-pedantic’ : Enforces strict adherence to the C standard by issuing warnings for non-standard code and rejecting programs that use non-standard features. 6) ‘-ansi’ : Disables GCC-specific features not included in the standard C and enables some standard features that are normally disabled. This ensures compliance with the ANSI C standard. NOTE: You must include ‘ANSI’ in your code compilation for all your PRACTICAL assessments. 19 IMPORTANT INFORMATION NOTE: For all practical assessments, you must compile your code with the ‘ANSI’ option. Failure to do so will result in a loss of marks. Detailed guidelines will be provided in the practical rubrics 20 Running a C Code in a Linux Environment DEBUGGING Use ‘gdb’ (GNU Debugger) to debug your program if needed. gdb./hello Makefile For larger projects, consider using a ‘makefile’ to automate the build process. all: hello hello: hello.c gcc -o hello hello.c clean: rm hello Run ‘make’ to build your project and ‘make clean’ to remove the executable 21 Compilation Process PHASES of EXECUTING a C PROGRAM 1) Edit: Writing and modifying the source code in a text editor or IDE 2) Preprocess: The preprocessor handles directives (e.g., ‘#include’, ‘#define’) and produces an intermediate code for the compiler. 3) Compile: The compiler translates the preprocessed code into assembly language or machine code, generating an object file. 4) Link: The linker combines object files and libraries into a single executable file, resolving references between them. 5) Load: The loader loads the executable file into memory, preparing it for execution. 6) Execute: The CPU executes the instructions in the program, performing the specified tasks. 22 Pre-processor Does a straight-forward substitution/modification of your source code in preparation for the actual compilation Value definitions #define MAX_STUDENTS 500 Macros (object-like and function-like) #define MAX(a,b) ((a < b) ? (b) : (a)) Inclusions #include Conditional Compilations #ifdef DEBUG assertIndexIsValid( x, “x out of bounds” ); printf( “line number = “ + iRow ); #endif 23 Pre-processor Directives in C Prefix: All pre-processor directives start with “#” Purpose: These directives are handled before the actual compilation of the code begins Internal Process: After the pre-processing phase, directives are no longer present in the code that gets compiled. The pre-processor generates a new, temporary file with the processed code. Output Option: You can view the pre-processed output by using the ‘-E’ option with ‘gcc’. This option outputs the pre-processed code to the terminal or a file. gcc -E source.c -o preprocessed.c Command-Line Definitions: You can define macros directly in the command line gcc -o register register.c -D NUM_STUDENTS=500 This command is equivalent to #define NUM_STUDENTS 500 24 Compiler Purpose of the Compiler: Converts human-readable C code into machine-level instructions that the CPU can execute. Example Transformation: The line of C code: while (count > 0) { processItem(); count--; } The compiler translates this into assembler instructions, which might look like: cmp.l d0, d1 ; Compare count with 0 ble end_loop ; Branch to end_loop if count

Use Quizgecko on...
Browser
Browser