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

C Programming Language2020

This document provides an overview of an introductory computer programming course taught in Somalia. It includes the course title, instructor information, academic year, and a table of contents that outlines the chapters to be covered. The chapters will introduce programming languages, C fundamentals, and various control structures like selection and looping.

Uploaded by

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

C Programming Language2020

This document provides an overview of an introductory computer programming course taught in Somalia. It includes the course title, instructor information, academic year, and a table of contents that outlines the chapters to be covered. The chapters will introduce programming languages, C fundamentals, and various control structures like selection and looping.

Uploaded by

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

East Africa University

Faculty of Engineering

Bosaaso, Somalia

Computer Programming

Using C

Mohamed Abdirahman Warsame

IT instructor

Academic Year: 2019/2020


Contents

Title Page

I. Introduction To Computer Programming Language

1.1: What Is Programming Language?

1.2: How Computer Programming Works?

1.3: Types Of Programming Languages

1.4: Introduction To C

II. C Fundamentals

2.1: First Program in C : Printing a Line of Text

2.2: Modifying Our First C Program

2.3: Variables, Data Types and Constants

.4: Another C Program: Adding Integers

2.5: Arithmetic

2.6: Equality And Relational Operators

III. Selection Control Structure

3.1: Simple If Selection

3.2: Double Selection Using If-Else

3.3: Nested If Selection


3.4: Multiple Selections Using Switch

IV. Looping Control Structure

4.1: While Statement

4.2: Do-While Statement

4.3: For Statement


Chapter 1:

Introduction to Computer programming Language

Objectives

In this chapter you will learn:

• Describe Program And Computer Programming


• Explain Structure Of Programming
• Steps In Program Development
• Programming techniques
• Introduce Types Of Programming Languages
• Which Programming Languages Are Most Widely Used?
Chapter 1:

Introduction to Computer programming Language

1.1: What Is Programming Language?

Programming language is an artificial language designed to express


computations that can be performed by a computer.

Programming languages can be used to create programs that control the


behavior of a computer.

A Computer Programming is simply a set of instructions which tell a computer


how to perform a particular task.

➢ A Computer Programmer :-
▪ is a person who translates the task you want a computer to do
▪ into a form that a computer can understand

1.2: How Computer Programming Works?

The original concepts of structured programming was set out in paper


published in 1964 in Italy, Bohm and Jacopini established the idea of designing
program using structure theorem based on three control structure. Numbers of
authors such as Edsger Dijkstra and Ninklaus Wirth have developed concepts
of structured programming further like top- down development and modular
design.
Structured Programming assists the programmer to write effective and error-
free programs. This term refers to a structured approach to program design
using techniques such as Top-down development and Modular design.

The Structured Theorem is based on three basic control structures; these


control structure are:

1. Sequences Of Instructions:

Here the program flows from one step to the next in strict sequence
2. Selection:

Here the program reaches a decision point and if the result of the test is true
then the program performs the instructions in Path 1, and if false it performs
the actions in Path 2. This is also known as a Conditional Construction because
the flow of the program is dependent on the result of the test condition.

3. Loops:

In this construct the program steps are repeated continuously until some test,
condition is reached, at which point control then flows past the loop into the
next piece of program logic.
Top-down Development

Top-down development – An approach to program development in which


progress is made by defining required elements in terms of more basic
elements, beginning with the required program and ending when the
implementation language is reached.

In top-down development of a program design, a general solution to the


problem is outlined first. This is then broken down gradually into more detailed
steps until finally the most detailed levels have been completed. It is only after
this process of stepwise refinement that the programmer starts to code. The
result of this systematic disciplined approach to program design is Higher
Precision programming
Modular Design

Structured Program also incorporates the concept of Modular Design which


involves grouping tasks together because they all perform the same function
(e.g. calculating sales tax or print report headings)

Here the program performs an identical sequence of actions several times.

For convenience these common actions are placed in a module, which is a kind
of mini-program which can be executed from within the main program. Other
names for such a module are Procedure or Function Modular design is
connected directly to top-down development, as the steps or subtasks which
the programmer breaks up the program solution into, will actually format the
future modules of the program. Good modular design also aids in the reading
and understanding of the program.
Common Features Of All Programs

Along with these structured programs a few more features are needed to make
them useful:

