0% found this document useful (0 votes)
70 views27 pages

CS 12-Pages-1-27

The document outlines chapters in an introduction to C language book, including chapters on input/output statements, conditional statements, looping statements, and arrays. Chapter 1 introduces C and discusses its history, uses, data types, and variables. It describes C as a general purpose, middle-level programming language developed in the 1970s to write operating systems like UNIX.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
70 views27 pages

CS 12-Pages-1-27

The document outlines chapters in an introduction to C language book, including chapters on input/output statements, conditional statements, looping statements, and arrays. Chapter 1 introduces C and discusses its history, uses, data types, and variables. It describes C as a general purpose, middle-level programming language developed in the 1970s to write operating systems like UNIX.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Contents

Chapter 1: Introduction to C Language

In the Beginning

C Data Types

Variable Declaration

Basic Operators of C

Chapter 2: The Basic Input/output Statements of C

Case 1: Sum of Two Input Numbers

Case 2: Area of a Circle

Case 3: Compute the Average

Case 4: Converts Fahrenheit to Celsius

Some Things to Remember

Lab-Application Test 1: Simple Input / Output Statements


Chapter 3 The Conditional Statements

Simple if-else Conditional Statements

Case 1: Determine the input age

Case 2: Determine the magic number

Case 3: Determine if Positive or Negative number

Case 4: Determine if Odd or Even number

Ladderized if/ else if/ e/se Conditional Statements

Case e 1: Assist a teacher in calculating grades (using if/ else if/ else)

Case 2: Display an equivalent color (using if/ else if/ else)

Case e 3: Display the high-school level (using i// else if/ else)

Switch/Case Conditional Statements

Case 1: Assist a teacher in calculating grades (using switch/case)

Case 2: Display an equivalent color (using switch/case)

Case 3: Display the high-school level (using switch/case)

Lab-Application Test 1: Conditional Statements


Chapter 4 The Looping Statements

Incrementation, Decrementation, and Accumulator Formulas

Case 1: Sequence number generator

1st Solution: Using while Loop

2’d Solution: Using do-while Loop

3’d Solution: Using for Loop

Case 2: Inverse sequence number generator

1st Solution: Using for Loop

2’d Solution: Using while Loop

3rd Solution: Using do-while Loop

Case 3: Sum of the given sequence numbers

1*t Solution: Using for Loop

2nd Solution: Using while Loop

3rd Solution: Using do-while Loop


Case 4: Compute the Factorial value

1st Solution: Using for Loop

2nd Solution: Using while Loop

3rd Solution: Using do-while Loop

Program Simulation Example 1

Program Simulation Example 2

Lab-Application Test 1: Looping Statements

Chapter S Arrays

Case 1: Simple One-Dimensional Array

Case 2: Simple Two-Dimensional Array

Case e 3: Determine the highest value in an array variable

Case 4: Determine the Even numbers in an array variable

Lab-Application Test 1: Arrays


1

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.

“Variables and constants are the


basic data objects
manipulated in a program.”
-Dennis Ritchie

C is a general-purpose, high-level language that was originally developed by Dennis M.


Ritchie to develop the UNIX operating system at Bell Labs. C was originally first
implemented on the DEC PDP-11 computer in 1972.
In 1978, Brian Kernighan and Dennis Ritchie produced the first publicly available
description of C, now known as the K&R standard.
2

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

• C was invented to write an operating system called UNIX.


• C is a successor of B language which was introduced around the early 1970s.
• The language was formalized in 1988 by the American National Standard Institute
(ANSI).
• The UNIX OS was totally written in C.
• Today C is the most widely used and popular System Programming Language.
• Most of the state-of-the-art software have been implemented using C.
• Today's most popular Linux OS and RDBMS MySQL have been written in C.
Why use C?
C was initially used for system development work, particularly the programs that make-
up the operating system. C was adopted as a system development language because it
produces code that runs nearly as fast as the code written in assembly language. Some
examples of the use of C might be —

• 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))

int % or %i -a whole number (3,7,-i-8,-9,1000000)


float d -a number with decimal point
%f
(5.8, 9.0, -5.6789, +0.0032)
char O/oC
-a single letter, symbol, or number
enclosed within two single quotes
(‘B’, ‘r’, ‘*’, ‘3’)
ChaF O/os -a string in C is considered as a
series of characters (“Ms.”,”Hi!”, “143”,
love”)
double O
/of -for bigger or larger numbers with a decimal
point (123456789.123)

