🎧 New: AI-Generated Podcasts Turn your study notes into engaging audio conversations. Learn more

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Document Details

LowCostCarolingianArt

Uploaded by LowCostCarolingianArt

Tags

C programming programming fundamentals computer science

Full Transcript

CS1050 Programming Fundamentals with C UNIT - I Introduction to Programming and C Language Basics Introduction to Programming, History and features of the C language, Structure of a C program, Compilation and Execution of a C program, Basic syntax: keywords, identifiers, constants, vari...

CS1050 Programming Fundamentals with C UNIT - I Introduction to Programming and C Language Basics Introduction to Programming, History and features of the C language, Structure of a C program, Compilation and Execution of a C program, Basic syntax: keywords, identifiers, constants, variables, and data types, Operators and expressions, Input and output functions: printf(), scanf(). Introduction to Programming A programming language is a set of instructions and syntax used to create software programs. Hierarchy of Computer language – Most Popular Programming Languages – C Python C++ Java SCALA C# R Ruby Go Swift JavaScript Characteristics of a programming Language – A programming language must be simple, easy to learn and use, have good readability, and be human recognizable. Abstraction is a must-have Characteristics for a programming language in which the ability to define the complex structure and then its degree of usability comes. A portable programming language is always preferred. Programming language’s efficiency must be high so that it can be easily converted into a machine code and its execution consumes little space in memory. A programming language should be well structured and documented so that it is suitable for application development. Necessary tools for the development, debugging, testing, maintenance of a program must be provided by a programming language. A programming language should provide a single environment known as Integrated Development Environment(IDE). A programming language must be consistent in terms of syntax and semantics. Basic Terminologies in Programming Languages: Algorithm: A step-by-step procedure for solving a problem or performing a task. Variable: A named storage location in memory that holds a value or data. Data Type: A classification that specifies what type of data a variable can hold, such as integer, string, or boolean. Function: A self-contained block of code that performs a specific task and can be called from other parts of the program. Function: A self-contained block of code that performs a specific task and can be called from other parts of the program. Control Flow: The order in which statements are executed in a program, including loops and conditional statements. Syntax: The set of rules that govern the structure and format of a programming language. Comment: A piece of text in a program that is ignored by the compiler or interpreter, used to add notes or explanations to the code. Debugging: The process of finding and fixing errors or bugs in a program. IDE: Integrated Development Environment, a software application that provides a comprehensive development environment for coding, debugging, and testing. Operator: A symbol or keyword that represents an action or operation to be performed on one or more values or variables, such as + (addition), – (subtraction), * (multiplication), and / (division). Statement: A single line or instruction in a program that performs a specific action or operation. Advantages of programming languages: 1. Increased Productivity: Programming languages provide a set of abstractions that allow developers to write code more quickly and efficiently. 2. Portability: Programs written in a high-level programming language can run on many different operating systems and platforms. 3. Readability: Well-designed programming languages can make code more readable and easier to understand for both the original author and other developers. 4. Large Community: Many programming languages have large communities of users and developers, which can provide support, libraries, and tools. Disadvantages of programming languages: 1. Complexity: Some programming languages can be complex and difficult to learn, especially for beginners. 2. Performance: Programs written in high-level programming languages can run slower than programs written in lower-level languages. 3. Limited Functionality: Some programming languages may not have built-in support for certain types of tasks or may require additional libraries to perform certain functions. 4. Fragmentation: There are many different programming languages, which can lead to fragmentation and make it difficult to share code and collaborate with other developers. Introduction to C Programming The C Language is developed by Dennis Ritchie for creating system applications that directly interact with the hardware devices such as drivers, kernels, etc. It can be defined by the following ways: 1. Mother language 2. System programming language 3. Procedure-oriented programming language 4. Structured programming language 5. Mid-level programming language History of C C programming language was developed in 1972 by Dennis Ritchie at bell laboratories of AT&T (American Telephone & Telegraph), located in the U.S.A. Dennis Ritchie is known as the founder of the c language. It was developed to overcome the problems of previous languages such as B, BCPL, etc. C language was developed to be used in UNIX operating system. Language Year Developed By Algol 1960 International Group BCPL 1967 Martin Richard B 1970 Ken Thompson Traditional C 1972 Dennis Ritchie K&RC 1978 Kernighan & Dennis Ritchie ANSI C 1989 ANSI Committee ANSI/ISO C 1990 ISO Committee C99 1999 Standardization Committee Features of C IDEs for C/C++ IDEs for C/C++ developers in 2024: Code::Blocks Visual Studio CLion NetBeans Eclipse CodeLite QtCreator provide a robust set of tools that enhance productivity and capabilities in software development. Introduction Heading to Programming 1 C Program Structure Program defined by: ○ global declarations ○ function definitions May contain preprocessor directives Always has one function named main, may contain others Introduction Heading to Programming 1 Parts of a Program Introduction to Programming Preprocessor Directives Begin with # Instruct compiler to perform some transformation to file before compiling Example: #include ○ add the header file stdio.h to this file ○.h for header file ○ stdio.h defines useful input/output functions Introduction to Programming Declarations Global ○ visible throughout program ○ describes data used throughout program Local ○ visible within function ○ describes data used only in function Introduction to Programming Functions Consists of header and body ○ header: int main () ○ body: contained between { and } starts with location declarations followed by series of statements More than one function may be defined Functions are called (invoked) - more later Introduction to Programming Main Function Every program has one function main Header for main: int main () Program is the sequence of statements between the { } following main Statements are executed one at a time from the one immediately following to main to the one before the } Introduction to Programming Comments Text between Used to “document” the code for the human reader Ignored by compiler (not part of program) Have to be careful ○ comments may cover multiple lines ○ ends as soon as */ encountered (so no internal comments - comment */) Introduction to Programming Comment Example #include int main () { printf(“Too many comments\n”); } Introduction to Programming Documentation Global - start of program, outlines overall solution, may include structure chart Module - when using separate files, indication of what each file solves Function - inputs, return values, and logic used in defining function Add documentation for key (tough to understand) comments Names of variables - should be chosen to be meaningful, make program readable Introduction to Programming Syntax of C Rules that define C language ○ Specify which tokens are valid ○ Also indicate the expected order of tokens Some types of tokens: ○ reserved words: include printf int... ○ identifiers: x y... ○ literal constants: 5 ‘a’ 5.0... ○ punctuation: { } ; < > # Introduction to Programming Identifier Names used for objects in C Rules for identifiers in C: ○ first char alphabetic [a-z,A-Z] or underscore (_) ○ has only alphabetic, digit, underscore chars ○ first 31 characters are significant ○ cannot duplicate a reserved word ○ case (upper/lower) matters Introduction to Programming Reserved Words Identifiers that already have meaning in C Examples: ○ include, main, printf, scanf, if, else, … ○ more as we cover C language Introduction to Programming Valid/Invalid Identifiers Valid Invalid sum 7of9 c4_5 x-name A_NUMBER name with spaces longnamewithmanychars 1234a TRUE int _split_name AXYZ& Introduction to Programming Program Execution Global declarations set up Function main executed ○ local declarations set up ○ each statement in statement section executed executed in order (first to last) changes made by one statement affect later statements Introduction to Programming Variables Named memory location Variables declared in global or local declaration sections Syntax: Type Name; Examples: int sum; float avg; char dummy; Introduction to Programming Variable Type Indicates how much memory to set aside for the variable Also determines how that space will be interpreted Basic types: char, int, float ○ specify amount of space (bytes) to set aside ○ what can be stored in that space ○ what operations can be performed on those vars Introduction to Programming Variable Name Legal identifier Not a reserved word Must be unique: ○ not used before ○ variable names in functions (local declarations) considered to be qualified by function name ○ variable x in function main is different from x in function f1 Introduction to Programming Multiple Variable Declarations Can create multiple variables of the same type in one statement: int x, y, z; is a shorthand for int x; int y; int z; - stylistically, the latter is often preferable Introduction to Programming Variable Initialization Giving a variable an initial value Variables not necessarily initialized when declared (value is unpredictable - garbage) Can initialize in declaration: Syntax: Type Name = Value; Example: int x = 0; Introduction to Programming Initialization Values Literal constant (token representing a value, like 5 representing the integer 5) An expression (operation that calculates a value) Function call The value, however specified, must be of the correct type Introduction to Programming Multiple Declaration Initialization Can provide one value for variables initialized in one statement: int x, y, z = 0; Each variable declared and then initialized with the value Introduction to Programming Type Set of possible values ○ defines size, how values stored, interpreted Operations that can be performed on those possible values Data types are associated with objects in C (variables, functions, etc.) Introduction to Programming Standard Types Atomic types (cannot be broken down) ○ void ○ char ○ int ○ float, double Derived types ○ composed of other types Introduction to Programming Literal Constants Sequences of characters (tokens) that correspond to values from that type -35 is the integer -35 3.14159 is the floating pointer number 3.14159 ‘A’ is the character A Can be used to initialize variables Introduction to Programming Void Type Type name: void Possible values: none Operations: none Useful as a placeholder Introduction to Programming Integer Type Type name: ○ int ○ short int ○ long int Possible values: whole numbers (within given ranges) as in 5, -35, 401 Operations: arithmetic (addition, subtraction, multiplication, …), and others Introduction to Programming Integer Types/Values Introduction to Programming Why Limited? With a fixed number of bits, only a certain number of possible patterns 16 bits, 65,536 possible patterns ○ 32768 negative numbers ○ 1 zero ○ 32767 positive numbers Overflow: attempt to store a value to large in a variable (40000 in short int) Introduction to Programming Integers: Two’s Complement positive number: 0, number in binary 97 in binary 1*64 + 1*32 + 1*1 (1100001) pad with leading zeroes (0 000000001100001) - 16 bits zero: 0, all zeroes negative number: 1, (inverse of number + 1) -97 (1, 111111110011110 + 1) 1 111111110011111 Introduction to Programming Unsigned Integers Type: unsigned int No negative values unsigned int: ○ possible values: 0 to 65536 Representation: binary number Introduction to Programming Integer Literal Constants Syntax: 1 or more digits Optional leading sign (+ or -) Optional l or L at the end for long Optional u or U for unsigned Examples: 5, -35, 401, 4010L, -350L,2000UL Introduction to Programming Integer Literal Constants For example "2000UL" is used in programming, particularly in languages like C, to represent the number 2000 as an unsigned long integer. 2000: The numerical value. U: Indicates that the number is of type "unsigned," meaning it can only represent non-negative numbers. L: Indicates that the number is of type "long," which typically means it has a larger range than a standard integer. So, "2000UL" represents the unsigned long integer value of 2000. Introduction to Programming Floating-Point Type Type names: ○ float ○ double ○ long double Possible values: floating point numbers, 5.0 -3.5, 4.01 Operations: arithmetic (addition, subtraction, multiplication, …), and others Introduction to Programming Floating-Point Representation float: 4 bytes, 32 bits double: 8 bytes, 64 bits long double: 10 bytes, 80 bits Representation: ○ magnitude (some number of bits) plus exponent (remainder of bits) ○ 3.26 * 10^4 for 32600.0 Introduction to Programming Floating-Point Limitations Maximum, minimum exponents ○ maximum possible value (largest positive magnitude, largest positive exponent) ○ minimum value (largest negative magnitude, largest positive exponent) ○ can have overflow, and underflow Magnitude limited ○ cannot differentiate between values such as 1.00000000 and 1.00000001 Introduction to Programming Floating-Point Literals Syntax: ○ Zero or more digits, decimal point, then zero or more digits (at least one digit) ○ Whole numbers also treated as float ○ Optional sign at start ○ Can be followed by e and whole number (to represent exponent) ○ f or F at end for float ○ l or L at end for long double Examples: 5,.5, 0.5, -1.0, 2.1e+3, 5.1f Introduction to Programming Character Type Type name: char Possible values: keys that can be typed at the keyboard Representation: each character assigned a value (ASCII values), 8 bits ○ A - binary number 65 ○ a - binary number 97 ○ b - binary number 98 ○ 2 - binary number 50 Introduction to Programming Character Literals Single key stroke between quote char ‘ Examples: ‘A’, ‘a’, ‘b’, ‘1’, ‘@’ Some special chars: ○ ‘\0’ - null char ○ ‘\t’ - tab char ○ ‘\n’ - newline char ○ ‘\’’ - single quote char ○ ‘\\’ - backslash char Introduction to Programming String Literals No string type (more later) Contained between double quote chars (“) Examples: “” - null string “A string” “String with newline \n char in it” “String with a double quote \” in it” Introduction to Programming Constants Literal constants - tokens representing values from type Defined constants ○ syntax: #define Name Value ○ preprocessor command, Name replaced by Value in program ○ example: #define MAX_NUMBER 100 Introduction to Programming Constants (cont) Memory constants ○ declared similar to variables, type and name ○ const added before declaration ○ Example: const float PI = 3.14159; ○ Can be used as a variable, but one that cannot be changed ○ Since the value cannot be changed, it must be initialized Introduction to Programming Formatted Input/Output Input comes from files Output sent to files Other objects treated like files: ○ keyboard - standard input file (stdin) ○ monitor - standard output file (stdout) Generally send/retrieve characters to/from files Introduction to Programming Formatted Output Command: printf - print formatted Syntax: printf(Format String, Data List); ○ Format string any legal string ○ Characters sent (in order) to screen Ex.: printf(“Welcome to\nCS 1621!\n”); causes Welcome to CS 1621! to appear on monitor Introduction to Programming Formatted Output (cont) Successive printf commands cause output to be added to previous output Ex. printf(“Hi, how “); printf(“is it going\nin 1621?”); prints Hi, how is it going in 1621? To the monitor Introduction to Programming Field Specifications Format string may contain one or more field specifications ○ Syntax: %[Flag][Width][Prec][Size]Code ○ Codes: c - data printed as character d - data printed as integer f - data printed as floating-point value ○ For each field specification, have one data value after format string, separated by commas Introduction to Programming Field Specification Example printf(“%c %d %f\n”,’A’,35,4.5); produces A 35 4.50000 (varies on different computers) Can have variables in place of literal constants (value of variable printed) Introduction to Programming Width and Precision When printing numbers, generally use width/precision to determine format ○ Width: how many character spaces to use in printing the field (minimum, if more needed, more used) ○ Precision: for floating point numbers, how many characters appear after the decimal point, width counts decimal point, number of digits after decimal, remainder before decimal Introduction to Programming Width/Precision Example printf(“%5d%8.3f\n”,753,4.1678); produces 753 4.168 values are right justified If not enough characters in width, minimum number used use 1 width to indicate minimum number of chars should be used Introduction to Programming Left Justification (Flags) Put - after % to indicate value is left justified printf(“%-5d%-8.3fX\n”,753,4.1678); produces 753 4.168 X For integers, put 0 after % to indicate should pad with 0’s printf(“%05d”,753); produces 00753 Introduction to Programming Size Indicator Use hd for small integers Use ld for long integers Use Lf for long double Determines how value is treated Introduction to Programming Printf Notes Important to have one value for each field specification ○ some C versions allow you to give too few values (garbage values are formatted and printed) Values converted to proper type ○ printf(“%c”,97); produces the character a on the screen Introduction to Programming Formatted Input Command: scanf - scan formatted Syntax: scanf(Format String, Address List); ○ Format string a string with one or more field specifications ○ Characters read from keyboard, stored in variables scanf(“%c %d %f”,&cVar,&dVar,&fVar); attempts to read first a single character, then a whole number, then a floating point number from the keyboard Introduction to Programming Formatted Input (cont) More notes ○ can use width in field specifications to indicate max number of characters to read for number ○ computer will not read input until return typed ○ if not enough input on this line, next line read, (and line after, etc.) ○ inappropriate chars result in run-time errors (x when number expected) ○ if end-of-file occurs while variable being read, an error occurs Introduction to Programming Address Operator & - address operator Put before a variable (as in &x) Tells the computer to store the value read at the location of the variable More on address operators later Introduction to Programming Scanf Rules Conversion process continues until end of file reached maximum number of characters processed non-number char found number processed an error is detected (inappropriate char) Field specification for each variable Variable address for each field spec. Any character other than whitespace must be matched exactly Introduction to Programming Scanf Example scanf(“%d%c %f”,&x,&c,&y); and following typed: -543A 4.056 56 -543 stored in x, A stored in c, 4.056 stored in y, space and 56 still waiting (for next scanf) Introduction to Programming Prompting for Input Using output statements to inform the user what information is needed: printf(“Enter an integer: “); scanf(“%d”,&intToRead); Output statement provides a cue to the user: Enter an integer: user types here

Use Quizgecko on...
Browser
Browser