• Data because programs are written to process data so you must have a
good understanding of the nature and structure of Data
• Operations (add, subtract, compare etc.
• Input/Output capability (e.g. to display results)

Steps to Program Development

Programming can be defined as the development of a solution to an identified,


problem. There are seven basic steps in the development of a program:-

1. Define the Problem

This step (often overlooked) involves the careful reading and re-reading of the
problem until the programmer understands completely what is required. To
help with this initial analysis
2. Outline The Solution (Analysis)

Once the problem has been defined, the programmer may decide to break the
problem up into smaller tasks or steps and several solutions may be
considered.

✓ The major processing steps involved


✓ The major subtask (if any)
✓ The major variables and record structures
✓ The mainline logic

The solution outline often takes the shape of a hierarchy or structure chart.

3. Develop The Outline Into An Algorithm (Design)

Using the solution outline developed in step 2, the programmer then expands
this into

a set of precise steps (algorithm) that describe exactly the tasks to be


performed and the order in which they are to be carried out. This step can use
both structured programming techniques and pseudo code

4. Test The Algorithm For Correctness (Desk Check)

This step is one of the most important in the development of a program as is


often forgotten. Test data needs to be walked though each step in the
algorithm to check that the instructions described in the algorithm will actually
do what they are supposed to. If logic errors are discovered then they can be
easily corrected
5. Code The Algorithm Into A Specific Programming Language
(Coding)

It is only after all design considerations have been met that a programmer
should actually start to code the program. In preceding analysis it may have
been necessary to consider which language should be used, as each has its
own peculiarities (advantages and disadvantages).

6. Run The Program On The Computer (Testing)

This step uses a program compiler and test data to test the code for both
syntax and

logic errors. If the program is well designed then the usual time-wasting
frustration and despair often associated with program testing are reduced to a
minimum. This step will often need to be done several times until the
programmer is satisfied that the program is running as required,

7. Document And Maintain The Program (Documentation)

Program documentation should not be just listed as the last step in the
development process, as it is an ongoing task from the initial definition of the
problem to the final test results. Documentation also involves maintenance -
the changes that are made to a program, often by another programmer,
during the life of that program. The better a program has been documented
and the logic understood, the easier it is for another to make changes.
Programming technique

Some general useful programming techniques are pseudo code and algorithm,
flowcharts

1-Pseudocode is an artificial and informal language that helps


programmers develops general algorithms. Pseudocode is very similar to
everyday English.
2- Algorithm-: list of stapes of solution
3- Flowcharts: is a type of diagram that represents an algorithm or
process, showing the steps as boxes of various kinds, and their order by
connecting these with arrows. This diagrammatic representation can give
a step-by-step solution to a given problem. Process operations are
represented in these boxes, and arrows connecting them represent flow
of control
➢ A typical programming task can be divided into 2 phases:
▪ Problem solving phase
❑ produce an ordered sequence of steps that describe solution of
problem this sequence of steps is called an algorithm
▪ Implementation phase
❑ implement the program in some programming language
➢ Steps in Problem solving
▪ First produce a general algorithm (You can use pseudocode)
▪ Refine the algorithm successively to get step by step detailed
algorithm that is very close to a computer language.
Example 1:
▪ Write an algorithm to determine the students final grade and indicate
weather it is passing or failing. The final grade is calculated as the average
of four marks.

Solution:
Pseudocode: Input a set of 4 marks
Calculate their average by summing and dividing by 4
if average is below 50
Print “FAIL”
else
Print “PASS”

Detailed Algorithm: Step 1: Input M1, M2,M3,M4


Step 2: GRADE = (M1+M2+M3+M4)/4
Step 3: if (GRADE <50) then

The Flowchart Print “FAIL”

➢ Easier to convey ideas by picture than


else by words
▪ shows logic of an algorithm Print “PASS”
▪ emphasises individual steps and their interconnections
❑ e.g. control flow from one action to the next
▪ standard flowchart symbols are shown below
Example 2:
Write an algorithm to determine the students final grade and indicate weather
it is passing or failing. The final grade is calculated as the average of four
marks.
Pseudocode: Input a set of 4 marks
Calculate their average by summing and dividing by 4
if average is below 50
Print “FAIL”
else
Print “PASS”

Detailed Algorithm: Step 1: Input M1, M2,M3,M4


Step 2: GRADE = (M1+M2+M3+M4)/4
Flowchart: Step 3: if (GRADE <50) then
Print “FAIL”
Else Print “PASS”
TRACE TABLE:

MARK GRADE STATUS

M1=80 80
START
M2=30 + 30

M3=40 + 40
Input
M1,M2,M3,M4 M4=30 + 30 /4

= 45 FAIL

GRADE=(M1+M2+M3+M4)/4

N If
Y
GRADE<50

PRINT PRINT

“PASS” “FAIL”

STOP
Example 3: Write an algorithm and draw a flowchart to convert the length in
feet to centimeter.

Pseudocode: Input the lenght in feet (Lft)

Calculate the length in cm (Lcm) by multiplying LFT with 30

Print LCM

Algorithm: Step 1: Input Lft

Step 2: Lcm = Lft x 30

Step 3: Print Lcm

Flowchart:
START

Input
Lft

Lcm = Lft x 30

Print

Lcm

STOP
Example 3: Write an algorithm and draw a flowchart that will read the two
sides of a rectangle and calculate its area.

Pseudocode: Input the width (W) and Length (L) of a rectangle

Calculate the area (A) by multiplying L with W

Print A

Algorithm: Step 1: Input W,L

Step 2: A=L x W

Step 3: Print A

Flowchart: START

Input
W, L

A=LxW

Print

STOP
1.3: Types Of Programming Languages

Programmers write instructions in various programming languages, some


directly understandable by computers and others requiring intermediate
translation steps. Hundreds of computer languages are in use today. These
may be divided into three general types:

1. Machine Languages

2. Assembly Languages

3. High-level Languages

1. Machine Languages

Any computer can directly understand only its own machine language. Machine
Language is the "natural language" of a computer and as such is defined by its
hardware design. Machine language is often referred to as Object Code or
Binary Languages.

Machine Language is a collection of binary digits or bits that the computer


reads and interprets.

Machine-Language Programming was simply too slow, tedious and error-prone


for most programmers; the very first programmers actually had to enter the
binary codes themselves, this is known as Machine Code Programming and is
incredibly difficult
2. Assembly Languages

Sometimes referred to as Assembly or ASL, an Assembly Language is the Low-


level

Programming Language designed for a specific processor. Assembly language


uses

structured commands as substitutions for numbers allowing humans to read


the code more easily than looking at binary. Although easier to read than
binary,

Programmers using English-like abbreviations to represent elementary


operations. These abbreviations formed the basis of assembly languages.
Translator programs called assemblers were developed to convert early
assembly-language programs to machine language at computer speeds. The
following section of an assembly-language program also adds overtime pay to
base pay and stores the result in gross pay:

load basepay add overpay store grosspay

Although such code is clearer to humans, it is incomprehensible to computers


until translated to machine language.

3. High-level languages

To speed the programming process, High-level Languages were developed in


which single statements could be written to accomplish substantial tasks.
Translator programs called Compilers convert high-level language programs
into machine language. High-level languages allow programmers to write
instructions that look almost like everyday English and contain commonly used
mathematical notations. A payroll program written in a high-level language
might contain a statement such as

grossPay = basePay + overTimePay;

From the programmer's standpoint, obviously, high-level languages are


preferable to machine and assembly language. C, C++, Microsoft's .NET
languages (e.g., Visual Basic

.NET, Visual C++ .NET and C#) and Java are among the most widely used
high-level programming languages.

The process of compiling a high-level language program into machine


language can take a considerable amount of computer time. Interpreter
programs were developed to execute high-level language programs directly,
although much more slowly. Interpreters are popular in program development
environments in which new features are being added and errors corrected.
Once a program is fully developed, a compiled version can be produced to run
most efficiently
➢ Types of programming errors
▪ Syntax of a programming language is the set of rules to be followed
when writing a program
▪ syntax error occurs when these rules are violated
▪ run-time errors occur when invalid data is entered during program
execution
❑ e.g. program expects numeric data and alphabetic data is entered
program will crash
▪ logic error will not stop the program but results will be inaccurate
▪ The process of finding and correcting errors in a program is called
debugging

Types of High-level Language

The common types of High-level Language are

1- Procedure oriented programming language (pop)

2- Object oriented programming language (OOP)

The Concepts Of Procedure Oriented Programming (POP) Are As Follows:

1. Main program is divided into small parts depending on the functions.

2. The Different part of the program connects with each other by parameter
passing & using operating system.

3. Every function contains different data.

4. Functions get more importance than data in program.

5. Most of the functions use global data.


6. Same data may be transfer from one function to another

7. There is no perfect way for data hiding.

8. Functions communicate with other functions maintaining as usual rules.

9. add new data in program user should be ensure that function allows it.

10. Top down process is followed for program design.

11. The popular. Example for pop languages are : Pascal, Fortran and C

The Concepts Object Oriented Programming (OOP ) Are As Follows :

1. Main program is divided into small object depending on the problem.

2. Functions of object linked with object using message passing.

3. Data & functions of each individual object act like a single unit.

4. Data gets more importance than functions in program.

5. Each object controls its own data.

6. Data does not possible transfer from one object to another.

7. Data hiding possible in OOP which prevent illegal access of function from
outside of it. This is one of the best advantages of OOP also.

8. One object link with other using the message passing.

9. More data or functions can be added with program if necessary. For this
purpose full program need not to be change.

10. Message passing ensures the permission of accessing member of an object


from other object.
11. Bottom up process is followed for program design.

The popular. Example for Object Oriented Programming (OOP ):


C++,Java.
1.4: Introduction To C

Early History Of C

C evolved f from two previous programming languages, BCPL and B.


BCPL(Basic Combined Programming Language) was developed in 1967 by
Martin Richards of the University of Cambridge as a language for writing
operating-systems software and compilers for operating systems. Ken
Thompson modeled many features in his language B after their counterparts in
BCPL and used B i to create early versions of the UNIX operating system at
Bell Laboratories in 1970.

The C ((pronounced "See")) language was evolved from B by Dennis Ritchie at


Bell Laboratories in 1972, C uses many important concepts of BCPL and B. C
initially became widely known as the development language of the UNIX
operating system. Today, most operating systems are written in C and/or C ++
In 1978, Kernighan and Ritchie wrote a book entitled 'The C Programming
Language' that became the language definition for almost a decade

C Standards

The American National Standards Institute (ANSI) formed a committee in 1983


to

establish a standard definition of C. This committee approved a version of C in


1989 which is known as ANSI C. With few exceptions, every modern C
compiler has the ability to adhere to this standard. ANSI C was then approved
by the International Standards Organization (ISO) in 1990. The C language is
so named because its predecessor was called B.
Features Of C

Program written in c are very efficient and fast. This is due to its variety
of data types and powerful operators.

C is a powerful and flexible language which helps system developers to


deliver

various complex tasks with ease.

C is popular among professional programmers for programming, as a


result, a wide variety of C compilers and helpful accessories are available.

A C program is basically a collection of various function supported by C


library (also known as header files). We can also add our own functions to the
C library. These functions can be reused in other applications or programs by
passing pieces of information to the functions, you can create useful, reusable
code.

Writing C program with user-defined functions makes program more simple


and easy to understand. Breaking a problem in terms of functions makes
program debugging, maintenance and testing easier. As these features shows
that C is an excellent choice for your first programming language and today it
is widely used throughout the world in many educational institutions.

C Standard Library

C programs consist of pieces called functions. You can program each piece that
you
may need to form a C program. However, most C programmers take
advantage of the rich collections of existing functions called the C Standard
Library. Thus, there are really two parts to learning the C, The first is learning
the C language itself; the second is learning how to use the functions in the C
Standard Library.

Typical C Development Environment

Let's consider the steps in creating and executing a C application using a C


development environment. C systems generally consist of several parts: a
program development environment, the language and the C Standard Library.
C programs typically go through six phases to be executed the are: edit,
preprocess, compile, link, load and execute.

Phase 1: Creating A Program

Phase 1 consists of editing a file with an editor program (normally known


simply as an editor). You type a C program (typically referred to as source
code) using the editor,make any necessary corrections and save the program
on a secondary storage device, such as your hard drive. C source code file
names often end with the .C extensions (note that C is in uppercase) which
indicate that a file contains source code.The editor program for Microsoft
Windows such as Borland C++ (www.borland.com), and Microsoft Visual C++
(www.msdn.microsoft.com/visualc/) have editors integrated into the
programming environment. You can also use a simple text editor, such as
Notepad in Windows, to write your C++ code. I have been using Turbo C++
compiler for this purpose. Why Turbo C++ compiler why not Turbo C
compiler? Because Turbo

C++ compiler supports both C & C++ program and if you want to learn C++,
you don‟t need to change your compiler.

Phases 2 and 3: Preprocessing And Compiling A C Program

In phase 2, the programmer gives the command to compile the program.( Alt
+ F9 to

compile) In a C system, a preprocessor program executes automatically before


the compiler's translation phase begins (so we call preprocessing phase 2 and
compiling phase 3). The C preprocessor obeys commands called preprocessor
directives, which indicate that certain manipulations are to be performed on
the program before compilation.. In phase 3, the compiler translates the C++
program into machine- language code (also referred to as object code).

Phase 4: Linking

A linker links the object code with the code for the missing functions to
produce an executable image (with no missing pieces). If the program
compiles and links correctly, an executable image is produced.
Phase 5: Loading

Phase 5 is called loading. Before a program can be executed, it must first be


placed in memory. This is done by the loader, which takes the executable
image from disk and transfers it to memory. Additional components from
shared libraries that support the program are also loaded.

Phase 6: Execution

Finally, the computer, under the control of its CPU, executes the program one
instruction at a time.

NOTE:

Programs do not always work on the first try. Each of the preceding phases
can fail because of various errors; This would cause the C program to display
an error message. If this occurs, you would have to return to the edit phase,
make the necessary corrections and proceed through the remaining phases
again to determine that the corrections fix the problem(s).
Chapter 2:

C Fundamentals

Objectives

In This Chapter You Will Learn:

To Write Simple Computer Programs In C.

To Write Simple Input And Output Statements.

Understand Haw To Use Fundamental Data Types.

Describe Arithmetic Operators.

The Precedence Of Arithmetic Operators.

To Write Simple Decision-Making Statements.

Outline

2.1: First Program In C : Printing A Line Of Text

2.2: Other program with more output

2.3: Variables, Data Types And Constants

2.4: Another C Program: Adding Integers

2.5: Arithmetic

2.6: Equality And Relational Operators


2.1: First Program In C : Printing A Line Of Text

The best way to get started with C is to actually look at a program.

This simple program that prints a line of text We consider each line in detail.

Example 1

#include<stdio.h> /* allows program to output data to the screen*/

void main() /* function main begins program execution*/

printf("Welcome to C programming language");/* display message*/

} /* end function main*/


