Download presentation
Presentation is loading. Please wait.
1
Programming in C An Overview
2
C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language for The UNIX operating system. Why ‘C’ 1. C is a SMALL Language. Small is beautiful in programming. Fewer key words but powerful. C is the Standard Developmental Language for personal computers. Much of : MS-DOS & OS/2 Many windowing packages, Data Base PGMS, Graphic Libraries & other Large Application Packages are written in ‘C’
3
3. ‘C’ is Portable - easily moved from machine to machine.
Provides a standard library of functions that work the same on all machines. Built in Preprocessor - helps isolate any system dependent code. 4. ‘C’ is Terse - very powerful set of operators. Can accomplish in 1 statement what might require many statements in another language. A Terse language explicitly magnifies the underlying productivity of the programmers. 5. ‘C’ is Modular - Supports Structured Programming. Functions - Internal – External. Supports user - Defined Libraries of Functions. Supports Privacy by using “Static” storage Class within files.
4
Lexical Elements of the C Language
C Program is viewed as a sequence of Tokens separated by White Space (i.e., spaces, tabs, new lines). These tokens include: Keywords. Identifiers. Constants. String constants. Operators. Punctuators.
5
Keywords Reserved words.
Cannot be redefined or used in other contexts. Case sensitive. Have a special predefined meaning. See pg E.g, for, while, if, void
6
p.46 Keywords auto do goto signed unsigned break double if sizeof void
case else int static volatile char enum long struct while const extern register switch continue float return typedef default for short union
7
Identifiers The names of variables, functions, labels and other user-defined items are called identifiers. May be any length. ANSI C – First 31 characters are recognized. Cannot be the same as a keyword and should not have the same name as pre-defined C functions. Case sensitive. E.g., count, Count and COUNT are three separate identifiers.
8
Identifiers should be chosen to reflect their use in the program.
The first character must be a letter or an underscore, and subsequent characters must be either letters, digits or underscores. Correct Incorrect Count1 1count test23 hi!there high_balance high . . . Balance Identifiers should be chosen to reflect their use in the program.
9
Constants They refer to fixed values that the program may not alter.
They can be of any of the basic data types. Integer: 1. Decimal 2. Octal (Base 8) Digits 3. Hexadecimal (Base 16) Digits …9, A…F
10
Character: Any single printable character in single
Floating Point: Need a decimal pt or Scientific notation. 23.7 .16 1.604 2e3 Character: Any single printable character in single quotes. ‘?’, ‘A’, ‘9’…..
11
String Constant H e l l o ! \0
A character, or more likely a sequence of characters, enclosed in “double quotes”. A string is an array of characters. “A” and ‘A’ are not the same. ‘A’ is a string containing only one letter. “A” is actually A followed by the null character ‘\0’. H e l l o ! \0
12
EXAMPLES “a string of text” “” // the null string “ ” // a string of a blank character “ a = b + c; ” // nothing is executed
13
Operators: Arithmetic + Addition - Subtraction * Multiplication
/ Division [int/int yields int] ½=0; 7/2=3; 18/4=4; 29/5=5; % Modulus operator [integer remainder] 5 % 3= 2; 7 % 4= 3; 2 % 6= 2; 19 / 4 = 5;
14
Relational operators:
> , >= , < , <= , = = , != hours > 40, ans = =‘y’ Logical operators: && , || , ! ( Hours > 40 ) && (Union = = ‘Y’) Both allow us to create Boolean expressions which we can use to control program code execution.
15
Sometimes the meaning of the operator must be determined by its context.
a) scanf (“% d”, variable); b) x = y % z; a) % a conversion character b) % a modulus operator
16
Punctuators They are located by the compiler as tokens and are used to separate language elements. Parentheses ( ) Braces { } Commas , Semicolons ; int main(void) { int a, b=3, c=6; a = 17 * (b + c); … }
17
Terms Source code Object code Linker Text of a program.
The input to the C compiler. Object code Translation of the source code of a program into machine code. The input to the linker. Linker A program that links separately compiled modules into one program. The output is an executable program.
18
Library Compile time Run time
The file containing the standard functions that a program can use. Compile time The time during which a program is being compiled. Run time The time during which a program is executing.
19
Compilation A compiler translates source code into machine code.
One high-level instruction can correspond to several machine instructions. Ex: x = (y + 3) / z; Must generate machine code for flow-of-control syntax such as: while, repeat, if-then-else, case, …
20
The compiler must be able to generate machine code to execute subroutines. This would include the ability to: Copy input parameter values . Save return address. Start executing at beginning of procedure code. Copy output parameter values at end of procedure. Set PC to return address.
21
Ex: total=sum + 55.32; contains six tokens.
Lexical analysis: Break up strings of characters into logical components, called tokens, and discard comments, spaces, etc. Ex: total=sum ; contains six tokens. total, =, sum, +, 55.32, ” ;” Parsing: Decide how tokens are related. Ex: sum is an arithmetic expression, and total= sum is an assignment statement. Code generation: Generate machine instructions for each high-level instruction. Important to optimize the code.
22
X = Y+Z; 2. W = X+Z; After line 1, X and Z are already in registers, so don’t load the registers for line 2. The resulting machine language program,called object code, is written to disk.
23
Linking and Loading The Object program produced by the translation process, although in machine code, is rarely in a form that can be executed directly by the machine. One reason is that programming environments allow the modules of a program to be developed and translated as individual units at different times. This supports the modular construction of software and reusability of code.
24
Thus an object program is actually a machine-language program containing several loose ends:
a) Calls to functions in other compilation units. b) Calls to functions in system or user-created libraries.
25
In the past, the task of making these connections was performed by a program called the Linker.
Its job was to link several object programs, operating system routines, and other utility software to produce a complete, executable program(load module) that was stored in the machine’s mass storage system. Today the linking process is usually disguised as a part of the translation process, or delayed until a request is made to execute the program.
26
Library and Linking Linker: combines the result of compiling different pieces of the program separately. If pieces refer to each other, these references cannot be resolved during independent compilation. procedure p main Refers to x Declares x Invokes p
27
int count; #include <stdio
int count; #include <stdio.h> void display(void); extern int count; int main(void) void display(void) { { count = 10; printf(“%d”, count); display(); } return 0; } 2 Separate Files
28
C’s Memory Map Stack Heap Global variables Program code
Conceptualized memory map of a C program. Return address of function calls; Arguments to functions; Local variables; Current state of the CPU. Stack Heap Global variables Program code
29
Conceptually, memory is divided into program memory and data memory.
Program memory consists of the memory used for Main and all called functions. Data memory consists of: a) Permanent definitions such as global data and constants. b) Local definitions. c) Dynamic memory. Exactly how “C” handles these different needs is a function of the operating system and the compiler writer’s skills.
30
Conceptual View of Memory
Main Called Funcs. Func. Program Memory global heap run time stack Data Memory
31
A Hello World Program /*The traditional first program in honor of Dennis Ritchie who invented C at Bell Labs in 1972.*/ #include <stdio.h> Hello,world! int main(void) //main function { printf(“Hello, world!\n”); return 0; }
32
Format of a Function: Preprocessor Directives //Here we include any libraries int main () { Declarations ; //Here we list any data variable declarations. Body of Function //Here is the source program version of the algorithm. }
33
Main Function: Program will have 1 main function where execution Begins & Ends.
Pre-Defined Functions: Already Exist - Part of the language. The Programmer uses them to do predefined Activities – (e.g., input/output, scanf, printf). User-Defined Functions: Functions written by the programmer. Created to do specific task(s). e.g. - Given Hours worked & payrate; Calculate Employee salary.
34
Preprocessing Directives
Before compilation takes place the preprocessor modifies the source code that is input to the compiler via executing pre-processor directives. e.g., includes files #include define constants - #define All preprocessor directives begin with a # sign. Each preprocessing directive must be on its own line. #include <stdio.h> #include <stdlib.h> //wrong
35
#include General Syntax: #include <filename>
e.g. #include <stdio.h> The preprocessor looks to include header file from the standard library. #include “filename” e.g. #include “utility.h” The preprocessor looks to include the header file from the library that holds the source code. Either format can contain a fully qualified name that directs the search(#include “K:\PROJECT\HEADER.h”)
36
#define General Syntax: e.g. #define PI The preprocessor changes all occurrence of the identifier PI to 3.14. e.g. printf(“PI = %f\n”, PI) printf(“PI = %f\n”, 3.14) PI is called a symbolic constant. By convention, a symbolic constant is written in capital letters.
37
xyz #define ONE 1 #define TWO ONE+ONE
#define E_MS "standard error on input\n" printf(E_MS); standard error on input #define XYZ “this is a test” printf("XYZ"); xyz #define LONG_STRING "this is a very long \ string that is used as an example"
38
# define can be placed anywhere in your source code.
usually place at the beginning of your source code before main( ) function. where you place them determines their SCOPE. SCOPE: The segment of code that “knows about” the existence of the symbolic constants and/or macros you have created. e.g., If place at the beginning of your source file, then the SCOPE is the entire file.
39
Functional Prototype:
Header Files: Are joined with your source code by the Preprocessing Directive #. Why?- often reason is that they contain the FUNCTIONAL PROTOTYPES (FP’s) of functions that the program wishes to call. - If the FP’s are not available then the program can’t call (use) those functions. Functional Prototype: The “Heading” of the function. Contains the Name of the function. Return Type of the Function. Number & type of values that may be passed to the function (Parameter or Argument). The Compiler needs the FP’s of invoked functions to perform its job.
40
Comments Multi-Line comments: /* this is a multiline comment */
May be placed anywhere in a program, as long as they do not appear in the middle of a keyword or identifier. May not be nested. /* this is a multiline comment */ x = /* add the numbers */5; //correct swi/*this will not work*/tch(c) { . . .}; //wrong /* this is an outer comment x = y/a; /* this is an inner comment - and causes an error */ */ //wrong
41
Single-Line Comments:
A single-line comment can be nested within a multi-line comment. All but the most obvious functions should have a comment at the top that states what the function does, how it is called, and what it returns. // this is a single-line comment /* this is a // test of nested comments. */
42
A Depth Program #include <stdio.h> int main(void) {
int inches, feet, fathoms; //declarations fathoms = 7; feet = 6 * fathoms; inches = 12 * feet; printf(“Wreck of the Hesperus:\n”); printf(“Its depth at sea in different units:\n”); printf(“ %d fathoms\n”, fathoms); printf(“ %d feet\n”, feet); printf(“ %d inches\n”, inches); } Wreck of the Hesperus: Its depth at sea in different units: 7 fathoms 42 feet 504 inches
43
Declarations A variable is declared to be of a type. This enables the compiler to: Set aside the appropriate amount of memory to hold the variable. Determines what operations are permissible with that variable. What sort of data is allowed to be stored in that variable. All variables must be declared before they are assigned values and used in statements. Declaration end with a semicolon.
44
Assignment Variable = constant;
Allows the work and processing of data to achieved. variable; Variable = constant; function call; expression [contains any/all of above joined by operators]; Multiple assignments. Right to Left Association: 1. C = 0; A = B = C = 0; 2. B = (C = 0); 3. A = (B = (C = 0));
45
Compound Assignments General Form:
Variable += Exp; Variable = Variable + Exp; Variable -= Exp; Variable = Variable – Exp; Variable *= Exp ; Variable = Variable * Exp; Variable /= Exp ; Variable = Variable * Exp; Variable %= Exp; Variable = Variable % Exp; x +=10; x = x +10; x -=100; x = x - 100;
46
Data Types: Preliminary info: see more in Chap. 6.
Variables - Locations in memory we create which can hold data. Variables have a specific type. Type defines what sort of data is allowed to be stored in the variable. Integer Types: int, short int, long int Real Types: float, double, long double Text Types: Char 1 keystroke (1 symbol) String multiple characters
47
Initialization When variables are declared, they may also be initialized. Typically, constants or constant expressions are used to initialize a variable. General Syntax: type var-name = constant; A) Integer Constant: e.g., int x = 100; B) Real: double 1.63F float 1.63L long double e.g. double x = 1.63;
48
C) Char : Single symbol in single quotes.
e.g Char Letter = ‘A’: D) String: Multiple symbols in double quotes. e.g Char name[15] = “Mary”;
49
Input Predefined Functions
scanf (“format string”, Arguments); Interactive Input: get data from user entering via keyboard. fscanf (f, “format string”, Arguments); File Input: get data that is stored in file F. sscanf (s, “format string”, Arguments); String Input: get data from string S. Return value: If error occurs, return value is EOF (usually -1), Otherwise returns the number of successful assignments of data to the arguments. Input Predefined Functions
50
Unsuccessful Input: EOF (End of File) is reached before ALL arguments have been assigned data, if so the value EOF (-1) is returned. Data Mismatch: The input data does not match the control string specifications. (e.g., indicated data would be integer and the data actually entered was REAL).
51
scanf- Interactive Input
User enters data with keyboard when program interrupt occurs. Input data treated as an input stream of characters. Arguments are addresses. “&” is the Address Operator. scanf(“%d”, &x);
52
#include <stdio.h>
int main(void) { char str[80]; printf("Enter a string: "); scanf(''%s", str); printf("Here's your string: %s", str); return 0; Why no “&” ? }
53
Output Predefined Functions
printf (“control string”, Arguments); Writes to terminal. fprintf (f, “control string”, Arguments); Writes to another file. sprintf (s, “control string”, Arguments); Writes to string s. Return Value: If EOF occurs, return value is - 1, otherwise returns the number of successful assignments of data to the arguments.
54
Format Strings 2) Contain Text: int Sum = 500;
1) Contain Conversion Specification Characters. e.g., d - decimal data c - character f - floating point s - string printf("I like %c %s", 'C', "very much!"); 2) Contain Text: int Sum = 500; printf (“The Sum is %d”, Sum); 3) Contain Control Characters: NEW LINE - printf (“hello, \n world”); Tab printf (“hello, \t world \n”) The Sum is 500
55
ASIDE: scanf float use %f
double use %lf printf float or use %f double
56
Field Width Specification
printf (“more numbers: %7.1f %7.2f %7.3f ”, 4.0, 5.0, 6.0); Field width. Precision # of columns output # of decimal digits to including dec. pt right of decimal pt. more numbers:_ _ _ _ 4.0 _ _ _ 5.00 _ _ 6.000
57
Character Data: printf (“%c %5c /n %4c”, ‘x’, ‘y’, ‘z’); x_ _ _ _ y _ _ _z
58
Looping - Iteration for While Do-while while (scanf(“%d”, &x)==1) {
Categories: Conditional Loops: Counting Loop : While Statement: while (Expression) { Body of Loop } for while (scanf(“%d”, &x)==1) { printf(“%d”, x); }
59
How Terminate Loop? Dummy Data Logic: End-of-file Logic:
User enter a value that can’t be successfully converted. End-of-file Logic: Indicate all data has been entered by typing EOF signal. UNIX ctrl + d MS DOS ctrl + z break - Exit from Loop immediately. continue - Jump to Bottom of Loop(stops just that single iteration).
60
Operator Precedence ( ) [ ] -> . ++ (postfix) - - (postfix)
! ~ sizeof (type) + (unary) - (unary) ++ (prefix) -- (prefix) & (address) * (indirection) * / % << >> < <= > >= == != &
61
= += -= *= /= >>= <<= &= ^= |=
Operator Precedence ^ | && || ?: = += -= *= /= >>= <<= &= ^= |= , (comma operator)
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.