Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
15 views

2_Overview of C Programming Language

Uploaded by

santasnowyy
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

2_Overview of C Programming Language

Uploaded by

santasnowyy
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 35

Overview of C

School of Computing and Informatics


Computer Science Department
Prepared by Dr. Mohammad Yahia
Outlines
 C Language Elements
 Variable Declarations and Data Types
 Executable and Assignment Statements
 Input/Output Operations (scanf / printf)
 Comments
 Arithmetic Expressions
C program Elements
C program Elements
 Preprocessor Directives
 Preprocessor directives are commands that give instructions to the C preprocessor.
 Preprocessor is a system program that modifies a C program prior to its compilation.
 Preprocessor directives begins with a #
 Example: #include or #define
 #include
 The #include directive gives a program access to a library.
 Libraries are useful functions that are predefined by the C language (standard
libraries).
 Example: You must include stdio.h if you want to use the printf and scanf
functions.
 How to include a library in your program: #include<stdio.h>
 #define
 The #define directive instructs the preprocessor to replace each occurrence of a text
by a particular constant value before compilation.
C program Elements
 main() function
 The heading int main() marks the beginning of the main function where program
execution begins.
 Every C program has a main function.
 Curly braces { and } mark the beginning and end of the body of function main.
 A function body has two parts:
 Declarations: tell the compiler what memory cells are needed in the function
 Executable statements: are translated into machine language and later
executed by the compiler.
 Reserved words
 These are words that C reserves for its own uses. For example, you couldn’t have a
variable named return
 Always lower case
 Examples: int, double, char, if, else, return, while, default, do, for,
continue, void, float, long, switch, short, const, …
C program Elements
 Standard Identifiers
 Identifier: A name given to a variable or a function
 Standard Identifier: An identifier that is defined in the standard C libraries
(e.g.: printf, scanf)
 User Defined Identifiers (Variables and Functions)
 We choose our own identifiers to name memory cells that will hold data.
 Rules for Naming Identifiers:
 An identifier must consist only of letters, digits, and underscores.
 An identifier cannot begin with a digit.
A C reserved word cannot be used as an identifier.
A standard identifier should not be redefined.
 Valid identifiers: letter1, inches, KM_PER_MILE
 Invalid identifiers: 1letter, Happy*trout, return