Lets understand each and every line of this program.

The very first line #include<stdio.h> (standard input / output header file)
tells the compiler to include a header file “stdio.h” in the program. Header file
contains information and declaration used by the compiler when compiling
standard input/output library functions. Here we are using printf() from stdio.h
header file.

The next line is void main() which is the beginning of the program. Every
program must have a main() because program starts execution from this
function. But what does the keyword void means before the main(). This
means that main function will not return any value to the compiler, The
parentheses following main() indicate that no parameters or arguments are
passed on to this function; The left brace, {,must begin the body of every
function. A corresponding right brace }, must end each function's body.

printf("Welcome to C"); printf is the one of functions defined in stdio.h


whose job is to print message specified in double quotation. At the end of the
line there is a semicolon (;) which is the end of that statement. Every C
statement must end with a semicolon (also known as the statement
terminator).
2.2: other C program with more out put

Our first C Program was a successful one, so for now let us try to modify or
change some of the contents of our program

Example:

#include<stdio.h>

#include<conio.h>

void main()

clrscr();

printf("Welcome to C. ");

printf("C is a Programming Language. ");

printf("Hello! How are you?");

getch();

Output

Welcome to C. C is a Programming Language. Hello! How are you?

The top two lines include two header files “stdio.h” and “conio.h” respectively.
The “stdio.h” header file contains “printf()” and “conio.h” file
(CONsoleInputOutput)contains “clrscr()” and “getch()”. The “clrscr()” clears
the output screen means any output shown by previously run program will be
erased and that why we always put them at the beginning. Next is three
“printf()” statements which will print three different messages. The “getch()”
waits for a keyboard input and if we press any key on keyboard the program
exits. So we don‟t need to press Alt + F5 to see the output as we did in above
program.