Every time we issue an input/output command or function in C program, we


always format the input/output variable. For example, if we declare n as type
int(integer) such as: int nj our input formatting is : scanf(“O/od”,&n). Now if we
declare Area as type float(real) such as: float Areaj our output formatting is:
printf(“The area: %f”,Area). Since string is considered as just a series of characters
in C, therefore its declaration is in character form (char). In declaring string variable
name, we simply write: char name[20];. The number 20 inside the square
brackets is the maximum characters a string variable name can handle or hold. If
the input string value is longer than 20 characters (including the spaces), the first 20
characters are only considered for manipulation and display. It's like the name is
being cut-off. The input formatting of string is simply:
scanf(“O/os”, &name); and the output formatting is printf(“O/os”,name).

To declare a constant name, we use the keyword #define. For example, to


declare Pi as a constant name, we use this syntax: #define Pi 3.1416 . This #define
declaration follows right after the #incIude declaration. In traditional C programming
practice, variable names are written in lower case, while constant names are written
in uppercase, or combination of both uppercase and lowercase, like in the case of Pi
4

constant name.

In our output statement printf, we use control characters or escape sequences.


The most popular and widely used is the backslash n (\n). This means a new line or
next line. The other set of control characters are the following:

Control Characters Meaning

\ 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;

float area; char letter;

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;

We can initialize the variable too, upon declaration. Initializing a variable


means we put the first value of that variable. In some cases, the C system compiler
would issue a warning message about a variable that was used but need to be
initialized first before being executed, manipulated, or processed. This warning
message was issued by the C compiler, so that the process or computation is correct
or accurate. We have to remember that an uninitialized variable would contain a
garbage data which is automatically produced or given by the computer's main
memory (RAM). You could notice this one when you use the Break/Watch menu. This
sub-menu item in our C system compiler is a very handy tool in monitoring how the
variables handled its value while they were being executed. In other words, this is
the best debugging tools we can use as programmer in C, Pascal, and some other
programming languages. I constantly used this Break/Watch submenu, when I'm
analyzing, debugging, and improvising my program that uses many looping
statements. After typing the variable to watch at the pop-up window of Break-watch
submenu. I just press F7 key to trace each line of my program. In that way, I can
5

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.

We have to examine our program seriously, because in programming, “trial-


and-error” technique doesn't work at all! Based on my own experience, this “trial-
and-error” will only mislead you to believe that programming is a very disappointing
task. Programming is not a matching type or a multiple choice examinations which
the odd of selecting the right answer is probable through the law of elimination. It is
more than that. It is a mind-power game, a mental exercise. It demands a sound
mind, a logical thinking capacity, and unwavering courage to try all over and over
again once we failed so many times. It's like saying, programming is not fit for the
faint-hearted humans, but for the humans whose heart is full of love to learn, no
matter what! That is why I borrowed the wisdom of Socrates who once said:
“Unexamined life is not worth living.” We can apply it in our programming endeavor
by saying: “Unexamined program is not worth doing.” Would you like to try?

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:

In Pascal syntax: R N mod 2;


In C syntax: r = n % 2;

Syntax is the rule of writing a correct program in a certain programming language.


Once we commit a mistake in syntax, we eventually get an error message when we
compile our program. This procedure can be done by pressing F10 and choosing the
6

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

Logical AND (&&)Truth Table

X Y Z=X*

0 0 0
0 1 0
1 0 0
1 1 1
7

Logical OR { || )Truth Table

X Y Z=X+

0 0 0
0 1 1
1 0 1
1 1 1

Logical NOT { ! ) Truth Table


X X "
0 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!).

Other Assignment Operators

Symbols Meaning

+= plus equal
minus equal
*= multiply equal
/= divide equal
o/o- modulus equal
minus minus (decrement)
++ plus plus (increment)

The application of these combined assignment operators is to compress the


form of operation. For example:

n n+1 can be written as n++ or ++n


n n-1 can be written as - -nn- -

Similarly the following equations below can be written in compressed form:


8

Normal Form Compressed Form

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

