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

Module 1.2 - C Language History and Programming Elements

Uploaded by

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

Module 1.2 - C Language History and Programming Elements

Uploaded by

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

Cebu Institute of Technology – University

Computer Engineering Department


Module 1.2 - C Language: History and Programming Elements

C Language: History and Definition


• Dennis Ritchie – developed C at AT&T Bell Laboratories in 1972.
• C was designed as a language for systems programming, as a way to fully access the computer’s
power without becoming caught up in the tedious writing of assembly language.
• One of the most popular languages of modern times.
• Programs written in C are portable across different environments
• Applications created using the C language range from operating systems to database
systems.
• C is a concise language
o It has only about 32 keywords
o It encourages concise code.
• C is flexible, powerful, and well suited for programming several levels of abstraction.
• C is a modular language
o The function is the primary program structure, but functions may not be nested.
o The C programmer depends on a library of function, many of which becomes part
of the standard language definition.
• C is the basis for C++.
o C++ programmer also uses many of the constructs and methodologies that are
routinely used by the C programmer.
o Learning C can be considered a first step in learning C++.

C Language Element: The C Preprocessors


• A program that is executed before the source code is compiled.

DIRECTIVES – how C preprocessor commands are called and begin with a pound / hash symbol
(#). No white space should appear before the #, and a semi colon is NOT required at the
end.
• Preprocessors are ALWAYS placed at the TOP of your program.
• Two Common Directives:
o #include
▪ Gives program access to a library.
▪ Causes the preprocessor to insert definitions from a standard header file
into the program before compilation.
▪ Tells the preprocessor that some names or functions used in the program
are found in included library.
• #include<stdio.h>
• #include<conio.h>
• highlighted part of the code would be discussed later, stdio.h and
conio.h are the libraries the directive is/are calling.
o #define
▪ Allows you to make text substitutions before compiling the program.
▪ Allows you to create constant variables with fixed values all throughout
your code.
• variables are:
- Containers in your computer's memory
- You can store values in them and retrieve or modify them
when necessary.
- You can assign a name to them. (Example is the variable x
that we are most familiar with)
- Will be further discussed later
▪ By convention, all identifiers that are to be changed by the
preprocessor are written in capital letters.
▪ Example:
• #define PI 3.14
- you set the value of variable PI to 3.14
- so when you use it later;
- Area_Circ = PI * r * r; (PI is automatically 3.14, you also
won’t have to declare the variable PI anymore)
• #define MIN 0
• #define MAX 10

Engr. Jundith D. Alterado


jundith.alterado@cit.edu
Cebu Institute of Technology – University
Computer Engineering Department
Module 1.2 - C Language: History and Programming Elements

o Sample Code:
#include <stdio.h> /*calls library stdio*/
#define MIN 0 /* #defines */
#define MAX 10
#define TRUE 1
#define FALSE 0
int main() { /* beginning of program */
int a;
int okay = FALSE; /*the compiler sees this as int okay=0;*/
while(!okay)
{
printf("Input an integer between %d and %d: ", MIN, MAX);
scanf("%d", &a);
if(a>MAX) { /*the compiler sees this as a>10;*/

printf("\nToo large.\n"); }
else if(a<MIN) {
printf("\nToo small.\n"); }
else { printf("\nThanks.\n");
okay = TRUE;
}
}
return 0;
}

The C Library - C implementations that contain collections of useful functions and symbols that
may be accessed by a program.
▪ A function is a block of statements that performs a specific task.
▪ We will be using ready-made functions of the C Library for displaying your outputs,
reading inputs, etc.
• Note: A C system may expand the number of operation available by supplying additional
libraries. Each library has a standard header file whose name ends with the symbol .h

Most Common Libraries we will be using:

▪ Stdio
▪ Probably the library we will be using the most.
▪ Most common functions under the stdio library:
▪ printf(), scanf(), gets(), puts() – we will discuss them one-by-one later.
(They are Input and Output functions)
▪ If you want to use the functions above, you have to call the stdio library
using the #include directive.
▪ Example:
• #include<stdio.h>
• Enclose the library inside the < > symbols, and add .h
• No space must be found anywhere in your code.
• #include < stdio.h > -WRONG
▪ conio
▪ Most common functions under the conio library:
▪ getch(), getche()
▪ If you want to use the functions above, you have to call the conio library
using the #include directive.
▪ Example:
• #include<conio.h>
• Enclose the library inside the < > symbols, and add .h
• No space must be found anywhere in your code.
• #include < conio.h > -WRONG
▪ math
▪ Most common functions under the math library:
▪ pow(), sqrt(), ceil(), floor(), abs(), etc
▪ If you want to use the functions above, you have to call the math library
using the #include directive.
▪ Example:
• #include<math.h>

Engr. Jundith D. Alterado


jundith.alterado@cit.edu
Cebu Institute of Technology – University
Computer Engineering Department
Module 1.2 - C Language: History and Programming Elements

• Enclose the library inside the < > symbols, and add .h
• No space must be found anywhere in your code.
▪ #include < math.h > -WRONG

Predefined Mathematical Functions
▪ These are functions under the math.h library
Function Purpose
abs(x) returns the absolute value of integer x.
x = abs(-5); x=5
fabs(x) returns the absolute value of type double.
x = fabs(-5.2); x=5.2
ceil(x) rounds up or returns the smallest whole number that is not
less than x.
x = ceil(5.2); x=6
floor(x) rounds down or returns largest whole number that is not
greater than x.
x = floor(5.2); x=5
sqrt(x) returns the non-negative square of x.
x = sqrt(25); x=5
pow(x, e) returns x to the power of e.
x = pow(4,2); x=16
sin(x) returns the sine of angle x.
cos(x) returns the cosine of angle x.
tan(x) returns the tangent of angle x.
log(x) returns the natural logarithm of x.
Summary

Commenting on your code


▪ You can add comments to your code by enclosing your remarks within /* and */. However,
nested comments aren't allowed.
▪ A few properties of comments:
• They can be used to inform the person viewing the code what the code does. This
is helpful when you revisit the code later.
• The compiler ignores all the comments. Hence, commenting does not affect the
efficiency of the program.
• You can use /* and */ to comment out sections of code when it comes to finding
errors, instead of deletion.
▪ Here are examples of commented code:

Note: /* /* NESTED COMMENTS ARE ILLEGAL!! */ */

Engr. Jundith D. Alterado


jundith.alterado@cit.edu
Cebu Institute of Technology – University
Computer Engineering Department
Module 1.2 - C Language: History and Programming Elements

C Language Element: Function Main

▪ Every C program has a main function. This is where program execution begins.
▪ Entry point of the program.
▪ Found under the C Preprocessors
▪ Body- the remaining line of the program is in the body.
▪ Braces {} – enclose the body of the function.
• Indicates the beginning and end of the function main.
▪ Example:
#include<stdio.h> /*C preprocessors found at the top of your code*/
int main() /*this is how you write your function main, no semicolon*/
{
…body of your code.
…enclosed inside an opening and closing brace { }
}
▪ Two parts of the main function body:
o Declarations
▪ The part of the program that tells the compiler the names of memory cells
(variables) needed in the program, commonly data requirements identified
during problem analysis.
▪ Simply, where you introduce your variables
o Executable statements
▪ Derived statements from the algorithm into machine language and later
executed. (Your translated algorithm into syntax)
▪ Program code proper, where all your process can be found.

Structure of a C Program
#include<stdio.h> /*C preprocessors*/
#include<conio.h>
#include<math.h>
int main() /*your main function*/
{
/*Variable declarations here*/

/*If possible, Inputs should be placed here*/

/*Arithmetic operations/program statements here*/

/*Display/Program Output here*/


}

Summary: Your program Structure should follow the format below:


I. Directives (Calling of the C Prerocessors)
II. Main Function
Inside the main function:
a. Variable declaration
b. Input of data
c. Arithmetic Operations/Processes
d. Display/Output of Data

Engr. Jundith D. Alterado


jundith.alterado@cit.edu
Cebu Institute of Technology – University
Computer Engineering Department
Module 1.2 - C Language: History and Programming Elements

Reserved Words
• In C, a reserved word is defined as the word that has special meaning in C and cannot be
used for other purposes.
• Examples: int, void, double, return

Punctuation Marks
/* */ -(slash asterisk) used to enclose a single line remarks/comments.
“ “ -(double quotation) used to display series of characters, and initializing string
constant.
; -(semicolon) statement separator (VERY IMPORTANT!) Your lines of codes
should always end in semicolon except in some special cases.
, -(comma) used to separate one variable to another
= -(equal sign) used as assignment operator
‘ -(single quotation) used for initializing character expression
& -(ampersand) used as address operator
{} -(open/close braces) denotes the beginning and end of the program.

C Language Element: Variables, Data Types and Constants

Identifiers (used to identify your variables)


• One feature present in all computer languages is the identifier.
• Identifiers allow us to name data and other objects in the program.
• Each identified object in the computer is stored at a unique address.
• If we didn’t have identifiers that we could use to symbolically represent data locations,
we would have to know and use object’s addresses. Instead, we simply give data
identifiers and let the compiler keep track of where they are physically located.
• Simply, naming your variables so that we can easily identify them.

Naming Conventions (Identifiers)


• Names are made up of letters and digits.
• The first character MUST be a letter.
• C is case-sensitive, example: ‘s’ is not the same with ‘S’.
• The underscore symbol (_) is considered as a letter in C. It is not recommended to be
used, however, as the first character in a name.
• At least the first 3 characters of a name are significant.
Names... Example
CANNOT start with a number 2i
CAN contain a number elsewhere h2o
CANNOT contain any arithmetic operators... r*s+t
CANNOT contain any other punctuation marks... x%£!!a
CAN contain or begin with an underscore _height_
CANNOT be a C keyword struct
CANNOT contain a space im stupid
CAN be of mixed cases Squared

Engr. Jundith D. Alterado


jundith.alterado@cit.edu
Cebu Institute of Technology – University
Computer Engineering Department
Module 1.2 - C Language: History and Programming Elements

Variables
• Are like containers in your computer's memory
• You can store values in them and retrieve or modify them when necessary.
• Associated with a memory cell whose value can change as the program executes.
Variable declaration
• Statements that communicate to the C compiler the names of all variables used in the
program and the kind of information stored in each variable.
• Also tells how that information will be represented in memory.

Syntax for Variable Declarations:


dataType variable_list;
Ex. int x,age; -- variables
float sum,a,b; -- data type
char middle_intial; multiple variables is separated by a comma.

Data Type
• A set of values and a set of operations that can be performed on those values.
• Standard Predefined Data Type in C:
▪ char
▪ double/float
▪ int
• int
o int is used to define integer numbers (whole numbers).
o Example
▪ int num; /*declaration only*/
▪ num = 12; /*putting the value of 12 into num*/

▪ int x = 3, y = 4, sum; /*declaration*/


▪ sum = x+y; /*adding the values of x and y and storing them into sum*/
• float
o float is used to define floating point numbers (or numbers that are fractional or
have a decimal value) but it can also store whole numbers, as they would be
recognized by the compiler as having a .00 decimal point/s (example: 15 would be
read as 15.00)
Note: We would be calling decimal numbers as floating point numbers.
o Example
▪ float miles; /*declaration*/
• miles = 15.82;

▪ float pi = 3.14, r = 5.5, area; /*declaration*/


• area = pi * r * r;
• char
o char is used to define characters.
o Example
▪ char Letter; /*declaration*/
• Letter = ‘a’;

• Notes:
o int variables can only store whole numbers;
▪ int num;
• num = 12.45;
▪ in the code above, only 12 will be stored in variable num, all values after
the decimal point will be ignored since num was declared as an int
variable.
▪ If you display the value of num, the result is 12.
o float variables can store whole numbers
▪ float num;
• num = 12;
▪ in the code above, the value of num would be 12.00
▪ if you display the value of num, the result is 12.000, depending on the
number of decimal points you want to display.

Engr. Jundith D. Alterado


jundith.alterado@cit.edu
Cebu Institute of Technology – University
Computer Engineering Department
Module 1.2 - C Language: History and Programming Elements

o Examples
▪ int num1 = 5, sum;
• float num2 = 5.5;
• sum = num1 + num2;
▪ final value of sum would be 10. Because sum was declared as an int, it
can only store whole numbers. So even though the operation above
translates to sum = 5 + 5.5 which is equal to 10.5, the variable sum would
only contain 10 and ignore the 0.5, but if

▪ int num1 = 5;
• float num2 = 5.5, sum;
• sum = num1 + num2;
▪ final value of sum would be 10.5. Because sum was declared as a float,
it can store decimal values.
o Additional note:
▪ You can use both int and float in arithmetic equations, just be careful
because there are cases like these:

▪ int num = 5;
▪ float quo;
▪ quo = num/2;
▪ final value of quo would be 2.000000. Because even though quo was
declared as float, it would receive a value that is a result between dividing
two integers (variable num and constant 2). So instead of 2.5 which is a
float value the result of num/2 would be 2 and since quo is float, it would
store it as 2.000000 (6 decimal places is the default display for float
values)
Constants
▪ identifiers that are having a constant value all throughout the program execution.
▪ also fixed values that may not be altered by the program.
▪ Examples:
o Character constants – enclosed between single quotes. Ex. ‘A’, ‘+’
o Integer constants – specified as numbers without fractional components.
Ex. 5 and -160
o Floating constants – require the use of decimal point followed by the number’s
fractional components. Ex. 16.234
o String constants – set of characters enclosed by double quotes. Ex. “bag” and
“this is good”
o Backslash character constants – enclosing all character constants in single
quotes that works for most printing characters. Ex. g = ‘\t’

Escape Sequence Characters


SEQUENCE NAME MEANING
\a Alert Sound a beep

\b Backspace Backs up one character


\f Form feed Starts a new screen of page

\n New line Moves to the beginning of the next line

\r Carriage Return Moves to the beginning of the current line

\t Horizontal tab Moves to the next Tab position

\v Vertical tab Moves down a fixed amount


\\ Backslash Displays an actual backslash
\’ Single quote Displays an actual single quote
\? Question mark Displays an actual question mark
\”” Double quote Displays an actual double quote

Engr. Jundith D. Alterado


jundith.alterado@cit.edu
Cebu Institute of Technology – University
Computer Engineering Department
Module 1.2 - C Language: History and Programming Elements

Defining Constants
▪ #define preprocessor
o allows us to define symbolic names and constants.
o A quick example:
• #define PI 3.14159
• This statement will translate every occurrence of PI in the program to
3.14159.
• Here is a more complete example:

#define PI 3.14159
int main()
{
int r=10;
float cir;
cir = PI * (r*r);
PI = 3.15; --this would be an error. You can’t change the value of
a constant variable in your program.
}
▪ const
o used to create a read only variable. Once initialized, the value of the variable
cannot be changed but can be used just like any other variable.
o Example:
int main()
{
const float PI = 3.14;
}
▪ The const keyword is used as a qualifier to the following data types –
int, float, char.
▪ const int DEGREES = 360;
▪ const float PI = 3.14;
▪ const char QUIT = 'q';

Assignment Operator – Equal sign (=)


- the most basic assignment operator where the value on the right of the equal sign is
assigned to the variable on the left.
- X = 10 means the value 10 is stored to variable X.
- The statement C = A + B means that add the value stored in variable A and variable
B then assign/store the value in variable C.
- The statement R = R + 1 means that add 1 to the value stored in variable R and
then assign/store the new value in variable R, in other words increase the value of
variable R by 1.
- There is no power (^) symbol in C, we will have to manually multiply it or use the pow()
function of the math.h library
- Examples:
▪ c = c + 1;
▪ radius = 2 * diameter;
▪ If we want to compute for the Area of a circle:
▪ Define PI as a constant variable first either using #define or const
Solution 1: instead of r^2 we use r*r
area_of_circle = PI * r * r;
Solution 2: instead of r^2 we use pow(r,2) → r raise to the power of 2
area_of_circle = PI * pow(r,2);

Binary Operators
▪ take two operands and return a result.
▪ Operator Use Result
+ op1 + op2 adds op1 to op2
- op1 - op2 subtracts op2 from op1
* op1 * op2 multiplies op1 by op2
/ op1 / op2 divides op1 by op2
% op1 % op2 computes the remainder
from dividing op1 by op2
▪ Note: the % operator can ONLY be used between two int variables

Engr. Jundith D. Alterado


jundith.alterado@cit.edu
Cebu Institute of Technology – University
Computer Engineering Department
Module 1.2 - C Language: History and Programming Elements

▪Proper:
▪ int x = 9, y = 2, rem;
rem = x%y;
final value of rem would be 1.
▪ Wrong
▪ float x = 9, y = 2, rem;
• rem = x%y;
this would cause an error. You cannot use % operator between two float
variables or with ANY float variable even though one of them is int.
Relational Operators

• take two operands and returns a result of either TRUE or FALSE


• conditional statements are expressions that uses relational operators
Operator Meaning Example
< Less than A < B, A is less than B
<= Less than or equal A <= B, A is less than or equal
to B
== Equal to A == B, A is equal to B
!= Not Equal to A != B, A is not equal to B
> Greater than A > B, A is greater than B
>= Greater than or equal A >= B, A is greater than or
equal to B

Example of Relational Expressions:


Expression Assumed values Results
A<B A=12, B=12 False
num1<=0 num1=0 True
C>D C=0, D=4 False
area>=55 area = 55.5 True
L>=W A=8, W=6 True

Logical Operators

• takes one or two conditional statements as operands and returns a result of either TRUE
or FALSE.
Operator Example Meaning
&& (AND) A<B && B<C Result is TRUE if both A<B
and B<C are TRUE, else
FALSE
|| (OR) A<B || B<C Result is TRUE if either A<B
or B<C are TRUE, else
FALSE
! (NOT) !(A>B) Result is TRUE if A>B is
FALSE, else TRUE
Note:
In AND, it will only be TRUE if both the statements are true. Otherwise, FALSE.
In OR, it will be TRUE as long as one of them, or both, are TRUE. Otherwise FALSE.

Examples of Logical Expressions:


Expression Assumed values Results
A=12, B=12
False
num1=0
(A<B) && (num1<=0)
A=9, B=12
True
num1=0
C=0, D=4
True
area = 55.5
(C>D) || (area>=55)
C=0, D=4
False
area = 54.5
!(L>=W) A=8, W=6 False

Engr. Jundith D. Alterado


jundith.alterado@cit.edu

You might also like