Example:

*Printing multiple lines of text with a single statement.*/

#include <stdio.h>

#include<conio.h>

void main()

printf(“welcome \n To \n C \n \t Language”) ;

getch() ;

Output Welcome To C Language

The one printf can print several lines by using new line character

The characters of the right operand normally print exactly as they appear
between the double quotes. Notice, however, that the characters \n are not
printed on the screen. The backslash (\) is called an escape character

Indicates that a "special" character is to be output. When a backslash is


encountered n a string of characters, the next character is combined with the
backslash to form an escape sequence.
The escape sequence \n means new line. It causes the cursor (i.e., the current

screen-position indicator) to move to the beginning of the next line on the


screen. Some other common escape sequences are listed in Table .

Escape Description
sequence
\n New line. Position the screen cursor to the
beginning of the next line.
\t Horizontal tab. Move the screen cursor to the
next tab stop.
\a Alert. Sound the system bell.
\\ Backslash. Used to print a backslash character.
\' Single quote. Use to print a single quote
character.
\" Double quote. Used to print a double quote
character
2.3: Variables, Data Types And Constants

Data is stored in a computer's memory. The memory system comprises of


uniquely numbered cells called memory addresses. We need to know the
address where something is stored in order to retrieve it and work on it. A
programming language frees us from keeping track of these memory
addresses by substituting names for them. These names are called variables.
Variables are descriptive names for the memory addresses.

Before we use a variable in C we must declare it. We must identify what kind
of information will be stored in it. This is called defining a variable .Variables
must be declared at the start of any block of code, but most are found at the
start of each function. A variable must be defined to be one of the legal C data
types . When a variable is defined it is not automatically initialized, it is the
responsibility of the programmer to initialize this to a start value.

Variable Names

All variable definitions must include two things variable name and its data
type.Some rules to be followed in naming a variable in C are

a. It must start with an alphabet and can contain letter, underscores and
digits. Both uppercase and lowercase letters can be used.

b. Spaces should not be used in a variable name.

c. Certain keywords like int, float, struct, if, while cannot be used as variable

names.

d. The variable names should not be very long and one should refer to the
documentation of the C compiler to know the limitation. Generally the first
eight 8 characters of a variable name are significant

e. C is case sensitive uppercase and lowercase letters are different, so a1 and


A1 are different identifiers

Note:

I. C allows identifiers of any length, but. Use identifiers of 31 characters or