Technically, the compressed form can be processed by the computer faster


than the normal or traditional form because the calculation is performed only
once. However, this difference in speed is unnoticeable with small programs.
Furthermore, the disadvantage of the compressed format is its inherent
unreadability.

The Basic Input/output Statements of C

“The only way to learn a new programming language is by writing programs in it.”
-Dennis M. Ritchie

In C language program involves three main operations. The first one is


the input operation that uses input functions such as scanf( }, getch( ), gets(
), getche( ), getchar( ) and others. The second is the process operation. In
this part of our program, we can see some equations that are calculated,
conditions which are evaluated, and tasks being performed. The third part is
the output operation. Here, we use output statements such as printf( )
function, puts( ), putch( ), putchar( } functions and other output statement
functions. We could notice that these three operations are interrelated from
each other, since whatever data we input, we also process it. And whatever
variables, equations, or tasks that we processed, we output them into the
screen. As a matter of fact, we can break down our programming tasks into
three phases with these three main operations. Like for example, we have to
analyze first what are those variables to be used as inputs in a given worded-
problem. Then, we will analyze how to process those input variables. And
finally, we can think our way on how to output those things (equations,
conditions, or tasks) that we processed. To learn this technique, we can jump
right in and type our first program that involves these three main operations.

Practice 1:

Write a C program that calculates the sum of two input numbers, and
display the result.
9

Algorithm:

Input Enter two numbers


(n1,n2)

Process —+Compute the sum


sum=n1+n2)

Output Display the sum (sum)

Solution:

#include <stdio.h>
+e*^()
int sum, n1,n2j