Few Guidelines for Naming Identifiers
 Uppercase and lowercase are different (C is a case-sensitive language)
 LETTER ≠ Letter ≠ letter
 Avoid names that only differ by case; they can lead to problems to find bugs
 Choose meaningful identifiers that are easy to understand.
 Example: distance = rate * time means a lot more than x=y*z
 All uppercase is usually used for constants (#define)
 KMS_PER_MILE is a defined constant
 As a variable, we would probably name it KmsPerMile or Kms_Per_Mile
Variables Declarations
 Variable: The memory cell used for storing a program’s data and its computational
results
 In C, variable’s value can change
 Example: miles, kms
 Variable declarations: Statements that communicate to the compiler the names of
variables in the program and the kind of information they can store
 Example: double miles
 Tellsthe compiler to create space for a variable of type double in memory
with the name miles
 C requires you to declare every variable used in the program
 Declarations should be in the body of the program
Data Types
 Data Types: a set of values and a set of operations that can be performed on
those values
 int: Stores integer values – whole numbers (e.g. 65, -12345)
 float: Stores real numbers – numbers that use a decimal point. (e.g. 3.14159
or 1.23e5 which equals 123000.0)
 double: Stores real numbers – numbers that use a decimal point. (e.g. 3.14159
or 1.23e5 which equals 123000.0)
 char: An individual character value.
 Each char value is enclosed in single quotes. (e.g. ‘A’, ‘*’)
 Can be a letter, a digit, or a special symbol
 Arithmetic operations (+, -, *, /) and compare can be performed in case of int
and double.
 Compare can be performed in char data
Data Types
 The following table shows the basic data types in C:
Data Type C Keyword Bytes Range
Character char 1 -27 to 27 – 1
Integer int 4 -231 to 231 – 1
Floating Point float 4 1.175494e-38 to 3.402823
e38
Double precision floating point double 8 2.225074e-308 to
1.797693e+308
Declaring Variables in C
 Declare a suitable variables for the following data:
Data Data type C syntax
salary float float salary;
Number of children int int number_Of_Children;
Age float float age;
Weight double double Weight;
Name initial char char init_Name;
Mobile number int int mobileNumber;
Light speed double double lightSpeed;

 You may write the variables of the same datatype in one line:
 int mobileNumber, number_Of_Children;
 float salary, age;
 double lightSpeed, Weight;
Executable Statements
 Executable Statements: C statements used to write or code the algorithm
 C compiler translates the executable statements to machine code
 Assignment Statements
 Input/Output Operations and Functions (printf, scanf )
 return Statement

Figure 2.3 Memory(a) Before


and (b) After Execution of a
Program
Assignment Statements
 Assignment statement: Stores a value or a computational result in a variable

kms = KMS_PER_MILE * miles;

 The assignment statement above assigns a value to the variable kms. The value
assigned is the result of the multiplication of the constant KMS_PER_MILE by the
variable miles.
More on Assignments
 In C, the symbol = is the assignment operator
 Read it as “becomes”, “gets”, or “takes the
value of” rather than “equals” because it is
not equivalent to the equal sign of
mathematics.
 In C, == tests equality. (We will study it
later)
 In C you can write assignment statements of
the form:
sum = sum + item;
where the variable sum appears on both sides
of the assignment operator.
 This is obviously not an algebraic equation, but
it illustrates a common programming practice.
This statement instructs the computer to add
the current value of sum to the value of item;
the result is then stored back into sum.
Input/Output Operations
 Input operation: data transfer from the outside world into computer memory
 Output operation: program results can be displayed to the program user
 Input/output functions: special program units that do all input/output
operations
 output function: printf
 input function: scanf
 Function call:
 In C, a function call is used to call or activate a function
 Calling a function means asking another piece of code to do some work for you
Output Function: printf
 The printf function may display string and values of the expressions and
variables in the print list in the same order from left-to-right
 String are given between two double quotations
 Syntax:
 printf(“formatted
string”)
 printf(“formatted string”, print list)
Placeholders
 Placeholder always begins with the symbol %
 It marks the place in a format string where a value will be printed out or
will be inputted
 Format strings can have multiple placeholders, if you are printing
multiple values
Placeholder Variable Type Function Use
%c char printf/scanf
%d int printf/scanf
%f float / double Printf
%lf double Scanf
Placeholders for char type
 Characters are actually represented in C as integer values.
 Each character is represented by its ASCII code (e.g A = 65. B = 66, etc).
 The table after the program below shows the printable ASCII characters and their
corresponding ASCII codes.
 Printing a char variable using “%c” will print the character but printing it with “%d”
will print the ASCII code.
 Similarly, printing an integer variable with “%c” will also print the character
provided the value is within the range of character values.
 The following example demonstrates this:
Escape Sequence
 The backslash \ is called an escape character.
 Indicates that printf is supposed to do something unusual
 When encountering a backslash, printf looks to the next character and combines
it with the backslash to form an escape sequence.

Escape sequence Action Function Use


\n Starts new line printf
\t tab printf

 Examples:
 printf(“This is one line\n“);
 printf(“and\nthis\tis\tanother\n“);
 Important: When input data is needed in an interactive program, it is better to
use the printf function to prompt a message that tells the user what data to enter
 printf(“Enter the distance in miles: “);
Escape Sequence Example
Output Formatting
 Integer Formatting
 You can specify how printf will display numeric integer values as follows:

%#d
 Where # is a number that represents the field width and it is optional
 If # is less than the integer size, it will be ignored
 If # is greater than the integer size, extra spaces will be added on the left
Value Format Displayed Value Format Displayed
output output
234 %4d ░234 -234 %4d -234
234 %5d ░░234 -234 %5d ░-234
234 %6d ░░░234 -234 %6d ░░-234
234 %1d 234 -234 %2d -234
The symbol ░ represents one blank space
Output Formatting
 float and double Formatting
 You can specify how printf will display real numbers (float and double) as
follows:
%n.mf
 n is a field width (optional):
 it is equal to the number of digits in the whole number, the decimal point,
and fraction digits
 If n is less than what the real number needs it will be ignored
 m: Number of decimal places (optional)
Value Format Displayed output Value Format Displayed output
3.14159 %5.2f ░3.14 3.14159 %4.2f 3.14
3.14159 %3.2f 3.14 3.14159 %5.1f ░░3.1
3.14159 %5.3f 3.142 3.14159 %8.5f ░3.14159
.1234 %4.2f 0.12 -.006 %4.2f -0.01
-.006 %8.3f ░░-0.006 -.006 %8.5f -0.00600
-.006 %.3f -0.006 -3.14159 %.4f -3.1416
Input Function: scanf
 The scanf function copies into memory data entered during the program execution
 The order of the placeholders must correspond to the order of the variables in the input list
 The data must be entered in the same order in the input list
 You should insert one or more blank characters or carriage returns between numeric items.
 Syntax:
scanf(“placeholders”, input list addresses)
 In the following figure:

 When user inputs a value, it is stored in variable


miles
 The placeholder type tells the function what kind of
data to store into variable miles
 The & (Ampersand) is the C address of operator. The &
operator in front of variable miles tells the scanf
function the location of variable miles in memory
Reading Numbers
 Example: Any of the following scanf calls can be used to read two numbers of type double
from the keyboard

 Possible inputs:

 Reading without using the address operator (&) on a variable, example:


scanf("%d",x)causes run-time error (the program crashes).
Reading Characters
 Example: A scanf call that reads characters does NOT automatically skip white
space (blanks, tab characters, and new line characters) in the input.
scanf("%c%c", &firstCharacter, &secondCharacter);
 Inputs as : K░M, where ░ is a white space between the two characters, cause the
character K to be read in firstCharacter, and a blank character to be read in
secondCharacter.
 To cause scanf that reads characters to skip one or more white spaces, precede
each format specifier %c by one or more blank characters:
scanf(“ %c %c”, &firstCharacter, &secondCharacter);
Statement: return
 Syntax:
return(0); or return 0;

 Transfers control from your program to the operating system.


 return (0) returns a 0 to the Operating System and indicates that the
program executed without error.
 It does not mean the program did what it was supposed to do. It only
means there were no syntax errors. There still may have been logical
errors.
 Once you start writing your own functions, you’ll use the return statement
to return information to the caller of the function.
Comments
 Comments provide supplementary information, making it easier for us to
understand the program, but the C compiler ignores it.
 Two forms of comments:
 /* */ : anything between them will be considered a comment, even if they span
multiple lines.
 //: anything after this and before the end of the line is considered a comment.
 Comments are used to create Program Documentation
 Information that helps others read and understand the program.
 The start of the program should consist of a comment that includes the
programmer’s name, the date of the current version, and a brief description of
what the program does.
 Always Comment on your Code!
White Spaces (Indentation)
 The complier ignores extra blanks between words and symbols, but you may
insert space to improve the readability and style of a program.
 You should always leave a blank space after a comma and before and after
operators such as , −, and =.
 Indentation; You should indent the lines of code in the body of a function
 Indentation will be used in other syntaxes such as selection and repetition

Bad: Good:
Arithmetic Expressions
 To solve most programming problems, you will need to write arithmetic
expressions that manipulate type int, float, and double data.
 Each operator manipulates two operands, which may be constants, variables,
or other arithmetic expressions.
 Example
Arithmeti
Works with
 5 + 2 c Examples
datatype
Operator
 sum + (incr * 2) 5 + 2 is 7
+ int and double
 (b/c) + (a + 0.5) 5.0 + 2.0 is 7.0
5 - 2 is 3
 The following table shows all - int and double
5.0 - 2.0 is 3.0
arithmetic operators. 5 * 2 is 10
* int and double
5.0 * 2.0 is 10.0
5 / 2 is 2
/ int and double 29
5.0 / 2.0 is 2.5
% int 5 % 2 is 1
Operators: / (division) and % (remainder)
 Division: When applied to two positive integers, the division operator (/)
computes an integral part of the result by dividing its first operand by its second.
 For example: 7.0 / 2.0 is 3.5
 7 / 2 is only 3
 The reason for this is that C makes the answer be of the same type as the
operands.
 Remainder: The remainder operator (%) returns the integer remainder of the
result of dividing its first operand by its second.
 Examples: 7 % 2 = 1,
 6%3=0
 The value of m%n must always be less than the divisor n.
 The operations / and % are undefined when the divisor (second operator) is 0.

30
Data Type of an Expression
 The data type of each variable must be specified in its declaration, but how does C
determine the data type of an expression?
 Example: What is the type of expression x + y when both x and y are of type
int?
 The data type of an expression depends on the type(s) of its operands.
 If both are of type int, then the expression is of type int
 If either one or both is of type double, then the expression is of type double.
 Example: what is the result of 5 / 2.0

 An expression that has operands of both int and double is a mixed-type


expression
 31
Example: What is the type of the assignment y = 5.0 / 2.0 when y is of type int?
 Example: What is the type of the assignment y = 5/2 when y is of type double?
Rules for Evaluating Expressions
 Parentheses rule - All expressions in parentheses must be evaluated
separately.
 Nested parenthesized expressions must be evaluated from the inside out, with
the innermost expression evaluated first.
 Operator precedence rule – Multiple operators in the same expression are
evaluated in the following order:
 First: unary – (such as the sign of the number)
 Second: binary operation *, /, %
 Third: binary operation +,-
 Associativity rule
 Unary operators in the same sub-expression and at the same precedence level
are evaluated right to left
 Binary operators in the same sub-expression and at the same precedence level
32
are evaluated left to right.
Evaluation Tree for v =(p2-p1)/(t2-t1)
Evaluation Tree for z-(a+b/2)+w*-y
Problem Solving
 Note: It is recommended before writing a C program to solve the problem it is
solving by first writing the analysis and then writing a pseudo-code algorithm or
draw a flowchart for the problem.
 A sample problem and its analysis and pseudo-code algorithm is:
 Problem: Write a C program that prompts for and reads two integer values. It then
computes and displays the sum and the product of the two values.
 Pseudo-code algorithm :
1. Prompt for num1
2. Input num1
3. Prompt for num2
4. Input num2
5. Compute sum = num1 + num2;
6. Compute product = num1 * num2;
7. Output: "sum = ", sum, "product = ", product;
8. Stop.

You might also like