fewer to ensure portability and can avoid some programming error s

II. The variable names should be meaningful and denote what the variable
stores. As far as possible
Data Types in C Language

A programming language is proposed to help programmer to process certain kinds


of data and to provide useful output. The task of data processing is accomplished
by executing series of commands called program. A program usually contains
different types of data types (integer, float, character etc.) and need to store the
values being used in the program. There are only a few basic data types in C

1. Integer types:

Integers are whole numbers with a range of values, range of values are machine
dependent. Generally an integer occupies 2 bytes memory space and its value
range

limited to -32768 to +32768

C has three classes of integer storage namely short int, int and long int. All three
data types have signed and unsigned forms.

Syntax: int variable name; like

int num1;

short int num2;

long int num3;


Example: 5, 6, 100, 2500.

/*Program to declare an integer variable i and then set it to be

20*/

#include<stdio.h>

void main()

int i = 20;

printf("This is my integer: %d \n", i);

Output:

This is my integer: 20

2. Floating Point Types:

The float data type is used to store fractional numbers (real numbers) with 6 digits
of precision. Floating point numbers are denoted by the keyword float. When the
accuracy of the floating point number is insufficient, we can use the double to
define the number. The double is same as float but with longer precision and takes
double space (8 bytes) than float. To extend the precision further we can use long
double which occupies 10 bytes of memory space.

Syntax: float variable name; like

float num1;

double num2;

long double num3;


Example: 9.125, 3.1254.

#include <stdio.h>

void main()

Float f = 3.1415;

printf("This is my float: %f \n", f);

Output

This is my float: 3.1415

3. Character Type:

Character type variable can hold a single character. As there are singed and
unsigned

int (either short or long), in the same way there are signed and unsigned chars;
both occupy 1 byte each, but having different ranges. Unsigned characters have
values between 0 and 255, signed characters have values from –128 to 127.

Syntax: char variable name ; like

char ch = „a;
Example: a, b, g, S, j. z

/* Program to declare a character variable d and then set it to be

'd' */

#include <stdio.h>

void main()

char c;

c = 'd';

printf("This is my character: %c \n", c);

Output

This is my character: d
Example

#include<stdio.h>

#include<conio.h>

main()

char itemname[15];

int units;

float price,total;

clrscr();

