CS 12-Pages-1-27
CS 12-Pages-1-27
In the Beginning
C Data Types
Variable Declaration
Basic Operators of C
Case e 1: Assist a teacher in calculating grades (using if/ else if/ else)
Case e 3: Display the high-school level (using i// else if/ else)
Chapter S Arrays
CHAPTER 1:
Introduction to C - Language
C-Language
Everything has its beginning. Now this is the right time and place to start, to
start talking about how C started. Well, C is like Pascal. It is a general-purpose
programming language and it started to run under Unix environment. C is closely
associated with Unix, because the operating system itself and majority of its
supporting application programs are written in C. However, this doesn't mean that C
could only run under Unix operating system environment. As a matter of fact, C can
run on almost any hardware and software platforms available in the world today.
Dr. Dennis Ritchie invented the C programming language at AT&T Bell
Laboratories, New Jersey, U.S.A. in early 1970s. Since C is similar to Pascal, a
structured-programming language; it provides the fundamental control-flow for well-
designed programs. These include statement groupings, decision-making if-else),
selecting one of the set of possible cases (switch/case and i//e/se ig, and looping
statements (while, for, do-w//i/e).
C is considered as middle-level programming language, because it combined
the power of low-level language (such as Assembly language) and the elegance of
high-level language like Pascal. This further means that C language can directly
manipulate the bits, bytes, and even the computer hardware memory addresses. This
makes C powerful, and the best tool for systems programming. Systems
programming is aimed in designing and developing operating systems, compilers,
interpreters, database software, and other highly sophisticated software including
embedded intelligence programs. Embedded intelligence systems are programs
embedded inside an Integrated Circuits (IC) or chips. Like other programming
language, C has its own blemishes. Some of its syntax could be designed better and
shorter like in the case of “case conditional statement”. Compared to Pascal, it is
longer and cumbersome to use. Well, inspite of that, C is still the choice of many
professional programmers and software engineers for designing and developing
highly sophisticated software. This is because C language has been proven to be an
extremely powerful, expressive, and effective language for a wide variety of
programming applications.
The UNIX operating system, the C compiler, and essentially all UNIX application
programs have been written in C. C has now become a widely used professional
language for various reasons —
• Easy to learn
• Structured language
• It produces efficient programs
• It can handle low-level activities
• It can be compiled on a variety of computer platforms
Facts about C
• Operating Systems
• Language Compilers
• Assemblers
• Text Editors
• Print Spoolers
• Network Drivers
• Modern Programs
• Databases
• Language Interpreters
• Utilities
C Programs
A C program can vary from 3 lines to millions of lines and it should be written into one
or more text files with extension ".c"; for example, hello.c. You can use "vi", "vim" or
any other text editor to write your C program into a file.
C Data Types
Before a variable name (identifier) can be used in a C program, it must be
declared explicitly, together with its corresponding data type. There are some
restrictions in giving a name to variables and constants. Names can be composed of
letters and numbers, however the first character must be a letter. Capital
(uppercase) letters and small (lower case) letters are treated differently, so capital A
3
is not the same with small a. When we declare capital A as a variable or constant
name, capital A must be consistently used throughout the program, not in
combination of small a. Otherwise, it will trigger an error during compilation.
Keywords or commands such as case, int, float, if, do, for, etc., cannot be used as
variable or constant names, because they are considered as reserved words. C
programming language is a case-sensitive. This means that all keywords, commands
and standard functions of C language must be written in lower case letters.
Remember that it is a good programming practice to choose and use variable and
constant names which are related to its intended purpose. For example, the best
variable name for sum is sum, not s, and the best constant name of Pi (0) is Pi.
Basic Data types of C
Type Format Meaning (Example(s))
constant name.
\ alert(beII)character
\b backspace
\n new line/next line
\r carriage return/Enter key
horizontal tab
vertical tab
backslash
\f \form feed
Variable Declaration
We have to declare all variables and constants, before we can use them in our
main program (main()). When we declare a variable, we specify its data type. For
example, to declare a variable with data type integer, float, and character, we simply
write: int sum;
or we can group similar data type variables in one list such as:
int n1,n2,sum,diff;
float area, fah, celsius, divided; char letter,
symbol, initial;
watch clearly and objectively, how the C compiler executes my program one line at a
time. It gives me more ideas how my program behaves and why it behaves that way.
And with my careful analysis and examination, I could find out why my program
produces such undesired output. It is called “undesired” because that's not what I
expected it to produce. This is really very important in programming task.
By the way, let us go back with variable monitoring. W. Digjstra, one of the
famous authorities and number one advocate of structured programming paradigm
once said: “ Once a person understands how a variable is used in the program, he
has understood the quintessence of programming.“ So that's it! Know the basics:
using variables, and how it is being manipulated or processed within the program is
the beginning of wisdom (tooth?).
Basic Operators of C
Arithmetic Operators
Symbols Meaning
Addition
Subtraction
Multiplication
/ Division
% Modulus (Remainder)
In Pascal language, we use the command mod to get the remainder in a
particular operation.
This can be easily understood through this comparative syntax:
Compile menu in our Turbo C compiler, or using the short-cut commands the: Ctrl-F9
keys to be pressed together or simultaneously. It's the same with Turbo Pascal's
compilation and running the program (Alt-F9 and Ctrl-F9 procedures).
Relational Operators
Symbols Meaning
greater than
>= greater than or equal to
less than
<= less than or equal to
equal to
!= not equal to
The difference between Pascal and C syntax of relational operators are the eqL/a/ or
not equal symbols. In Pascal programming language, we use single = (equal) sign
for our equality symbol while in C programming language we use double ==
(double equal) sign for our equality symbol. This is because the single equal
symbol (=) is used as assignment operator. That's where we can find the conflict in
C application of syntax. In Pascal language, there's no conflict of syntax since its
assignment operator is this symbol := (colon equal symbol).
Logical Operators
Symbol Meaning &&
and
or
! not
X Y Z=X*
0 0 0
0 1 0
1 0 0
1 1 1
7
X Y Z=X+
0 0 0
0 1 1
1 0 1
1 1 1
In Pascal programming language, we use the words and, or, and not,
however, in C we have to use symbols for logical and . && (two ampersand
symbols), for logical or : | | (two pipe symbols), and for logical not: !
(exclamation mark). The pipe symbol (||) can be found below (for old
keyboard) or above (for newly designed keyboard) the famous Enter key.
(Don't say it doesn't exist in your keyboard, man!).
Symbols Meaning
+= plus equal
minus equal
*= multiply equal
/= divide equal
o/o- modulus equal
minus minus (decrement)
++ plus plus (increment)
i=i+2 i+=2
p=p*b p*=b
r=r/4 r/=4
j=j-3 j-=3
n=no/o2 n0/o-2
“The only way to learn a new programming language is by writing programs in it.”
-Dennis M. Ritchie
Practice 1:
Write a C program that calculates the sum of two input numbers, and
display the result.
9
Algorithm:
Solution:
#include <stdio.h>
+e*^()
int sum, n1,n2j
Discussion:
The first line in our program is the #incIude statement which means we
tell the C compiler to use the standard input/output header file <stdio.h> that
contains the standard input/output functions such as printf( ), scanf( ), getch(
), clrscr( ); and much more. The second line is the main( ) function (program)
statement. Every C program should have this statement. The third line is the
list of variables declared as integer data type. The fourth line is the clear screen
(clrscr( )) standard function that tells the computer to clear the entire screen.
The fifth line is the printf( ) output function that commands the computer to
display the message on the screen. The \n (backslash n) control character is
used to tell the C compiler to occupy the whole line in the screen regardless of
how long the message is to be displayed. It further means that the next
message will be displayed in the next line or new line. The sixth line is the
scanf() standard input function which tells the C compiler to scan (read or
accept) the values typed from the keyboard and store them into variables. This
is the input operation in our program. The two %«ds are the data type format
of the n1 and n2 data type variables. The variables to be scanned should be
preceded with 8 symbol. The seventh line is the calculation of som. We are the
10
one who formulate this equation based on our previous knowledge in basic
mathematics. This part is the process (part) operation. The eight line is our
output part where we output the value of variable sum. The ninth line is an
instruction to the computer to pause, in this way we can see our output. The
getch( ) function means get character from the keyboard. Actually there is an
invinsible program pointer that executes our program line by line. Once this
program pointer reaches the last end ( j ) symbol, it will go back to the main
menu in our C compiler program editor. We can experiment this by replacing
getch( ) with delay(3000), in your program instead of writing getch( ). You
could notice how this “pause effect” works without getch( ). This getch( )
function simply waits user to type a character from the keyboard for it to get
that character.
Practice 2:
Algorithm:
Coding:
#incIude <stdio.h>
#define Pi 3.1416
main(j
int r/ float A/
Discussion:
You could notice also that in our output statement printf(“\n The area:
%/°”,A ; we format our output variable A with %/. This is because we had
declared our variable A as //oak data type.
Practice 3:
Write a program that computes the average of three input quizzes, then
display the result.
Algorithm:
#incIuda <stdio.h>
main()
Discussion:
Practice 4:
Write program that converts the input Fahrenheit degree into its Celsius
degree equivalent. Use the formula: C=(5/9) ”F-32. Display the result.
Algorithm:
Coding:
#include <stdio.h>
main{)
Discussion:
could notice a case like this: a truncated answer (number), probably you
declare the input variables needed in computation with an integer (int) data
type. Try to change it to //oak data type declaration and observe if it rectifies
the problem.
Remember
In C program, we have to type all commands int, float, for, do ,while, if,
case, etc.) and standard functions printf, scanf, getch( ), etc.) in lowercase
(small) letters, otherwise, we can get a syntax error message during or upon
compilation. This is because C language is a case-sensitive compiler. In other
programming languages such as Pascal, we can type our program in all capital
letters; in all small letters; or combination of both.
It works just fine. But this programming practice is not applicable to C
language. Maybe you had observed that we use constant and variable names in
capital letters such as in the case of A for Area, C for Celsius, F for Fahrenheit,
and Pi as constant name. Yes, we can use constant names and variable
names in capital letters form or combination of lowercase and uppercase letters
such as in the case of Pi (capital P and small i§ again. Take note, that we
cannot use PI (all capitals) in some parts of our program when we had already
use Pi, because they are not equivalent; unlike in Pascal language.
Maybe you had also observed how we format our variables. Actually, the
number of formats is dependent to the numbers of variables being scanned or
printed. For example, in our solution about the area of a circle, we have only
one %d, because we have only one scanned variable, the &r.
scanf(“%d%d%d”,q1,q2,q3),’ /* WRONG
STATEMENT */ printf(“\n The area: O/of”, &A]; /”
WRONG STATEMENT */
Remember
These two above statements will not produce syntax errors during compilation
and running time. However, your program will behave differently, such as your
program will execute so fast without waiting for an input values from the
keyboard. In the case of prinff( }, your program will produce an unusual output
value. Some of these values are in ASCII form (or Chinese-like characters) and
with letters and numbers combined.
15
ASSESSMENT NO.1
CHAPTER 1:
Name: Date:
Year/Course: Score:
1-20 Identification
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
1-30 Application
Write your answer here:
Application TEST 1
2. Write a program that converts the input Celsius degree into its equivalent
Fahrenheit degree. Use the formula: F=(9/5)”C-I-32.
3. Write a program that converts the input dollar to its peso exchange rate
equivalent. Assume that the present exchange rate is 51.50 pesos against
the dollar. Then display the peso equivalent exchange rate.
16
5. Write a program that exchanges the value of two variables : x and y. The
output must be : the value of variable y will become the value of variable x,
and vise versa.
7. YOu can solve the worded-problem number 5 with the use of three
variables declaration. Now try to solve it with only two variables declaration.
Formulate with an equation that exchanges the value of variable x and y.
The hint is: use 3 equations that involve with plus and minus operations.
.Write a program that takes as input the purchase price of an item (P), its
expected number of years of service (Y) and its expected salvage value (S).
Then outputs the yearly depreciation for the item (D). Use the formula: D=
(P-S)/Y
where:
R= total yearly production
requirement S= set up cost
per order
I=inventory carrying cost per unit
10. Write a program to compute the radius of a circle. Derive your formula
from the given equation: A=Or2, then display the output.
17
CHAPTER 2:
C - Basic SynŒx
You have seen the basic structure of a C program, so it will be easy to
understand other basic building blocks of the C programming language.
Tokens in C
A C program consists of various tokens and a token is either a keyword, an
identifier, a constant, a string literal, or a symbol. For example, the following C
statement consists of five tokens —
printf("Hello, World! \n");
The individual tokens are —
printf
Semiœlons
In a C program, the semicolon is a statement terminator. That is, each
individual statement must be ended with a semicolon. Il indicates the end of
one logical entity.
Given below are two different statements —
printf("Hello, World! \n");
return 0;
Comments
Comments are like helping text in your C program and they are ignored by the
compiler. They start with /” and terminate with the characters "/ as shown
below —
/" my first program in C ”/
You cannot have comments within comments and they do not occur within a
string or character literals.
Identifiers
A C identifier is a name used to identify a variable, function, or any other user-
defined item. An identifier starts with a letter A to Z, a to z, or an underscore
_’ followed by zero or more letters, underscores, and digits (0 to 9).
C does not allow punctuation characters such as @, $, and o/o within identifiers.
C is a case-sensitive programming language.
Thus, Nanpower and manpower are two different identifiers in C. Here are
some examples of acceptable identifiers —
mohd zara abc move_name a_123
myname50 _temp j a23b9 retVal
18
Keywords
The following list shows the reserved words in C. These reserved words may
not be used as constants or variables or any other identifier names.
auto Else long switch
Whitespace in C
A line containing only whitespace, possibly with a comment, is known as a
blank line, and a C compiler totally ignores it.
Whitespace is the term used in C to describe blanks, tabs, newline characters
and comments. Whitespace separates one part of a statement from another
and enables the compiler to identify where one element in a statement, such
as int, ends and the next element begins. Therefore, in the following statement
int age;
there must be at least one whitespace character (usually a space) between int
and age for the compiler to be able to distinguish them. On the other hand, in
the following statement —
fruit apples + oranges; // get the total fruit
no whitespace characters are necessary between fruit and =, or between = and
apples, although you are free to include some if you wish to increase
readability.
C - Variables
A variable is nothing but a name given to a storage area that our programs can
manipulate. Each variable in C has a specific type, which determines the size
and layout of the variable's memory; the range of values that can be stored
within that memory; and the set of operations that can be applied to the
variable.
19
The name of a variable can be composed of letters, digits, and the underscore
character. It must begin with either a letter or an underscore. Upper and
lowercase letters are distinct because C is case-sensitive. Based on the basic
types explained in the previous chapter, there will be the following basic
variable types —
Type Description
char Typically a single octet(one byte). This is an integer type.
int The most natural size of integer for the machine.
float A single-precision floating point value.
// Variable declaration:
extern int a, b;
extern int c;
extern float f;
int main ()
/* variable definition: */
int a, b;
int c;
float f;
20
/” actual initialization ”/
a = 10;
b = 20;
c = a + b;
printf("value of c O /od \n", c);
f 70.0/3.0;
printf("value of f : 0/of \n", f);
return 0;
When the above code is compiled and executed, it produces the following result
value of c : 30
value of f 23.333334
Arithmetic Operators
The following table shows all the arithmetic operators supported by the C
language. Assume variable A holds 10 and variable B holds 20 then —
Show Examples
Operator Description Example
+ Adds two operands. A+ B
30
— Subtracts second operand from the first. A- B
-10
Relational Operators
The following table shows all the relational operators supported by C. Assume
variable A holds 10 and variable B holds 20 then —
Show Examples
Operator Description Example
Checks if the values of two operands are equal (A B)
or not. If yes, then the condition becomes true. is not
true.
!= Checks if the values of two operands are equal (A != B)
or not. If the values are not equal, then the is true.
condition becomes true.
Checks if the value of left operand is greater (A > B)
than the value of right operand. If yes, then the is not
condition becomes true. true.
Checks if the value of left operand is less than (A < B)
the value of right operand. If yes, then the is true.
condition becomes true.
= Checks if the value of left operand is greater (A >= B)
than or equal to the value of right operand. If is not
yes, then the condition becomes true. true.
Checks if the value of left operand is less than or (A <= B)
equal to the value of right operand. If yes, then is true.
the condition becomes true.
Logical Operators
Following table shows all the logical operators supported by C language.
Assume variable A holds 1 and variable B holds 0, then —
Show Examples
Operator Description Example
&& Called Logical AND operator. If both the (A && B)
operands are non-zero, then the condition is false.
becomes true.
Called Logical OR Operator. If any of the two (A | | B)
operands is non-zero, then the condition is true.
becomes true.
! Called Logical NOT Operator. It is used to !(A &&
reverse the logical state of its operand. If a B) is
condition is true, then Logical NOT operator will true.
make it false.
22
Assignment Operators
The following table lists the assignment operators supported by the C language
Show Examples
Operator Description Example
= Simple assignment operator. Assigns values C = A -I- B
from right side operands to left side operand will assign
the value
of A + B
to C