printf(“\n Enter two nos.");


scanf(“^/»d^/»d",&n1,&n2)/
sum-n1+n2;
printf(“1n The sum: •/od",sum};
getch{)/

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:

Write a program to calculate the area of a circle and display the


result. Use the formula: A=Or* where Pi (0) is approximately equal to
3.1416.

Algorithm:

Input ——>Enter the radius (r)


Process Compute the Area
(A=Pi”r”r)

Output Display the Area (A)

Coding:

#incIude <stdio.h>
#define Pi 3.1416
main(j
int r/ float A/

printf(“\n Enter the radius:”)/


scanf(“^/»d",&r);
A-Pi*r*r;
printf(“\n Tha area:•/»f”,A)/
getch()/
11

Discussion:

We could notice how the constant name Pi is declared in C, it is by using


the #define command. This is the exact syntax: no equal ( -- ) symbol between
the constant name and its corresponding value. Take note, there is no
semicolon symbol after the constant value.

We declare variable A (for Area) as float because it would eventually


contain a value that has a decimal point. This is because of the resulting
computation that whatever number multiplied to Pi would produce a number
with a decimal point. T he float data type in C programming language is
equivalent to real data type in Pascal programming language.

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:

Input Enter three quizzes (q1,q2,q3)


Process Compute the average
—->(ave=(q1+q2+q3/3)
Output Display the average (ave)

#incIuda <stdio.h>
main()

int q1,q2,q3; float


ave/ clrscr()/
printf(“\n Enter thrae quizzes:");
scanf(“•Ad•/«d•/«d",&q1,&q2&q3};
ave-(q1+q2+q3)/3,
printf{“\n Tha average:•/of”,ave)j
getch()/
12

Discussion:

We declare av'erage variable ave as float, because it is used in a division


operation. In any rules of programming, a whole(integer) number divided by
another whole(integer) number has a possibility of yielding a computation
value with a decimal point. Like in the case of 5/2,' the resulting computation is
2.5 and 2.5 is a floating point value (a number with a decimal point). That is
why we have to declare a data type float for a variable that holds the computed
value of an equation that involves a division (/) operation. Based on our
previous knowledge in mathematics, we come up with the equation:
ave--(q1+q2+q3)/3. This means that we need a background in basic
mathematics before we can successfully solve a given worded-problem in our
computer subject.

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:

Input Enter the Fahrenheit (f)


Process Compute the Celsius
(C=(5.0/9.0)”F-32.0) Output
Display the Celsius ( C )

Coding:

#include <stdio.h>
main{)

float c,f/ clrscr{);


printf(“\n Enter the F•ahrenheit:“)/
scanf(“•/»f“,&f};
c-(5.o/9.0)”f-32.0/
prinf(“\n The ceIsius:•/«f",c); getch();

Discussion:

Since integer division in C language truncates the resulting computed


value to zero, that is why it is safe to write the values in floating point form
(i.e. 5.0/9.0 or 32.0) and to declare the input variable needed in the equation
as float data type. This will result to a correct (untruncated) answer. So if you
13

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.

In our example about the average of three quizzes, we have three


%d%d%d because we have three variables: &q1, 8q2, 8q3. Remember that
we use the %d format when the variables scanned are declared as integer and
%/° when declared them as noat data type. The same also when we output
the value of these mentioned variable in an output statement printf( ) function.
Like the output of our example about “sum of the two input numbers“. We
format the output variable som as %d, and we format the output variable A
(area) as %/; this is because the variable sum was declared as integer, while
variable A (area) was declared as float.

We have to remember also that when we scanned our variables, we have


to write them preceded with the & (ampersand) symbol, otherwise our program
will behave differently; different from what we expected. In contrast, when we
print the output values of our variables, we must write the variables without
preceding it with ampersand (&) symbol. This too, would produce a different
output when we do. Again, different from what we expected. To make these
explanation clearer, we will have these examples:
14

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

i.Create a program to compute the volume of a sphere. Use the formula :


V=(4/3)”Or3 where 0 is equal to 3.1416 approximately. The r* is the
radius. Display the result.

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

4. Write a program that converts an input inch(es) into its equivalent


centimeters. Takenote that one inch is equivalent to 2.54 cms.

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.

6. Design a program to find the circumference of a circle. Use the formula:


C=2Or, where 0 is approximately equivalent to 3.1416.

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

9. Determine the most economical quantity to be stocked for each product


that a manufacturing company has in its inventory. This quantity, called
economic order quantity (EOQ) is calculated as follows:
= 2RS

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

"Hello, World! \n"

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

break Enum register typedef

case Extern return union


char Float short unsigned

const For signed void

continue Goto sizeof volatile

default If static while


do Int struct _Packed
double

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.

double A double-precision floating point value.

void Represents the absence of type.


Variable Declaration in C
A variable declaration provides assurance to the compiler that there exists a
variable with the given type and name so that the compiler can proceed for
further compilation without requiring the complete detail about the variable. A
variable declaration has its meaning at the time of compilation only, the
compiler needs actual variable declaration at the time of linking the program.
A variable declaration is useful when you are using multiple files and you define
your variable in one of the files which will be available at the time of linking of
the program. You will use the keyword extern to declare a variable at any
place. Though you can declare a variable multiple times in your C program, it
can be defined only once in a file, a function, or a block of code.
Example
Try the following example, where variables have been declared at the top, but
they have been defined and initialized inside the main function —
#include <stdio.h>

// 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

Multiplies both operands. A* B=


200

Divides numerator by de-numerator. B/A= 2


Modulus Operator and remainder of after an B O/o A
integer division. 0

++ Increment operator increases the integer value A++


by one. 11
Decrement operator decreases the integer value A-- = 9
by one.
21

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

-F= Add AND assignment operator. It adds the right C -‹-= A is


operand to the left operand and assign the equivalent
result to the left operand. to C = C
-I- A

Subtract AND assignment operator. It subtracts C -= A is


the right operand from the left operand and equivalent
assigns the result to the left operand. to C = C -
A

”= Multiply AND assignment operator. It multiplies C ”= A is


the right operand with the left operand and equivalent
assigns the result to the left operand. to C = C
” A

/= Divide AND assignment operator. It divides the C /= A is


left operand with the right operand and assigns equivalent
the result to the left operand. to C = C /
A

O/o = Modulus AND assignment operator. It takes C %= A is


modulus using two operands and assigns the equivalent
result to the left operand. to C = C
O/o A

Left shift AND assignment operator. C xx= 2


issame
as C = C
xa2
»= Right shift AND assignment operator. C > >= 2
is same
as C C
23

&= Bitwise AND assignment operator. C &= 2 is


same as C
=C&2
^= Bitwise exclusive OR and assignment operator. C ^= 2 is
same as C
= C” 2

= Bitwise inclusive OR and assignment operator. C | = 2 is


same as C

You might also like