printf("Enter the Item name: "); scanf("%s",itemname); printf("Enter Item price:


"); scanf("%f",&price);

printf("Enter the units: "); scanf("%d",&units); total=price*units;


printf("Total=US$ %.2f",total); getch();

Output

Enter the Item name: (user input)

Enter Item price: (user input) Enter the units: (user input)

Total=Us$ .00 (depends on the previous user inputs)


Data Types in C, Size & Range of Data Types
Note

Void Type: The void type has no values therefore we cannot declare it as
variable as

we did in case of integer and float.

The void data type is usually used with function to specify its type. Like in our
first C

program we declared “main ()” as void type because it does not return any
value.

Input / Output Instructions:

This type of instruction are used to reading the data and used to display the
results, You can print all of the normal C types with printf by using different
placeholders:

int (integer values) uses %d

float (floating point values) uses %f

char (single character values) uses %c

26
Scanf

The scanf function allows you to accept input from standard in, which for us is
generally the keyboard.

The simplest application of scanf looks like this:

scanf("%d", &b);

The program will read in an integer value that the user enters on the keyboard
(%d is for integers, as is printf, so b must be declared as an int) and place that
value into b.

The scanf function uses the same placeholders as printf:

int uses %d float uses %f char uses %c

Ex: scanf(“%d%d”, &a, &b)

In the above example a, b are variables. At the run time we have to store
some values in to that variables. a, b are integer variables.

Note

You MUST put & in front of the variable used in scanf. when you forget it your

program will almost always crash when you run it

27
2.4: Another C Program: Adding Integers

/*Addition program that displays the sum of two numbers.*

#include <stdio.h> /* allows program to perform input and output*/

#include<conio.h>

main()

/* variable declarations*/

int number1; /* first integer to add */

int number2; /* second integer to add */

int sum; /* sum of number1 and number2*/

/*Accepting input from the user*/ printf( “ enter first number \n”) ;
scanf(“%d”,&number1) ;

printf( “ enter second number \n”) ; scanf(“%d”,&number2) ;


sum=number1+number2;

printf(“sum is %d\n”,sum);

getch() ;

28
Constant:

Constant is the quantity. It takes one location in memory. During the

Execution we cann‟t change this quantity. That is known as constant.

Ex: x=25, here 25 is constant.This value will not change in a program

A user using a program having constants cannot change the constants when
the program is executing

There are three ways for defining a constant in C. First method is by using
#define statements.

#define statement is a preprocessor directive . It is used to define constants as


follows :

#define TRUE 1

#define FALSE 0

#define PI 3.1415

Wherever the constant appears in a program, the preprocessor replaces it by


its value.

The second method is by using the const keyword in conjunction with a


variable declaration.

const float PI = 3.1415;

29
Here, the compiler will throw an error whenever the variable PI declared as a
constant is assigned a new value

The third method is by using enumerated data type. This data type is initiated
by the keyword enum, immediately after the keyword enum is the name of the
variable, followed by a list of values enclosed in curly braces. This defines a set
of constants. Hence eliminates the usage of multiple #define statements

enum answer {FALSE, TRUE};

/* Program to show using #define to declare constants */

#include<stdio.h>

#define TRUE 1

#define FALSE 0

#define PI 3.1415

void main()

printf("This is TRUE as an integer: %d \n", TRUE);

printf("This is FALSE as an integer: %d \n", FALSE); printf("This is PI as an


integer: %d \n", PI); printf("This is PI as a float: %.4f \n", PI);

}
30
Keyword:

Keyword is having special meaning. We have to use this one for special

Purpose. C compiler can recognize this word.

The following list shows all the ANSI defined C keywords.....

auto break case char const continue default do

double else enum extern float for goto if

int long register return short signed sizeof static

struct switch typedef union unsigned void volatile while

31
Operators in C

2.5: Arithmetic Operators

C has a wide range of operators. An arithmetic expression is composed of


operators

and operands. Operators act on operands to yield a result. Commonly used


arithmetic operators are +, -, *, / and %.

The plus sign (+) is used to add two values, the minus sign (-) to subtract one
value from another, the asterisk(*) to multiply two values, the division (/) to
divide a value and the modulus (%) to obtain the reminder of integer division.
These are known as binary operators since they operate on two values or
variables. Table 2.4 summarizes the C arithmetic operators.

C Operation C Arithmetic Operator Algebraic Expression C Expression


Addition + f+7 f+7
Subtraction - pc p-c
Multiplication * bm or b · m b*m
Division / x/y
Modulus % r mod s r%s

32
Note:

Arithmetic expressions in C must be entered into the computer in straight-line


form. Thus, expressions such as "a divided by b" must be written as a / b, so
that all constants, variables and operators appear in a straight line.

Example

/* Usage of various arithmetic operators */

#include <stdio.h>

main()

int var1 = 10; int var2 = 2; int var3 = 35; int var4 = 8; int result;

result = var1 + var2;

printf("Sum of var1 and var2 is %d\n", result);

result = var3 * var3;

printf("Square of var3 is %d\n", result);

result = var2 +var3 * var4; /* precedence */

printf("var2 + var3 * var4 =%d\n", result);

33
Rules of Operator Precedence

C applies the operators in arithmetic expressions in a precise sequence


determined by

the following rules of operator precedence, which are generally the same as
those followed in algebra:

1. Operators in expressions contained within pairs of parentheses are evaluated


first. Thus, parentheses may be used to force the order of evaluation to occur in
any sequence desired by the programmer. Parentheses are said to be at the
"highest level of precedence." In cases of nested, or embedded, parentheses,
such as

((a+b)+c)

the operators in the innermost pair of parentheses are applied first.

2. Multiplication, division and modulus operations are applied next. If an


expression contains several multiplication, division and modulus operations,
operators are applied from left to right. Multiplication, division and modulus are
said to be on the same level of precedence.

3. Addition and subtraction operations are applied last. If an expression


contains several addition and subtraction operations, operators are applied from
left to right. Addition and subtraction also have the same level of precedence.

34
Precedence Of Arithmetic Operators.

Operator(S) Operation(S) Order Of Evaluation (Precedence)

() Parentheses Evaluated first. If the parentheses are nested, the


expression in the innermost pair is evaluated first. If
there are several pairs of parentheses "on the same
level" (i.e., not nested), they are evaluated left to right.

* Multiplication Evaluated second. If there are several, they are


/ Division evaluated left to right.
% Modulus

+ Addition Evaluated last. If there are several, they are evaluated


- Subtraction left to right

35
Example:

//Program that shows how to substract 2 numbers.//

#include<stdio.h>

main()

int x,y,z;

printf("Enter x, y values \n");

scanf("%d%d", &x, &y);

z=x-y;

printf("The result is :%d",z);

36
//Program that shows how to multiply 2 numbers.//

#include<stdio.h>

main()

int p,q,r;

printf("Enter 2 numbers for P and q\n");

scanf("%d%d",&p,&q);

r=p*q;

printf("The multiply result is : %d",r);

//Program that shows how to devide 2 numbers.//

#include<stdio.h>

main()

float a,b,c;

37
clrscr();

printf("Enter a, b values\n");

scanf("%f%f",&a,&b);

c=a/b;

printf("The result is : %f", c);

/* Modulus operator */

#include <stdio.h>

main()

int x = 25, y=10, z;

z = x % y;

printf ("x %% y is %d\n", z);

38
2.6: Equality and Relational Operators

Relational and Logical Operators

The relational operators are

> >= < <=

They all have the same precedence. Just below them in precedence are the
equality operators:

== !=

Note:

Relational operators have lower precedence than arithmetic operators

A simple relational expression contains only one relational operator and takes the
following form. exp1 relational operator exp2

Relational expressions are used in decision making statements of C language


such as if, while and for statements to decide the course of action of a running
program.

39
Relational operators in C are in Table

Standard Algebraic Equality


Or Relational Operator

Relational Operators
Equality Or Sample C Meaning Of C
> > x>y x is greater than
Condition Condition
Relational Operator y
< < x<y x is less than y
>= x >= y x is greater than
or equal to y
<= x <= y x is less than or
equal to y
Equality Operators
= == x == y x is equal to y
!= x != y x is not equal to
y

40
Logical Operators

C has the following logical operators; they compare or evaluate logical and
relational

expressions.

Symbol Name
&& Logical

|| Logical OR
AND```````````
! Logical NOT

Logical AND (&&)

This operator is used to evaluate 2 conditions or expressions with relational

operators simultaneously. If both the expressions to the left and to the right of
the logical operator is true then the whole compound expression is true.

Example

a > b && x = = 10

The expression to the left is a > b and that on the right is x == 10 the whole

expression is true only if both expressions are true i.e., if a is greater than b
and x is equal to 10.
41
Logical OR (||)

The logical OR is used to combine 2 expressions or the condition evaluates to

true if any one of the 2 expressions is true.

Example

a < m || a < n

The expression evaluates to true if any one of them is true or if both of them
are true. It evaluates to true if a is less than either m or n and when a is less
than both m and n.

Logical NOT (!)

The logical not operator takes single expression and evaluates to true if the

expression is false and evaluates to false if the expression is true. In other

words it just reverses the value of the expression.

For example

! (x >= y) the NOT expression evaluates to true only if the value of x is neither

greater than or equal to y

42
Example

/*using if statements, relational operators and equality


operators*/

#include <stdio.h>

int main()

int num1; /* first integer to compare */

int num2; /* second integer to compare */

printf( "enter two integers, and I will tell you \n") ; printf("the relationships
they satisfy:\n "); scanf("%d%d", &num1,&num2);

if(num1==num2)

printf("%d is equel to %d\n",num1&num2);

else if(num1!=num2)

printf("%d is not equal to %d\n", num1,num2) ;

else if(num1<num2 )

printf("%d is less then %d\n", num1,num2) ;

else

if (num1>num2)

printf("%d is greater then %d\n", num1,num2) ;


43
else

if(num1 <=num2)

printf("%d is less then or equal to %d\n", num1,num2) ;

else

if (num1 >=num2)

printf("%d is greater then or equal to %d\n", num1,num2) ;

return 0 ;

44
Chapter Three:

Selection Control Structure

Objectives:

In This Chapter You Will Learn:

Describe Selection Control Structure

To Write Simple If Selection Control Structure

To Be Able To Use If…Else Selection

To Understand Haw To Use Nested If

To Understand Multiple Selection Using Switch Selection

Haw To Use Logical Operators And Relational Operators.

Outline:

3.1: Simple If Selection

3.2: Double Selection Using If-Else

3.3: Nested If Selection

3.4: Multiple Selections Using Switch


Selection Control Structure

The selection control structure allows one set of statements to be executed if a


condition is true and another set of actions to be executed if a condition is
false.

A selection structure is flowcharted as follows:

If Statement

To conditionally execute statements, you can use the if for three forms :

1- simple selection if statement

2- if...else statement.

3- Nested if .. else statements

3.1: Simple If Selection

The general form of the if statement is

If (expression)
{

s1 ;

s2 ;

....

Expression is a Boolean Expression that returns true (nonzero) or false (zero).

Example:

#include <stdio.h>

main()

int age;

printf("please enter your age ");

scanf("%d",&age);

if(age >=15)

printf(" you are adult ");

}
Example:

/* One way selection -To enter a number and print that if that is more than
100*/

#include<stdio.h>

#include<conio.h>

main()

int no;

clrscr();

printf("Enter the number : ");

scanf("%d",&no);

if(no>100)

printf("The number you have entered=%d",no);

printf("\nThanks for following the condition.");

getch();

3.2: Double Selection Using If-Else

The general format for an if-else statement is


if (condition)

{ simple or compound statement;

else

simple or compound statement;

Example:

#include <stdio.h>
void main()
{
int i = 5;
if(i > 0)
{
printf(" i > 0. \n");
}
else
{
printf(" i < 0. \n");
}
}

Example:
#include <stdio.h>

main()

int age ;

printf("please enter your age ");

scanf("%d",&age);

if(age >=15)

printf(" you are adult ");

else

printf(" you are child ");

}
Example:

/* To enter any two numbers and find the greatest */

#include<stdio.h>
#include<conio.h>
main()
{
int no1,no2;
clrscr();
printf("Enter the two numbers :"); scanf("%d%d",&no1,&no2); if(no1>no2)
printf("%d is the greatest",no1);
else
printf("%d is the greatest",no2);
getch();
}
Example:

/* To enter a number and check that is positive or negative */

#include<stdio.h>

#include<conio.h>

main()

int no;

clrscr();

printf("Enter the number :");

scanf("%d",&no);

if(no>0)

printf("%d is a positive number.",no);

else

printf("%d is a negative number.",no);

getch();

}
Example:

/* To enter an alphabet and check whether that is a consonant or


vowel */

#include<stdio.h>

#include<conio.h>

main()

char al;

clrscr();

printf("Enter the alphabet :");

scanf("%c",&al);

if(al=='a' || al=='e' || al=='i' || al=='o' || al=='u')

printf("The alphabet is vowel.");

else

printf("The alphabet is a consonant.");

getch();

}
3.3: Nested If Selection

Nested If Selection is one If Condition inside another If Condition. Here we


have two ways to implement Nested-If.

1. By joining more than one condition inside one If Condition using

" && " and symbol in C.

Example:

if(sub1>=50 && sub2>=50 && sub3>=50)

2. By implementing if condition line by line..

Example: if(sub1>=50) if(sub2>=50) if(sub3>=50)

Example:

#include<stdio.h>

main()

int sno,sub1,sub2,sub3,total;

char name[10];

float avg;

printf("Enter the student No, name\n");

scanf("%d %s",&sno, &name);

printf("\nEnter the 3 subjects marks\n");

scanf("%d %d %d", &sub1, &sub2, &sub3); printf("\n\n");


total=sub1+sub2+sub3;

avg=total/3;

printf("\nThe Student Informatin is...\n");

printf("\nThe Student Number is %d:", sno);

printf("\nThe Student Name is %s:", name);

printf("\n\nThe Student Total marks is %d:", tot);

printf("\n\nThe Student Avg Marks is %f:", avg);

printf("\n");

if(sub1>=50 && sub2>=50 && sub3>=50)

printf("\nThe Result is Pass");

else

printf("\nThe Result is Fail...\n");

}
Example:

/* to enter any 3 numbers and find the greatest */

#include<stdio.h>

#include<conio.h>

main()

int no1,no2,no3;

clrscr();

printf("Enter the 3 numbers \n"); scanf("%d%d%d",&no1,&no2,&no3);

if(no1>no2 && no1>no3)

printf("%d is the greatest",no1);

else if(no2>no1 && no2>no3)

printf("%d is the greatest",no2);

else

printf("%d is the greatest",no3);

}
getch();

Example:

/* If statement: compare the value from user input */

#include <stdio.h>

int main(void)

int number = 0;

printf("\nEnter an integer between 1 and 10: ");

scanf("%d",&number);

if (number > 5)

printf("You entered %d which is greater than 5\n", number);

if (number < 6)

printf("You entered %d which is less than 6\n", number);

return 0;

}
3.4: Multiple Selections Using Switch

By selecting a 'case' we will execute the statements which belongs to the


case, when it finished printing the same statements one break breaks the
program up to that point and program will end.

Case and break

Syntax:

switch(variable)

case 1: statemetns; break;

casse 2: statement ; break ; default: statement

Example:

/* Program that shows to select the color */

#include<stdio.h>

main()

int no;

printf("Enter 1 yo 4 numbers to display the name of the color\n");

scanf("%d", &no);

switch(no)

case 1:
printf("\n The color is RED...");

break;

case 2:

printf("\n The color is Blue...");

break;

case 3:

printf("\n The color is BLACK...");

break;

case 4:

printf("\n The color is YELLO...");

break;

default:

printf("\nThere is no color stored in this no.. Plse try again..");

}
Chapter Four:

Looping Control Structure

Objectives:

In This Chapter You Will Learn:

Construct Programs Loop Control Structure

Describe Looping Control Structure

Write Efficient Program For Loop

To Use Common Statement For Repetition

To Be Able To Use While Statement

To Understand Haw To Use Do... While

To Understand For Statement

Outline:

4.1: While Statement

4.2: Do-While Statement

4.3: For Statement

4.4: Assignments
Looping Control Structure:

1. While

2. Do-While

3. For

4.1: While Statement

It is looping control instruction. It has one starting point, one condition(ending


point), and increment or decrement arithmetic operator.

A repetition statement (also called a looping statement or a loop) allows the


programmer to specify that a program should repeat an action while some
condition remains true.

Syntax:

varible initialization; / Starting point while(expression) / Ending Point

statement ;

increment / decrement operator;

}
Increment/Decrement Arithmetic Operator:

Increment = ++ sign shows Increment operator. It adds one value to the


previous value.

Example :

i =9;

i++;

i++ means i = i+1;

i =9+1;

i = 10;

Decrement = -- sign shows Decrement operator. It removes one value from


the previous value.

Example:

i =9;

i--;

i-- means i = i-1;

i =9-1;

i = 8;
Example:

/* Write a program to print a statement 10 times on the screen */

#include<stdio.h>

#include<conio.h>

main ()

int i=1; /* intialization */

clrscr();

while(i<=10) /* condition with end point */

printf("in the name of allah .\n");

i++; /* incremrnt */

getch();

}
Example:

/* to print the numbers from 1 to 100 by sing while loop */

#include<stdio.h>

#include<conio.h>

main()

int i=1;

clrscr();

while(i<=100)

printf("%d\t",i);

i++;

getch();

}
Example:

//Program that shows how to print 1-100 even numbers using while

loop//

#include<stdio.h>

main()

int i=2;

while(i<=100)

printf(“%d\n”, i);

i=i+2;

Example:

//Write a program to print 20-1 even numbers using while loop//

#include<stdio.h>

main()

int i=20;

while(i>=1)

printf(“%d\n”, i);
i=i-2;

Example:

/* To enter a number and print its factors like :

factors of 10 are 1,2 and 5

factors of 12 are 1,2,3,4,6 */

#include<stdio.h>

#include<conio.h>

main()

int no,i=1;

clrscr();

printf("Enter the number :");

scanf("%d",&no);

printf("the factors of %d are ",no);

while(i<no)

{ if(no%i==0) printf("%d\t",i); i++;

getch();

}
4.2: Do-While Statement:

In while loop first it checks the condition then it prints the value. But in do-
while first it prints the value and it checks the condition.

Syntax:

do

statements;

increment / decrement

while(expression);

Example:

/* Program that shows to print 1- 10 numbers using do-while */

#include<stdio.h>
main()
{
int i=1;
do
{
printf("%d\n", i);
i++;
}
While (i<=100);
}
Example:

// Write a program to print all even numbers from 1 to 100

#include<stdio.h>

#include<conio.h>

main()

int i=1;

clrscr();

printf("All even numbers from 1 to 100 are: -\n");

do

if(i%2==0) /* if reminder after divising by 2 is 0 */

printf("%d\t",i);

i++;

while(i<=100);

getch();

}
4.3: For Statement

Syntax

For ( int counter = 1; counter <= 10; ++ counter)

For = keyword

Counter = control variable name

1 = initial value of control variable

counter <= 10; = loop-continuation condition

10 = Final value of control variable for which the condition is true

++ = counter increment of control variable

Examples:

#include<stdio.h>

main()

int counter=1 ;

for( counter =1; counter<=100; counter++)

Printf (“%d\n”, counter );

Return 0 ;

}
Examples:

// Program that controls variable from 1 to 100 in increments of 1

#include<stdio.h>

main()

int i=1 ;

for(i=1; i<=100; i++)

printf("%d\t”,i);

Examples:

/* Program that controls variable from 100 down to 1 in increments

of -1 (that is, decrements of 1). */


#include<stdio.h>
main()
{
int i =100;
for(i=100; i>=1; i--)
{
printf("%d\t",i);
}
}

Examples:

// To print a statement 10 times on the screen by using for loop

#include<stdio.h>

#include<conio.h>

main()

int i;

clrscr();

for(i=1 ; i<=10 ; i++)

printf("welcome to faculty of computer science.\n");

getch();

}
Examples:

/* To print all numbers from one number to another number

10 25

1 7

100 200

*/

#include<stdio.h>

#include<conio.h>

main()

int start, end, i;

clrscr();

printf("Enter the start number :");

scanf("%d",&start);

printf("Enter the end number :");

scanf("%d",&end);

for(i=start ; i<=end ; i++)

i=start*end ;

printf("%d\t",i);

getch();

}
Examples:

/* To enter a number and print its multiplication table


5*1=5
5*2=10
5*3=15
...
...
5*10=50
*/
#include<stdio.h>
#include<conio.h>
main()
{
int no, i, res;
clrscr();
printf("Enter the number :");
scanf("%d",&no);
for(i=1;i<=10;i++)
{
res=no*i;
printf("%d * %d = %d\n",no,i,res);
}
getch();
}

You might also like