You are on page 1of 104

SCHOOL OF INFORMATION TECHNOLOGY

Course Overview

Course Code/Title: ENGCFP1/COFPRO1

Course Description: ( COMPUTER FUNDAMENTALS AND PROGRAMMING)

This is an introductory course in programming which aims to develop skills and


concepts that are essential to good programming practice and problem solving. It covers
fundamental programming concepts of primitive data types, simple I/O, conditional
statements, iterative structures, arrays and functions. It also includes the use of testing and
debugging techniques. Fundamental to the software development practice is the ability to
develop programs that use appropriate constructs aside from achieving desired results to
solve computing problems. This course also serves as a preparation for intermediate
programming. At the end of the course, the students are expected to be able to make
judicious choices of programming constructs to solve computing problems using appropriate
coding standards..

Course Requirements: At the end of the course you are required to take quizzes,
assignments and self-reflection and major examinations.
.
Module Requirements:
At the end of each module, you are expected to complete each:

1. Self-check (Quiz), Seatwork , Assignment


2. Programming Exercises
3. Major Written Examinations
4. Hands-on Examinations

Contact Information:

jpascual@e.ubaguio.edu

Consultation Hours:
Class time

Table of Contents

Lesson : Introduction
1.1. Course Syllabus
SCHOOL OF INFORMATION TECHNOLOGY

1.2. Introduction to Computer

Programming 2.1. Introduction to

Programming Languages 2.2.

Program Development Life Cycle

2.3. Introduction to C Programming


2.4. Program Structure
2.5 Identifiers, keywords, literals
2.6 Data Types
2.7 Variables
2.8 Coding Guidelines
2.9 Testing and debugging techniques
2.10 Output statements
2.11 Compiling and executing C programs
2.12 Arithmetic Operators
2.13 Input / output statements
2.14 Relational & Logical operators
2.15 Decision control structures
- if
- if-else
- if-else if
2.16 Decision control structures
- nested if
- switch
2.17 Repetition control structures
- while loop
- do-while loop
- for loop
- nested loop
- break, continue
2.18 Repetition
SCHOOL OF INFORMATION TECHNOLOGY

control structures -
while loop

- do-while loop
- for loop
- nested loop
- break, continue
2.19 Introduction to arrays
2.20 One-dimensional array
2.21 Built-in functions
2.22 User-defined functions
SCHOOL OF INFORMATION TECHNOLOGY

Introduction to Computer Programming

Computer programming is the process of designing and writing computer programs. As a skill set,
it includes a wide variety of different tasks and techniques, but our tutorials are not intended to teach
you everything. Instead, they are meant to provide basic, practical skills to help you understand and
write computer code that reflects things you see and use in the real world.

What you need to know

Our computer programming tutorials assume that you have no programming experience
whatsoever. They do, however, require basic familiarity with the use of computers and web browsers.
For example, you should be comfortable downloading and opening files, and using text editing
software. If you don't feel confident in those skills, consider spending some time with these tutorials
first:

· Computer Basics

· Internet Basics

What is a computer?

A computer is an electronic device that manipulates information, or data. It has the ability to store,
retrieve, and process data. You may already know that you can use a computer to type documents,
send email, play games, and browse the Web. You can also use it to edit or create spreadsheets,
presentations, and even videos.

Hardware vs. software

Before we talk about different types of computers, let's talk about two things all computers have in
common: hardware and software.

· Hardware is any part of your computer that has a physical structure, such as the

keyboard or mouse. It also includes all of the computer's internal parts, which you

can see in the image below.


SCHOOL OF INFORMATION TECHNOLOGY

· Software is any set of instructions that tells the hardware what to do and how to do

it. Examples of software include web browsers, games, and word processors.

Everything you do on your computer will rely on both hardware and software. For example, right now
you may be viewing this lesson in a web browser (software) and using your mouse (hardware) to
click from page to page. As you learn about different types of computers, ask yourself about the
differences in their hardware. As you progress through this tutorial, you'll see that different types of
computers also often use different types of software.

What are the different types of


computers?

When most people hear the word computer, they think of a personal computer such as a desktop
or laptop. However, computers come in many shapes and sizes, and they perform many different
functions in our daily lives. When you withdraw cash from an ATM, scan groceries at the store, or use
a calculator, you're using a type of computer

Desktop computers

Many people use desktop computers at work, home, and school. Desktop computers are designed to
be placed on a desk, and they're typically made up of a few different parts, including the computer
case, monitor, keyboard, and mouse.

Laptop computers

The second type of computer you may be familiar with is a laptop computer, commonly called a
laptop. Laptops are battery-powered computers that are more portable than desktops, allowing you to
use them almost anywhere.

Tablet computers

Tablet computers—or tablets—are handheld computers that are even more portable than laptops.
SCHOOL OF INFORMATION TECHNOLOGY

Instead of a keyboard and mouse, tablets use a touch-sensitive screen for typing and navigation.
The iPad is an example of a tablet.

Servers

A server is a computer that serves up information to other computers on a network. For example,
whenever you use the Internet, you're looking at something that's stored on a server. Many businesses
also use local file servers to store and share files internally.

Other types of computers

Many of today's electronics are basically specialized computers, though we don't always think of
them that way. Here are a few common examples.

· Smartphones: Many cell phones can do a lot of things computers can do, including

browsing the Internet and playing games. They are often called smartphones.

· Wearables: Wearable technology is a general term for a group of devices—including

fitness trackers and smartwatches—that are designed to be worn throughout the

day. These devices are often called wearables for short.

· Game consoles: A game console is a specialized type of computer that is used for

playing video games on your TV.

· TVs: Many TVs now include applications—or apps—that let you access various types

of online content. For example, you can stream video from the Internet directly onto

your TV.

PCs and Macs

Personal computers come in two main styles: PC and Mac. Both are fully functional, but they have a
different look and feel, and many people prefer one or the other.
SCHOOL OF INFORMATION TECHNOLOGY

This type of computer began with the original IBM PC that was introduced in 1981. Other companies

began creating similar computers, which were called IBM PC Compatible (often shortened to PC).

Today, this is the most common type of personal computer, and it typically includes the Microsoft

Windows operating system.

The Macintosh computer was introduced in 1984, and it was the first widely sold personal computer

with a graphical user interface, or GUI (pronounced gooey). All Macs are made by one company

(Apple), and they almost always use the Mac OS X operating system.

Basic Parts of a Desktop

The basic parts of a desktop computer are the computer case, monitor, keyboard, mouse, and power

cord. Each part plays an important role whenever you use a computer.

The computer case is the metal and plastic box that contains the main components of the computer,

including the motherboard, central processing unit (CPU), and power supply. The front of the case

usually has an On/Off button and one or more optical drives.

Computer cases come in different shapes and sizes. A desktop case lies flat on a desk, and the

monitor usually sits on top of it. A tower case is tall and sits next to the monitor or on the floor.

All-in-one computers come with the internal components built into the monitor, which eliminates the

need for a separate case.

Computer Basics: About This Lesson

This lesson helps you understand how computers work and how to use them. We’ll talk about how to

set up a computer, the difference between hardware and software, and the types of computers you

can use. We’ll also explore operating systems, applications, the cloud, and a whole lot more.
SCHOOL OF INFORMATION TECHNOLOGY

Basic Parts of a Computer

The basic parts of a desktop computer are the computer case, monitor, keyboard, mouse, and power

cord. Each part plays an important role whenever you use a computer.

Computer case

Showing computer cases

The computer case is the metal and plastic box that contains the main components of the computer,

including the motherboard, central processing unit (CPU), and power supply. The front of the case

usually has an On/Off button and one or more optical drives.

Computer cases come in different shapes and sizes. A desktop case lies flat on a desk, and the

monitor usually sits on top of it. A tower case is tall and sits next to the monitor or on the floor.

All-in-one computers come with the internal components built into the monitor, which eliminates the

need for a separate case.

Monitor

Showing a computer monitor

The monitor works with a video card, located inside the computer case, to display images and text on

the screen. Most monitors have control buttons that allow you to change your monitor’s display

settings, and some monitors also have built-in speakers.

Newer monitors usually have LCD (liquid crystal display) or LED (light-emitting diode) displays. These

can be made very thin, and they are often called flat-panel displays. Older monitors use CRT (cathode

ray tube) displays. CRT monitors are much larger and heavier, and they take up more desk space.

Keyboard
SCHOOL OF INFORMATION TECHNOLOGY

The keyboard is one of the main ways to communicate with a computer. There are many different

types of keyboards, but most are very similar and allow you to accomplish the same basic tasks.

Print Screen, Scroll Lock, Pause/Break

The Print Screen, Scroll Lock, and Pause/Break keys are at the top-right corner of the keyboard. The

Print Screen key takes a picture of your screen (called a screenshot) that you can edit or save using a

graphics program. Scroll Lock and Pause/Break are rarely used today, so some keyboards don’t have

them.

Keyboard

Escape Key

The Escape (Esc) key allows you to stop a function or action. For example, if a webpage is taking a

long time to load, you can press the Escape key to stop loading it.

Keyboard

Function Keys

The function keys are labeled F1 through F12. Some programs use these keys as shortcuts for

common tasks. For example, in many programs, F1 opens the Help file.

Keyboard
SCHOOL OF INFORMATION TECHNOLOGY

Tab Key

The Tab key is used to create indents in word processing programs. Also, if you are filling out a form

online, you can use the Tab key to switch to the next field.

Keyboard

Alphanumeric Keys

The main part of the keyboard includes the alphanumeric keys (letters and numbers) and the

spacebar.

Keyboard

Ctrl, Alt, and Shift

The Control (Ctrl), Alternate (Alt), and Shift keys are designed to work in combination with other keys.

Typically, you hold down Ctrl, Alt, or Shift and then type another key to perform a specific task. For

example, in many programs, typing Ctrl+S will save a file.

Keyboard

Arrow Keys

The arrow keys are used for many different purposes, including moving the cursor, scrolling a

document, and controlling a game.

Keyboard
SCHOOL OF INFORMATION TECHNOLOGY

Numeric Keypad

The numeric keypad resembles a calculator keypad. Many users find that it is easier to type numbers

using this keypad. On some keyboards, these keys double as arrow keys.

Keyboard

Backspace Key

The Backspace key (also known as the delete key) erases the character to the left of the cursor.

Keyboard

Enter

The Enter key (also known as the return key) executes commands. For example, while on the Internet,

you can type a website address and then press Enter to go to the site. It is also used to start a new

line in word processing programs.

Keyboard

Home and End

These move the cursor to the beginning or end of the current line.

Keyboard
SCHOOL OF INFORMATION TECHNOLOGY

Insert and Delete

Insert: This switches between insert mode (which inserts new text without deleting anything) and

overtype mode (which deletes text after the cursor as you type).

Delete: This erases the character to the right of the cursor.

keyboard

Page Up and Page Down

These scroll a document or webpage up or down.

The mouse is another important tool for communicating with computers. Commonly known as a

pointing device, it lets you point to objects on the screen, click on them, and move them.

There are two main mouse types: optical and mechanical. The optical mouse uses an electronic eye to

detect movement and is easier to clean. The mechanical mouse uses a rolling ball to detect movement

and requires regular cleaning to work properly.

Mouse alternatives

There are other devices that can do the same thing as a mouse. Many people find them easier to use,

and they also require less desk space than a traditional mouse. The most common mouse alternatives

are below.

Trackball: A trackball has a ball that can rotate freely. Instead of moving the device like a mouse, you
SCHOOL OF INFORMATION TECHNOLOGY

can roll the ball with your thumb to move the pointer.

Touchpad: A touchpad—also called a trackpad—is a touch-sensitive pad that lets you control the

pointer by making a drawing motion with your finger. Touchpads are common on laptop computers.

Buttons and Ports on a Computer

Ethernet Port

This port looks a lot like the modem or telephone port, but it is slightly wider. You can use this port for
networking and connecting to the Internet.

PS/2

These ports are sometimes used for connecting the mouse and keyboard. Typically, the mouse port
is green and the keyboard port is purple. On new computers, these ports have been replaced by
USB.

Serial Port

This port is less common on today's computers. It was frequently used to connect peripherals like
digital cameras, but it has been replaced by USB and other types of ports.

Expansion Slots

These empty slots are where expansion cards are added to computers. For example, if your
computer did not come with a video card, you could purchase one and install it here.

Power Socket
SCHOOL OF INFORMATION TECHNOLOGY

This is where you'll connect the power cord to the computer.

Other types of ports

There are many other types of ports, such as FireWire, Thunderbolt, and HDMI. If your computer has

ports you don’t recognize, you should consult your manual for more information.

Peripherals you can use with


your computer

The most basic computer setup usually includes the computer case, monitor, keyboard, and
mouse, but you can plug many different types of devices into the extra ports on your computer. These
devices are called peripherals. Let's take a look at some of the most common ones.

· Printers: A printer is used to print documents, photos, and anything else that appears

on your screen. There are many types of printers, including inkjet, laser, and photo

printers. There are even all-in-one printers, which can also scan and copy

documents.

· Scanners: A scanner allows you to copy a physical image or document and save it

to your computer as a digital (computer-readable) image. Many scanners are

included as part of an all-in-one printer, although you can also buy a separate flatbed

or handheld scanner.

· Speakers/headphones: Speakers and headphones are output devices, which means

they send information from the computer to the user—in this case, they allow you to

hear sound and music. Depending on the model, they may connect to the audio

port or the USB port. Some monitors also have built-in speakers.

· Microphones: A microphone is a type of input device, or a device that receives

information from a user. You can connect a microphone to record sound or talk with

someone else over the Internet. Many laptop computers come with built-in

microphones.
SCHOOL OF INFORMATION TECHNOLOGY

· Web cameras: A web camera—or webcam—is a type of input device that can record

videos and take pictures. It can also transmit video over the Internet in real time,

which allows for video chat or video conferencing with someone else. Many

webcams also include a microphone for this reason.

· Game controllers and joysticks: A game controller is used to control computer

games. There are many other types of controllers you can use, including joysticks,

although you can also use your mouse and keyboard to control most games.

· Digital cameras: A digital camera lets you capture pictures and videos in a digital

format. By connecting the camera to your computer's USB port, you can transfer the

images from the camera to the computer.

· Mobile phones, MP3 players, tablet computers, and other devices: Whenever you

buy an electronic device, such as a mobile phone or MP3 player, check to see if it

comes with a USB cable. If it does, this means you can most likely connect it to your

computer.

Front of a computer case


Optical Disc Drive
SCHOOL OF INFORMATION TECHNOLOGY

Often called a CD-ROM or DVD-ROM drive, this lets your computer read CD

Power Button

The power button is used to power the computer on and off.

Audio In/Audio Out

Many computers include audio ports on the front of the computer case that allow you to easily
connect speakers, microphones, and headsets without fumbling with the back of the computer.

USB (Universal Serial Bus)

Port

Most desktop computers have several USB ports. These can be used to connect almost any type of
device, including mice, keyboards, printers, and digital cameras. They will often appear on the front
and back of the computer.

Back of a computer case

The back of a computer case has connection ports that are made to fit specific devices. The
placement will vary from computer to computer, and many companies have their own special
connectors for specific devices. Some of the ports may be color coded to help you determine which
port is used with a particular device.

Audio In/Audio Out

Almost every computer has two or more audio ports where you can connect various devices,
SCHOOL OF INFORMATION TECHNOLOGY

including speakers, microphones, and headsets.

Monitor Port

This is where you'll connect your monitor cable. In this example, the computer has both a DisplayPort
and a VGA port. Other computers may have other types of monitor ports, such as DVI (digital visual
interface) or HDMI (high-definition multimedia interface).

USB Ports

On most desktop computers, most of the USB ports are on the back of the computer case. Generally,
you'll want to connect your mouse and keyboard to these ports and keep the front USB ports free so
they can be used for digital cameras and other devices.

Ethernet Port

This port looks a lot like the modem or telephone port, but it is slightly wider. You can use this port for
networking and connecting to the Internet.

PS/2

These ports are sometimes used for connecting the mouse and keyboard. Typically, the mouse port
is green and the keyboard port is purple. On new computers, these ports have been replaced by
USB.

Serial Port
SCHOOL OF INFORMATION TECHNOLOGY

This port is less common on today's computers. It was frequently used to connect peripherals like
digital cameras, but it has been replaced by USB and other types of ports.

Expansion Slots

These empty slots are where expansion cards are added to computers. For example, if your
computer did not come with a video card, you could purchase one and install it here.

Power Socket

This is where you'll connect the power cord to the computer.

Other types of ports

There are many other types of ports, such as FireWire, Thunderbolt, and HDMI. If your computer has
ports you don't recognize, you should consult your manual for more information.

Inside a computer

Have you ever looked inside a computer case, or seen pictures of the inside of one? The small parts
may look complicated, but the inside of a computer case isn't really all that mysterious. This lesson will
help you master some of the basic terminology and understand a bit more about what goes on inside
a computer.

Motherboard

The motherboard is the computer's main circuit board. It's a thin plate that holds the CPU, memory,
connectors for the hard drive and optical drives, expansion cards to control the video and audio, and
connections to your computer's ports (such as USB ports). The motherboard connects directly or
indirectly to every part of the computer.
SCHOOL OF INFORMATION TECHNOLOGY

CPU/processor

The central processing unit (CPU), also called a processor, is located inside the computer case on
the motherboard. It is sometimes called the brain of the computer, and its job is to carry out
commands. Whenever you press a key, click the mouse, or start an application, you're sending
instructions to the CPU.

The CPU is usually a two-inch ceramic square with a silicon chip located inside. The chip is usually
about the size of a thumbnail. The CPU fits into the motherboard's CPU socket, which is covered by
the heat sink, an object that absorbs heat from the CPU.

A processor's speed is measured in megahertz (MHz), or millions of instructions per second; and
gigahertz (GHz), or billions of instructions per second. A faster processor can execute instructions
more quickly. However, the actual speed of the computer depends on the speed of many different
components—not just the processor.

RAM (random access memory)

RAM is your system's short-term memory. Whenever your computer performs calculations, it
temporarily stores the data in the RAM until it is needed.

This short-term memory disappears when the computer is turned off. If you're working on a
document, spreadsheet, or other type of file, you'll need to save it to avoid losing it. When you save a
file, the data is written to the hard drive, which acts as long-term storage.

RAM is measured in megabytes (MB) or gigabytes (GB). The more RAM you have, the more things
your computer can do at the same time. If you don't have enough RAM, you may notice that your
computer is sluggish when you have several programs open. Because of this, many people add extra
RAM to their computers to improve performance.
SCHOOL OF INFORMATION TECHNOLOGY

Hard drive

The hard drive is where your software, documents, and other files are stored. The hard drive is
long-term storage, which means the data is still saved even if you turn the computer off or unplug it.

When you run a program or open a file, the computer copies some of the data from the hard drive
onto the RAM. When you save a file, the data is copied back to the hard drive. The faster the hard
drive, the faster your computer can start up and load programs.

Power supply unit

The power supply unit in a computer converts the power from


the wall outlet to the type of power needed by the computer. It
sends power through cables to the motherboard and other
components.
SCHOOL OF INFORMATION TECHNOLOGY

Introduction to Programming Languages

The basic components of a computer are:

1. Input unit

2. Central Processing Unit(CPU)

3. Output unit

The CPU is further divided into three parts-

· Memory unit

· Control unit

· Arithmetic Logic unit

Most of us have heard that the CPU is called the brain of our computer because it accepts data,

provides temporary memory space to it until it is stored(saved) on the hard disk, performs logical

operations on it and hence processes(here also converts) data into information. We all know that a

computer consists of hardware and software. Software is a set of programs that performs multiple

tasks together. An operating system is also software (system software) that helps humans to interact

with the computer system.

A program is a set of instructions given to a computer to perform a specific operation. a computer is a

computational device that is used to process the data under the control of a computer program. While

executing the program, raw data is processed into the desired output format. These computer

programs are written in a programming language which are high-level languages. High level

languages are nearly human languages that are more complex than the computer understandable

language which are called machine language, or low level language. So after knowing the basics, we

are ready to create a very simple and basic program. Like we have different languages to

communicate with each other, likewise, we have different languages like C, C++, C#, Java, python, etc
SCHOOL OF INFORMATION TECHNOLOGY

to communicate with the computers. The computer only understands binary language (the language of

0’s and 1’s) also called machine-understandable language or low-level language but the programs we

are going to write are in a high-level language which is almost similar to human language.

The piece of code given below performs a basic task of printing “hello world! I am learning

programming” on the console screen. We must know that keyboard, scanner, mouse, microphone, etc

are various examples of input devices, and monitor(console screen), printer, speaker, etc are

examples of output devices.

main()

clrscr();

printf(“hello world! I am learning to program");

getch();

At this stage, you might not be able to understand in-depth how this code prints something on the

screen. The main() is a standard function that you will always include in any program that you are

going to create from now onwards. Note that the execution of the program starts from the main()

function. The clrscr() function is used to see only the current output on the screen while the printf()

function helps us to print the desired output on the screen. Also, getch() is a function that accepts any

character input from the keyboard. In simple words, we need to press any key to continue(some

people may say that getch() helps in holding the screen to see the output). Between high-level

language and machine language, there are assembly languages also called symbolic machine code.

Assembly languages are particularly computer architecture specific. Utility program (Assembler) is

used to convert assembly code into executable machine code. High Level Programming Language is

portable but requires Interpretation or compiling to convert it into a machine language that is computer

understood.
SCHOOL OF INFORMATION TECHNOLOGY

Hierarchy of Computer language –

C Python C++

C# R Ruby

COBOL ADA Java

Altair

Fortran BASIC BASIC

Visual

BASIC
True

BASIC GW BASIC

QBASIC PureBASIC PASCAL

Turbo

Pascal GO ALGOL

Swift

LISP SCALA
SCHOOL OF INFORMATION TECHNOLOGY

Rust Prolog Reia

Racket Scheme Simula

Perl PHP Java Script

CoffeeScri VisualFoxP

pt ro Babel

Logo Lua

Smalltalk

Matlab F F#

Dart Datalog dbase

Haskell dylan Julia

ksh metro Mumps

Nim OCaml pick


SCHOOL OF INFORMATION TECHNOLOGY

TCL D CPL

ActionScrip

Curry t Erlang

DarkBASCI

Clojure C Assembly

Most Popular Programming Languages –

·C

· Python

· C++

· Java

· SCALA

· C#

·R

· Ruby

· Go

· Swift

· JavaScript
SCHOOL OF INFORMATION TECHNOLOGY

Characteristics of a programming Language –

· A programming language must be simple, easy to learn and use, have good readability,

and be human recognizable.

· Abstraction is a must-have characteristic for a programming language in which the ability

to define the complex structure and then its degree of usability comes.

· A portable programming language is always preferred.

· Programming language’s efficiency must be high so that it can be easily converted into

machine code and its execution consumes little space in memory.

· A programming language should be well structured and documented so that it is suitable

for application development.

· Necessary tools for the development, debugging, testing, maintenance of a program must

be provided by a programming language.

· A programming language should provide a single environment known as Integrated

Development Environment(IDE).

· A programming language must be consistent in terms of syntax and semantics.


SCHOOL OF INFORMATION TECHNOLOGY

// C program for sum of 2 numbers

#include <stdio.h>

int main()

int a, b, sum;

a = 10;

b = 15;

sum = a + b;

printf("Sum of %d and %d is: %d", a, b,

sum); // perform addition operation

return 0;

}
SCHOOL OF INFORMATION TECHNOLOGY

Program Development Life Cycle (PDLC)

Program Development Life Cycle (PDLC) is a systematic way of developing quality software. It

provides an organized plan for breaking down the task of program development into manageable

chunks, each of which must be successfully completed before moving on to the next phase.

The program development process is divided into the steps discussed below:

1. Defining the Problem –

The first step is to define the problem. In major software projects, this is a job for system

analyst, who provides the results of their work to programmers in the form of a program

specification. The program specification defines the data used in program, the

processing that should take place while finding a solution, the format of the output and

the user interface.

2. Designing the Program –

Program design starts by focusing on the main goal that the program is trying to achieve

and then breaking the program into manageable components, each of which

contributes to this goal. This approach of program design is called top-bottom program

design or modular programming. The first step involves identifying the main routine,

which is one of the program’s major activities. From that point, programmers try to

divide the various components of the main routine into smaller parts called modules.

For each module, the programmer draws a conceptual plan using an appropriate

program design tool to visualize how the module will do its assigned job.

Program Design Tools:

The various program design tools are described below:

· Structure Charts – A structure chart, also called Hierarchy chart, shows

top-down design of a program. Each box in the structure chart indicates a


SCHOOL OF INFORMATION TECHNOLOGY

task that the program must accomplish. The Top module, called the Main

module or Control module. For example:

· Algorithms –

An algorithm is a step-by-step description of how to arrive at a solution in the

easiest way. Algorithms are not restricted to the computer world only. In fact,

we use them in everyday life.

· Flowcharts

A flowchart is a diagram that shows the logic of the program. Flow charts are

diagrams showing the exact sequence of logical steps. They use

geometrical shapes and arrows to show processes, relationships, and

data/process flow. In other words, flowcharts depict decisions and results of

them. Flowcharts are useful tools in software development. In C

programming, flowcharts are often used to represent algorithms or

programs. They show the connections, flow of information, and processes

within an algorithm or a program. For example, here's an if else flowchart

that's often used in C programming.

Programmers use flowcharts in the program-planning, or the debugging process, often to solve
problems, even in complex programs.

A program might contain many flows of logic and processes, so flowcharts, using natural language and
symbols, can also help normal, non-technical people understand how the program works. Here are
some conventional symbols for a basic flowchart:
SCHOOL OF INFORMATION TECHNOLOGY

Here are some simple examples of flowcharts related to C programming:

Example 1: Print “Hello World.” On-screen

When you first learn a programming language, whether Python, Pascal, or C, your first program is
often a simple “Hello World” program. So, a chart of a simple program of printing a “Hello World”
message onto the screen should be like this:

Print "Hello World" on screen Flowchart


SCHOOL OF INFORMATION TECHNOLOGY

Example 2: Calculate The Average Of Two Numbers.

As you may have already known, to calculate the average of two numbers, you can sum up those two
numbers and divide the result by 2. In other words, the formula for calculating the average of two
numbers is: (number 1 + number 2)/2.

So the basic shapes of the chart should be like this:

Example 3: Input Number And Check If They Are Odd Or Even

Another relatively simple program is checking odd/even numbers. It is a basic conditional operation
that involves: inputting a number, determining whether it is odd or even, printing the result on-screen.
The chart should be something like this:
SCHOOL OF INFORMATION TECHNOLOGY

Input Number and Check If They Are


Odd or Even Algorithm Flowchart

Example 4: Controlling Algorithm For Toaster

There will be two inputs for this flowchart: the button you push to start the toaster and another input to
measure the toaster’s cooking temperature.

The heater is an output, which can be on or off. Your toaster will lower the bread inside to cook when
the heat is on, turn off the heat then eject the toast when it is done. The detailed chart should be as
follows:
SCHOOL OF INFORMATION TECHNOLOGY

Controlling Algorithm for Toaster


SCHOOL OF INFORMATION TECHNOLOGY

Flowchart Guidelines

To create a flowchart, you must follow the following current standard guideline:

● Step 1: Start the program.


● Step 2: Begin Process 1 of the program.
● Step 3: Check some conditions and make a Decision (“yes” or “no”).
● Step 4: If the decision is “yes”, proceed to Process 3. If the decision is “no”, proceed to
Process 2 and return to Step 2.
● Step 5: End of the program.

Building a standard flow chart

Additionally, the following can be helpful tips in creating flowcharts as well:


SCHOOL OF INFORMATION TECHNOLOGY

● You can only have one start and one end in your chart, no more, no less.
● On-page connectors are referred to by numbers, while off-page connectors are referred to by
alphabetical letters.
● The flow of processes is generally from top to bottom or left to right, not the other way
around.
● It would be best not to make the arrows cross each other.

Conclusion

It is important to plan ahead with coding. Coding is a process that can take a while and it is best to
plan ahead. One way of planning is by using a flowchart as a guide. This flowchart should indicate
which blocks of code will be used where, what the codes will do, and how they will interact with each
other. These are just some of the many methods programmers use to plan their coding before they
even start.

· Decision tables –A Decision table is a special kind of table, which is divided into four parts by a pair

of horizontal and vertical lines.

· Pseudocode –A pseudocode is another tool to describe the way to arrive at a solution. They are

different from algorithms by the fact that they are expressed in program language like constructs.

3. Coding the Program –Coding the program means translating an algorithm into a specific

programming language. The technique of programming using only well defined control structures is

known as Structured programming. Programmers must follow the language rules, violation of any rule

causes error. These errors must be eliminated before going to the next step.

4. Testing and Debugging the Program – After removal of syntax errors, the program will execute.

However, the output of the program may not be correct. This is because of a logical error in the

program. A logical error is a mistake that the programmer made while designing the solution to a

problem. So the programmer must find and correct logical errors by carefully examining the program
SCHOOL OF INFORMATION TECHNOLOGY

output using Test data. Syntax error and Logical error are collectively known as Bugs. The process of

identifying errors and eliminating them is known as Debugging.

5. Documenting the Program –After testing, the software project is almost complete. The structure

charts, pseudocodes, flowcharts and decision tables developed during the design phase become

documentation for others who are associated with the software project. This phase ends by writing a

manual that provides an overview of the program’s functionality, tutorials for the beginner, in-depth

explanations of major program features, reference documentation of all program commands and a

thorough description of the error messages generated by the program.

6. Deploying and Maintaining the Program – In the final phase, the program is deployed (installed)

at the user’s site. Here also, the program is kept under watch till the user gives a green signal to

it.Even after the software is completed, it needs to be maintained and evaluated regularly. In software

maintenance, the programming team fixes program errors and updates the software.
SCHOOL OF INFORMATION TECHNOLOGY

What is C Programming Language?

C is a general-purpose programming language that is extremely popular, simple, and flexible to use. It

is a structured programming language that is machine-independent and extensively used to write

various applications, Operating Systems like Windows, and many other complex programs like Oracle

database, Git, Python interpreter, and more.

It is said that ‘C’ is a god’s programming language. One can say, C is a base for programming. If you

know ‘C,’ you can easily grasp the knowledge of the other programming languages that uses the

concept of ‘C’

It is essential to have a background in computer memory mechanisms because it is an important

aspect when dealing with the C programming language.

History of C language

The base or father of programming languages is ‘ALGOL.’ It was first introduced in 1960. ‘ALGOL’ was

used on a large basis in European countries. ‘ALGOL’ introduced the concept of structured

programming to the developer community. In 1967, a new computer programming language was

announced called ‘BCPL’ which stands for Basic Combined Programming Language. BCPL was

designed and developed by Martin Richards, especially for writing system software. This was the era

of programming languages. Just after three years, in 1970 a new programming language called ‘B’

was introduced by Ken Thompson that contained multiple features of ‘BCPL.’ This programming

language was created using the UNIX operating system at AT&T and Bell Laboratories. Both the

‘BCPL’ and ‘B’ were system programming languages.

In 1972, a great computer scientist Dennis Ritchie created a new programming language called ‘C’ at

the Bell Laboratories. It was created from ‘ALGOL’, ‘BCPL’ and ‘B’ programming languages. ‘C’

programming language contains all the features of these languages and many more additional

concepts that make it unique from other languages.


SCHOOL OF INFORMATION TECHNOLOGY

‘C’ is a powerful programming language which is strongly associated with the UNIX operating system.

Even most of the UNIX operating system is coded in ‘C’. Initially ‘C’ programming was limited to the

UNIX operating system, but as it started spreading around the world, it became commercial, and many

compilers were released for cross-platform systems. Today ‘C’ runs under a variety of operating

systems and hardware platforms. As it started evolving many different versions of the language were

released. At times it became difficult for the developers to keep up with the latest version as the

systems were running under the older versions. To assure that ‘C’ language will remain standard,

American National Standards Institute (ANSI) defined a commercial standard for ‘C’ language in 1989.

Later, it was approved by the International Standards Organization (ISO) in 1990. ‘C’ programming

language is also called ‘ANSI C’.

C Basic Commands

C Basic Explanation

commands

#include <stdio.h> This command includes standard input output header file(stdio.h) from

the C library before compiling a C program

int main() It is the main function from where C program execution begins.

{ Indicates the beginning of the main function.

/*_some_comments Whatever written inside this command “/* */” inside a C program, it will

_*/ not be considered for compilation and execution.

printf(“Hello_World! This command prints the output on the screen.

“);

getch(); This command is used for any character input from the keyboard.
SCHOOL OF INFORMATION TECHNOLOGY

return 0; This command is used to terminate a C program (main function) and it

returns 0.

} It is used to indicate the end of the main function.

Where is C used? Key Applications

1. ‘C’ language is widely used in embedded systems.

2. It is used for developing system applications.

3. It is widely used for developing desktop applications.

4. Most of the applications by Adobe are developed using the ‘C’ programming language.

5. It is used for developing browsers and their extensions. Google’s Chromium is built using the

‘C’ programming language.

6. It is used to develop databases. MySQL is the most popular database software which is built

using ‘C’.

7. It is used in developing an operating system. Operating systems such as Apple’s OS X,

Microsoft’s Windows, and Symbian are developed using ‘C’ language. It is used for

developing desktop as well as mobile phone’s operating systems.

8. It is used for compiler production.

9. It is widely used in IOT applications.


SCHOOL OF INFORMATION TECHNOLOGY

Why learn C Language?

As we studied earlier, ‘C’ is a base language for many programming languages. So, learning ‘C’ as the

main language will play an important role while studying other programming languages. It shares the

same concepts such as data types, operators, control statements and many more. ‘C’ can be used

widely in various applications. It is a simple language and provides faster execution. There are many

jobs available for a ‘C’ developer in the current market.

‘C’ is a structured programming language in which a program is divided into various modules. Each

module can be written separately and together it forms a single ‘C’ program. This structure makes it

easy for testing, maintaining and debugging processes.

‘C’ contains 32 keywords, various data types and a set of powerful built-in functions that make

programming very efficient.

Another feature of ‘C’ programming is that it can extend itself. A ‘C’ program contains various functions

which are part of a library. We can add our features and functions to the library. We can access and

use these functions anytime we want in our program. This feature makes it simple while working with

complex programming.

Various compilers are available in the market that can be used for executing programs written in this

language.

It is a highly portable language which means programs written in ‘C’ language can run on other

machines. This feature is essential if we wish to use or execute the code on another computer.

How C Programming Language Works?

C is a compiled language. A compiler is a special tool that compiles the program and converts it into

the object file which is machine readable. After the compilation process, the linker will combine

different object files and create a single executable file to run the program. The following diagram
SCHOOL OF INFORMATION TECHNOLOGY

shows the execution of a ‘C’ program .Nowadays, various compilers are available online, and you can

use any of those compilers. The functionality will never differ and most of the compilers will provide the

features required to execute both ‘C’ and ‘C++’ programs.

Following is the list of popular compilers available online:

· Clang compiler

· MinGW compiler (Minimalist GNU for Windows)

· Portable ‘C’ compiler

· Turbo C

Summary

· ‘C’ was developed by Dennis Ritchie in 1972.

· It is a robust language.

· It is a low programming level language close to machine language

· It is widely used in the software development field.

· It is a procedure and structure oriented language.

· It has the full support of various operating systems and hardware platforms.

· Many compilers are available for executing programs written in ‘C’.

· A compiler compiles the source file and generates an object file.

· A linker links all the object files together and creates one executable file

· It is highly portable.
SCHOOL OF INFORMATION TECHNOLOGY

Program Structure

Before we study the basic building blocks of the C programming language, let us look at a bare

minimum C program structure so that we can take it as a reference in the upcoming chapters.

Hello World Example

A C program basically consists of the following parts −

· Preprocessor Commands

· Functions

· Variables

· Statements & Expressions

· Comments

#include <stdio.h>

int main() {

/* my first program in C */

printf("Hello, World! \n");

return 0;

Let us take a look at the various parts of the above program −


SCHOOL OF INFORMATION TECHNOLOGY

· The first line of the program #include <stdio.h> is a preprocessor command, which tells

a C compiler to include stdio.h file before going to actual compilation.

· The next line int main() is the main function where the program execution begins.

· The next line /*...*/ will be ignored by the compiler and it has been put to add additional

comments in the program. So such lines are called comments in the program.

· The next line printf(...) is another function available in C which causes the message

"Hello, World!" to be displayed on the screen.

· The next line return 0; terminates the main() function and returns the value 0.

Compile and Run C Program

To compile and run a C language program, you need a C compiler. A compiler is a software that is

used to compile and execute programs. To set up a C language compiler in your Computer/laptop,

there are two ways:

1. Download a full-fledged IDE like Turbo C++ or Microsoft Visual C++ or DevC++, which

comes along with a C language compiler.

2. Or, you can use any text editor to edit the program files and download the C compiler

separately and then run the C program using the command line.

If you haven't already installed an IDE for the C language - Follow this step-by-step guide to Install

Turbo C++ for C Language

Using an IDE - Turbo C

We will recommend you to use Turbo C or Turbo C++ IDE, which is the oldest IDE for C

programming. It is freely available over the internet and is good for a beginner.
SCHOOL OF INFORMATION TECHNOLOGY

Step 1: Open turbo C IDE(Integrated Development Environment), click on File and then click on New

Step 2: Write a Hello World program that we created in the previous article - C Hello World program.

Step 3: Click on Compile menu and then on Compile option, or press the keys press Alt + F9 to

compile the code.

Step 4: Click on Run or press Ctrl + F9 to run the code. Yes, C programs are first compiled to

generate the object code and then that object code is Run.

Step 5: Output is here.

C Keywords and Identifiers


In this lesson, you will learn about keywords; reserved words in C programming that are part of the

syntax. Also, you will learn about identifiers and how to name them.

Character set

A character set is a set of alphabets, letters and some special characters that are valid in C language.

Alphabets

Uppercase: A B C ................................... X Y Z

Lowercase: a b c ...................................... x y z
SCHOOL OF INFORMATION TECHNOLOGY

Special Characters in C Programming

, < > . _

( ) ; $ :

% [ ] # ?

' & { } "

^ ! * / |

- \ ~ +

White space Characters

Blank space, newline, horizontal tab, carriage return and form feed.

C Keywords

Keywords are predefined, reserved words used in programming that have special meanings to the

compiler. Keywords are part of the syntax and they cannot be used as an identifier. For example:

int money;
SCHOOL OF INFORMATION TECHNOLOGY

Here, int is a keyword that indicates money is a variable of type int (integer).

As C is a case sensitive language, all keywords must be written in lowercase. Here is a list of all

keywords allowed in ANSI C.

C Keywords

auto double int struct

break else long switch

case enum register typedef

char extern return union

continue for signed void

do if static while

default goto sizeof volatile


SCHOOL OF INFORMATION TECHNOLOGY

const float short unsigned

All these keywords, their syntax, and application will be discussed in their respective topics. However,

if you want a brief overview of these keywords without going further, visit List of all keywords in C

programming.

List of all Keywords in C Language

This tutorial provides a brief information on all 32 keywords in C programming.

Keywords in C Programming

auto break case char

const continue default do

double else enum extern

float for goto if

int long register return


SCHOOL OF INFORMATION TECHNOLOGY

short signed sizeof static

struct switch typedef union

unsigned void volatile while

Description of all Keywords in C

auto

The auto keyword declares automatic variables. For example:

auto int var1;

This statement suggests that var1 is a variable of storage class auto and type int.

Variables declared within function bodies are automatic by default. They are

recreated each time a function is executed.

Since automatic variables are local to a function, they are also called local

variables. To learn more visit C storage class.


SCHOOL OF INFORMATION TECHNOLOGY

break and continue

The break statement terminates the innermost loop immediately when it's

encountered. It's also used to terminate the switch statement.

The continue statement skips the statements after it inside the loop for the iteration.

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

if (i==3)

continue;

if (i==7)

break;

printf("%d ",i);

Output

12456
SCHOOL OF INFORMATION TECHNOLOGY

When i is equal to 3, the continue statement comes into effect and skips 3. When i

is equal to 7, the break statement comes into effect and terminates the for loop. To

learn more, visit C break and continue statement

switch, case and default

The switch and case statement is used when a block of statements has to be

executed among many blocks. For example:

switch(expression)

case '1':

//some statements to execute when 1

break;

case '5':

//some statements to execute when 5


SCHOOL OF INFORMATION TECHNOLOGY

break;

default:

//some statements to execute when default;

Visit C switch statement to learn more.

char

The char keyword declares a character variable. For example:

char alphabet;

Here, alphabet is a character type variable.

To learn more, visit C data types.

const

An identifier can be declared constant by using the const keyword.


SCHOOL OF INFORMATION TECHNOLOGY

const int a = 5;

To learn more, visit C variables and constants.

do...while

int i;

do

printf("%d ",i);

i++;

while (i<10)

To learn more, visit C do...while loop

double and float


SCHOOL OF INFORMATION TECHNOLOGY

Keywords double and float are used for declaring floating type variables. For

example:

float number;

double longNumber;

Here, number is a single-precision floating type variable whereas, longNumber is a

double-precision floating type variable.

To learn more, visit C data types.

if and else

In C programming, if and else are used to make decisions.

if (i == 1)

printf("i is 1.")

else

printf("i is not 1.")


SCHOOL OF INFORMATION TECHNOLOGY

If the value of i is other than 1, the output will be :

i is not 1

To learn more, visit C if...else statement.

enum

Enumeration types are declared in C programming using keyword enum. For

example:

enum suit

hearts;

spades;

clubs;

diamonds;
SCHOOL OF INFORMATION TECHNOLOGY

};

Here, an enumerated variable suit is created having tags: hearts, spades, clubs, and

diamonds.

To learn more, visit C enum.

extern

The extern keyword declares that a variable or a function has external linkage

outside of the file it is declared.

To learn more, visit C storage type.

for

There are three types of loops in C programming. The for loop is written in C

programming using the keyword for. For example:


SCHOOL OF INFORMATION TECHNOLOGY

for (i=0; i< 9;++i){

printf("%d ",i);

Output

012345678

To learn more, visit C for loop.

goto

The goto statement is used to transfer control of the program to the specified label.

For example:

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

if (i==10)
SCHOOL OF INFORMATION TECHNOLOGY

goto error;

printf("i is not 10");

error:

printf("Error, count cannot be 10.");

Output

Error, count cannot be 10.

To learn more, visit C goto.

int

The int keyword is used to declare integer type variables. For example:

int count;

Here, count is an integer variable.

To learn more, visit C data types.


SCHOOL OF INFORMATION TECHNOLOGY

short, long, signed and unsigned

The short, long, signed and unsigned keywords are type modifiers that alter the

meaning of a base data type to yield a new type.

short int smallInteger;

long int bigInteger;

signed int normalInteger;

unsigned int positiveInteger;

Range of int type data types

Data types Range

short int -32768 to 32767

long int -2147483648 to 214743648


SCHOOL OF INFORMATION TECHNOLOGY

signed int -32768 to 32767

unsigned int 0 to 65535

return

The return keyword terminates the function and returns the value.

int func() {

int b = 5;

return b;

This function func() returns 5 to the calling function. To learn more, visit C

user-defined functions.

sizeof

The sizeof keyword evaluates the size of data (a variable or a constant).


SCHOOL OF INFORMATION TECHNOLOGY

#include <stdio.h>

int main()

printf("%u bytes.",sizeof(char));

To learn more, visit C operators.

Output

1 bytes.

register

The register keyword creates register variables which are much faster than normal

variables.

register int var1;


SCHOOL OF INFORMATION TECHNOLOGY

static

The static keyword creates a static variable. The value of the static variables persists

until the end of the program. For example:

static int var;

struct

The struct keyword is used for declaring a structure. A structure can hold variables

of different types under a single name.

struct student{

char name[80];

float marks;

int age;

}s1, s2;

To learn more, visit C structures.


SCHOOL OF INFORMATION TECHNOLOGY

typedef

The typedef keyword is used to explicitly associate a type with an identifier.

typedef float kg;

kg bear, tiger;

union

A union is used for grouping different types of variables under a single name.

union student {

char name[80];

float marks;

int age;

}
SCHOOL OF INFORMATION TECHNOLOGY

To learn more, visit C unions.

void

The void keyword meaning nothing or no value.

void testFunction(int a) {

.....

Here, the testFunction() function cannot return a value because its return type is void.

volatile

The volatile keyword is used for creating volatile objects. A volatile object can be

modified in an unspecified way by the hardware.

const volatile number

Here, number is a volatile object.

Sincenumber is a constant, the program cannot change it. However, hardware can

change it since it is a volatile object.


SCHOOL OF INFORMATION TECHNOLOGY

C Identifiers

Identifier refers to name given to entities such as variables, functions, structures etc.

Identifiers must be unique. They are created to give a unique name to an entity to identify it during the

execution of the program. For example:

int money;

double accountBalance;

Here, money and accountBalance are identifiers.

Also remember, identifier names must be different from keywords. You cannot use int as an identifier

because int is a keyword.

Rules for naming identifiers

1. A valid identifier can have letters (both uppercase and lowercase letters), digits and

underscores.

2. The first letter of an identifier should be either a letter or an underscore.

3. You cannot use keywords like int, while etc. as identifiers.

4. There is no rule on how long an identifier can be. However, you may run into problems in

some compilers if the identifier is longer than 31 characters.

You can choose any name as an identifier if you follow the above rule, however, give meaningful

names to identifiers that make sense.


SCHOOL OF INFORMATION TECHNOLOGY

C Variables, Constants and Literals

In this tutorial, you will learn about variables and rules for naming a variable. You
will also learn about different literals in C programming and how to create
constants.

Variables

In programming, a variable is a container (storage area) to hold data.

To indicate the storage area, each variable should be given a unique name
(identifier). Variable names are just the symbolic representation of a memory
location. For example:

int playerScore = 95;

Here, playerScore is a variable of int type. Here, the variable is assigned an integer
value 95.

The value of a variable can be changed, hence the name variable.

char ch = 'a';

// some code

ch = 'l';

Rules for naming a variable

1. A variable name can only have letters (both uppercase and lowercase
letters), digits and underscore.
2. The first letter of a variable should be either a letter or an underscore.
SCHOOL OF INFORMATION TECHNOLOGY

3. There is no rule on how long a variable name (identifier) can be. However,
you may run into problems in some compilers if the variable name is longer
than 31 characters.

Note: You should always try to give meaningful names to variables. For example:
firstName is a better variable name than fn.

C is a strongly typed language. This means that the variable type cannot be
changed once it is declared. For example:

int number = 5; // integer variable

number = 5.5; // error

double number; // error

Here, the type of number variable is int. You cannot assign a floating-point (decimal)
value 5.5 to this variable. Also, you cannot redefine the data type of the variable to
double. By the way, to store the decimal values in C, you need to declare its type to
either double or float.

Visit this page to learn more about different types of data a variable can store.

Literals
Literals are data used for representing fixed values. They can be used directly in
the code. For example: 1, 2.5, 'c' etc.
SCHOOL OF INFORMATION TECHNOLOGY

Here, 1, 2.5 and 'c' are literals. Why? You cannot assign different values to these
terms.

1. Integers

An integer is a numeric literal(associated with numbers) without any fractional or


exponential part. There are three types of integer literals in C programming:

● decimal (base 10)


● octal (base 8)
● hexadecimal (base 16)

For example:

Decimal: 0, -9, 22 etc

Octal: 021, 077, 033 etc

Hexadecimal: 0x7f, 0x2a, 0x521 etc

In C programming, octal starts with a 0, and hexadecimal starts with a 0x.

2. Floating-point Literals

A floating-point literal is a numeric literal that has either a fractional form or an


exponent form. For example:

-2.0
SCHOOL OF INFORMATION TECHNOLOGY

0.0000234

-0.22E-5

Note: E-5 = 10-5

3. Characters

A character literal is created by enclosing a single character inside single quotation


marks. For example: 'a', 'm', 'F', '2', '}' etc.

4. Escape Sequences

Sometimes, it is necessary to use characters that cannot be typed or has special


meaning in C programming. For example: newline(enter), tab, question mark etc.

In order to use these characters, escape sequences are used.

Escape Sequences Character

\b Backspace

\f Form feed
SCHOOL OF INFORMATION TECHNOLOGY

\n Newline

\r Return

\t Horizontal tab

\v Vertical tab

\\ Backslash

\' Single quotation mark

\" Double quotation mark

\? Question mark

\0 Null character

For example: \n is used for a newline. The backslash \ causes escape from the
SCHOOL OF INFORMATION TECHNOLOGY

normal way the characters are handled by the compiler.

5. String Literals

A string literal is a sequence of characters enclosed in double-quote marks. For


example:

"good" //string constant

"" //null string constant

" " //string constant of six white space

"x" //string constant having a single character.

"Earth is round\n" //prints string with a newline

Constants
If you want to define a variable whose value cannot be changed, you can use the
const keyword. This will create a constant. For example,

const double PI = 3.14;

Notice, we have added keyword const.

Here, PI is a symbolic constant; its value cannot be changed.

const double PI = 3.14;

PI = 2.9; //Error
SCHOOL OF INFORMATION TECHNOLOGY

In C programming, data types are declarations for variables. This determines the
type and size of data associated with variables. For example,

int myVar;

Here, myVar is a variable of int (integer) type. The size of int is 4 bytes.

Basic types
Here's a table containing commonly used types in C programming for quick access.

Type Size (bytes) Format Specifier

int at least 2, usually 4 %d, %i

char 1 %c

float 4 %f

double 8 %lf

short int 2 usually %hd


SCHOOL OF INFORMATION TECHNOLOGY

unsigned int at least 2, usually 4 %u

long int at least 4, usually 8 %ld, %li

long long int at least 8 %lld, %lli

unsigned long int at least 4 %lu

unsigned long long int at least 8 %llu

signed char 1 %c

unsigned char 1 %c

long double at least 10, usually 12 or 16 %Lf

int

Integers are whole numbers that can have both zero, positive and negative values
but no decimal values. For example, 0, -5, 10
SCHOOL OF INFORMATION TECHNOLOGY

We can use int for declaring an integer variable.

int id;

Here, id is a variable of type integer.

You can declare multiple variables at once in C programming. For example,

int id, age;

The size of int is usually 4 bytes (32 bits). And, it can take 232 distinct states from
-2147483648 to 2147483647.

float and double

float and double are used to hold real numbers.

float salary;

double price;

In C, floating-point numbers can also be represented in exponential. For example,

float normalizationFactor = 22.442e2;

What's the difference between float and double?

The size of float (single precision float data type) is 4 bytes. And the size of double

(double precision float data type) is 8 bytes.

char
SCHOOL OF INFORMATION TECHNOLOGY

Keyword char is used for declaring character type variables. For example,

char test = 'h';

The size of the character variable is 1 byte.

void

void is an incomplete type. It means "nothing" or "no type". You can think of void as
absent.

For example, if a function is not returning anything, its return type should be void.

Note that, you cannot create variables of void type.

short and long

If you need to use a large number, you can use a type specifier long. Here's how:

long a;

long long b;

long double c;

Here variables a and b can store integer values. And, c can store a floating-point
number.

If you are sure, only a small integer ([−32,767, +32,767] range) will be used, you can
use short.
SCHOOL OF INFORMATION TECHNOLOGY

short d;

You can always check the size of a variable using the sizeof() operator.

#include <stdio.h>

int main() {

short a;

long b;

long long c;

long double d;

printf("size of short = %d bytes\n", sizeof(a));

printf("size of long = %d bytes\n", sizeof(b));

printf("size of long long = %d bytes\n", sizeof(c));

printf("size of long double= %d bytes\n", sizeof(d));

return 0;

Run Code

signed and unsigned

In C, signed and unsigned are type modifiers. You can alter the data storage of a data
SCHOOL OF INFORMATION TECHNOLOGY

type by using them:

● signed - allows for storage of both positive and negative numbers


● unsigned - allows for storage of only positive numbers

For example,

// valid codes

unsigned int x = 35;

int y = -35; // signed int

int z = 36; // signed int

// invalid code: unsigned int cannot hold negative integers

unsigned int num = -35;

Here, the variables x and num can hold only zero and positive values because we
have used the unsigned modifier.

Considering the size of int is 4 bytes, variable y can hold values from -231 to 231-1,
whereas variable x can hold values from 0 to 232-1.

Derived Data Types


SCHOOL OF INFORMATION TECHNOLOGY

Data types that are derived from fundamental data types are derived types. For
example: arrays, pointers, function types, structures, etc.

We will learn about these derived data types in later tutorials.

● bool type
● Enumerated type
● Complex types

C Arithmetic Operators

An arithmetic operator performs mathematical operations such as addition, subtraction, multiplication,


division etc on numerical values (constants and variables).

Operator Meaning of Operator

+ addition or unary plus

- subtraction or unary minus

* multiplication
SCHOOL OF INFORMATION TECHNOLOGY

/ division

% remainder after division (modulo division)

Example 1: Arithmetic Operators

// Working of arithmetic operators

#include <stdio.h>

int main()

int a = 9,b = 4, c;

c = a+b;

printf("a+b = %d \n",c);

c = a-b;

printf("a-b = %d \n",c);

c = a*b;

printf("a*b = %d \n",c);

c = a/b;
SCHOOL OF INFORMATION TECHNOLOGY

printf("a/b = %d \n",c);

c = a%b;

printf("Remainder when a divided by b = %d \n",c);

return 0;

Run Code

Output

a+b = 13

a-b = 5

a*b = 36

a/b = 2

Remainder when a divided by b=1

The operators +, - and * computes addition, subtraction, and multiplication respectively as you might
have expected.

In normal calculation, 9/4 = 2.25. However, the output is 2 in the program.

It is because both the variables a and b are integers. Hence, the output is also an integer. The
compiler neglects the term after the decimal point and shows answer 2 instead of 2.25.

The modulo operator % computes the remainder. When a=9 is divided by b=4, the remainder is 1. The
% operator can only be used with integers.
SCHOOL OF INFORMATION TECHNOLOGY

Suppose a = 5.0, b = 2.0, c = 5 and d = 2. Then in C programming,

// Either one of the operands is a floating-point number

a/b = 2.5

a/d = 2.5

c/b = 2.5

// Both operands are integers

c/d = 2

C Increment and Decrement Operators

C programming has two operators increment ++ and decrement -- to change the value of an operand
(constant or variable) by 1.

Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. These two
operators are unary operators, meaning they only operate on a single operand.

Example 2: Increment and Decrement Operators

// Working of increment and decrement operators

#include <stdio.h>

int main()

int a = 10, b = 100;


SCHOOL OF INFORMATION TECHNOLOGY

float c = 10.5, d = 100.5;

printf("++a = %d \n", ++a);

printf("--b = %d \n", --b);

printf("++c = %f \n", ++c);

printf("--d = %f \n", --d);

return 0;

Run Code

Output

++a = 11

--b = 99

++c = 11.500000

--d = 99.500000

Here, the operators ++ and -- are used as prefixes. These two operators can also be used as postfixes
like a++ and a--. Visit this page to learn more about how increment and decrement operators work
when used as postfix.
SCHOOL OF INFORMATION TECHNOLOGY

C Assignment Operators

An assignment operator is used for assigning a value to a variable. The most common assignment
operator is =

Operator Example Same as

= a=b a=b

+= a += b a = a+b

-= a -= b a = a-b

*= a *= b a = a*b

/= a /= b a = a/b

%= a %= b a = a%b
SCHOOL OF INFORMATION TECHNOLOGY

Example 3: Assignment Operators


// Working of assignment operators

#include <stdio.h>

int main()

int a = 5, c;

c = a; // c is 5

printf("c = %d\n", c);

c += a; // c is 10

printf("c = %d\n", c);

c -= a; // c is 5

printf("c = %d\n", c);

c *= a; // c is 25

printf("c = %d\n", c);

c /= a; // c is 5

printf("c = %d\n", c);

c %= a; // c = 0

printf("c = %d\n", c);


SCHOOL OF INFORMATION TECHNOLOGY

return 0;

Output

c=5

c = 10

c=5

c = 25

c=5

c=0

C Relational Operators

A relational operator checks the relationship between two operands. If the relation is true, it returns 1;
if the relation is false, it returns value 0.

Relational operators are used in decision making and loops.

Operator Meaning of Operator Example

== Equal to 5 == 3 is evaluated to 0
SCHOOL OF INFORMATION TECHNOLOGY

> Greater than 5 > 3 is evaluated to 1

< Less than 5 < 3 is evaluated to 0

!= Not equal to 5 != 3 is evaluated to 1

>= Greater than or equal to 5 >= 3 is evaluated to 1

<= Less than or equal to 5 <= 3 is evaluated to 0

Example 4: Relational Operators

// Working of relational operators

#include <stdio.h>

int main()

int a = 5, b = 5, c = 10;

printf("%d == %d is %d \n", a, b, a == b);

printf("%d == %d is %d \n", a, c, a == c);


SCHOOL OF INFORMATION TECHNOLOGY

printf("%d > %d is %d \n", a, b, a > b);

printf("%d > %d is %d \n", a, c, a > c);

printf("%d < %d is %d \n", a, b, a < b);

printf("%d < %d is %d \n", a, c, a < c);

printf("%d != %d is %d \n", a, b, a != b);

printf("%d != %d is %d \n", a, c, a != c);

printf("%d >= %d is %d \n", a, b, a >= b);

printf("%d >= %d is %d \n", a, c, a >= c);

printf("%d <= %d is %d \n", a, b, a <= b);

printf("%d <= %d is %d \n", a, c, a <= c);

return 0;

Output

5 == 5 is 1

5 == 10 is 0

5 > 5 is 0

5 > 10 is 0
SCHOOL OF INFORMATION TECHNOLOGY

5 < 5 is 0

5 < 10 is 1

5 != 5 is 0

5 != 10 is 1

5 >= 5 is 1

5 >= 10 is 0

5 <= 5 is 1

5 <= 10 is 1

C Logical Operators

An expression containing a logical operator returns either 0 or 1 depending upon whether the
expression results true or false. Logical operators are commonly used in decision making in C
programming.

Operator Meaning Example

&& Logical AND. True only if all If c = 5 and d = 2 then, expression

operands are true ((c==5) && (d>5)) equals to 0.

|| Logical OR. True only if If c = 5 and d = 2 then, expression


SCHOOL OF INFORMATION TECHNOLOGY

either one operand is true ((c==5) || (d>5)) equals 1.

! Logical NOT. True only if the If c = 5 then, expression !(c==5) equals to

operand is 0 0.

Example 5: Logical Operators

// Working of logical operators

#include <stdio.h>

int main()

int a = 5, b = 5, c = 10, result;

result = (a == b) && (c > b);

printf("(a == b) && (c > b) is %d \n", result);

result = (a == b) && (c < b);

printf("(a == b) && (c < b) is %d \n", result);


SCHOOL OF INFORMATION TECHNOLOGY

result = (a == b) || (c < b);

printf("(a == b) || (c < b) is %d \n", result);

result = (a != b) || (c < b);

printf("(a != b) || (c < b) is %d \n", result);

result = !(a != b);

printf("!(a != b) is %d \n", result);

result = !(a == b);

printf("!(a == b) is %d \n", result);

return 0;

Output

(a == b) && (c > b) is 1

(a == b) && (c < b) is 0

(a == b) || (c < b) is 1

(a != b) || (c < b) is 0
SCHOOL OF INFORMATION TECHNOLOGY

!(a != b) is 1

!(a == b) is 0

Explanation of logical operator program

● (a == b) && (c > 5) evaluates to 1 because both operands (a == b) and (c > b) are 1 (true).
● (a == b) && (c < b) evaluates to 0 because operand (c < b) is 0 (false).
● (a == b) || (c < b) evaluates to 1 because (a = b) is 1 (true).
● (a != b) || (c < b) evaluates to 0 because both operands (a != b) and (c < b) are 0 (false).
● !(a != b) evaluates to 1 because operand (a != b) is 0 (false). Hence, !(a != b) is 1 (true).
● !(a == b) evaluates to 0 because (a == b) is 1 (true). Hence, !(a == b) is 0 (false).

C Bitwise Operators

During computation, mathematical operations like: addition, subtraction, multiplication, division, etc are
converted to bit-level which makes processing faster and saves power.

Bitwise operators are used in C programming to perform bit-level operations.

Operators Meaning of operators

& Bitwise AND

| Bitwise OR
SCHOOL OF INFORMATION TECHNOLOGY

^ Bitwise exclusive OR

~ Bitwise complement

<< Shift left

>> Shift right

Visit bitwise operators in C to learn more.

Other Operators

Comma Operator

Comma operators are used to link related expressions together. For example:

int a, c = 5, d;

The sizeof operator

The sizeof is a unary operator that returns the size of data (constants, variables, array, structure, etc).

Example 6: sizeof Operator

#include <stdio.h>

int main()
SCHOOL OF INFORMATION TECHNOLOGY

int a;

float b;

double c;

char d;

printf("Size of int=%lu bytes\n",sizeof(a));

printf("Size of float=%lu bytes\n",sizeof(b));

printf("Size of double=%lu bytes\n",sizeof(c));

printf("Size of char=%lu byte\n",sizeof(d));

return 0;

Output

Size of int = 4 bytes

Size of float = 4 bytes

Size of double = 8 bytes

Size of char = 1 byte


SCHOOL OF INFORMATION TECHNOLOGY

In C programming, printf() is one of the main output functions. The function sends
formatted output to the screen. For example,

Example 1: C Output

#include <stdio.h>

int main()

// Displays the string inside quotations

printf("C Programming");

return 0;

Run Code

Output

C Programming

How does this program work?

● All valid C programs must contain the main() function. The code execution
begins from the start of the main() function.
● The printf() is a library function to send formatted output to the screen. The
function prints the string inside quotations.
SCHOOL OF INFORMATION TECHNOLOGY

● To use printf() in our program, we need to include stdio.h header file using the
#include <stdio.h> statement.
● The return 0; statement inside the main() function is the "Exit status" of the
program. It's optional.

Example 2: Integer Output

#include <stdio.h>

int main()

int testInteger = 5;

printf("Number = %d", testInteger);

return 0;

Run Code

Output

Number = 5

We use %d format specifier to print int types. Here, the %d inside the quotations will
be replaced by the value of testInteger.
SCHOOL OF INFORMATION TECHNOLOGY

Example 3: float and double Output

#include <stdio.h>

int main()

float number1 = 13.5;

double number2 = 12.4;

printf("number1 = %f\n", number1);

printf("number2 = %lf", number2);

return 0;

Output

number1 = 13.500000

number2 = 12.400000

To print float, we use %f format specifier. Similarly, we use %lf to print double values.

Example 4: Print Characters

#include <stdio.h>
SCHOOL OF INFORMATION TECHNOLOGY

int main()

char chr = 'a';

printf("character = %c", chr);

return 0;

Output

character = a

To print char, we use %c format specifier.

C Input
In C programming, scanf() is one of the commonly used function to take input from
the user. The scanf() function reads formatted input from the standard input such as
keyboards.

Example 5: Integer Input/Output

#include <stdio.h>

int main()
SCHOOL OF INFORMATION TECHNOLOGY

int testInteger;

printf("Enter an integer: ");

scanf("%d", &testInteger);

printf("Number = %d",testInteger);

return 0;

Output

Enter an integer: 4

Number = 4

Here, we have used %d format specifier inside the scanf() function to take int input
from the user. When the user enters an integer, it is stored in the testInteger variable.

Notice, that we have used &testInteger inside scanf(). It is because &testInteger gets the
address of testInteger, and the value entered by the user is stored in that address.

Example 6: Float and Double Input/Output

#include <stdio.h>

int main()
SCHOOL OF INFORMATION TECHNOLOGY

float num1;

double num2;

printf("Enter a number: ");

scanf("%f", &num1);

printf("Enter another number: ");

scanf("%lf", &num2);

printf("num1 = %f\n", num1);

printf("num2 = %lf", num2);

return 0;

Output

Enter a number: 12.523

Enter another number: 10.2

num1 = 12.523000

num2 = 10.200000
SCHOOL OF INFORMATION TECHNOLOGY

We use %f and %lf format specifiers for float and double respectively.

Example 7: C Character I/O

#include <stdio.h>

int main()

char chr;

printf("Enter a character: ");

scanf("%c",&chr);

printf("You entered %c.", chr);

return 0;

Output

Enter a character: g

You entered g

When a character is entered by the user in the above program, the character itself
is not stored. Instead, an integer value (ASCII value) is stored.

And when we display that value using %c text format, the entered character is
SCHOOL OF INFORMATION TECHNOLOGY

displayed. If we use %d to display the character, it's ASCII value is printed.

Example 8: ASCII Value

#include <stdio.h>

int main()

char chr;

printf("Enter a character: ");

scanf("%c", &chr);

// When %c is used, a character is displayed

printf("You entered %c.\n",chr);

// When %d is used, ASCII value is displayed

printf("ASCII value is %d.", chr);

return 0;

Output

Enter a character: g
SCHOOL OF INFORMATION TECHNOLOGY

You entered g.

ASCII value is 103.

I/O Multiple Values


Here's how you can take multiple inputs from the user and display them.

#include <stdio.h>

int main()

int a;

float b;

printf("Enter integer and then a float: ");

// Taking multiple inputs

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

printf("You entered %d and %f", a, b);

return 0;
SCHOOL OF INFORMATION TECHNOLOGY

Output

Enter integer and then a float: -3

3.4

You entered -3 and 3.400000

Format Specifiers for I/O


As you can see from the above examples, we use

● %d for int
● %f for float
● %lf for double
● %c for char

Here's a list of commonly used C data types and their format specifiers.

Data Type Format Specifier

int %d
SCHOOL OF INFORMATION TECHNOLOGY

char %c

float %f

double %lf

short int %hd

unsigned int %u

long int %li

long long int %lli

unsigned long int %lu

unsigned long long int %llu

signed char %c
SCHOOL OF INFORMATION TECHNOLOGY

unsigned char %c

long double %Lf

References:

https://edu.gcfglobal.org/en/computer-programming-basics/introduction-to-computer-programming/1/

https://www.geeksforgeeks.org/software-engineering-program-development-life-cycle-pdlc/

https://www.programiz.com/c-programming/c-keywords-identifier

https://www.programiz.com/c-programming/c-variables-constants

https://www.programiz.com/c-programming/c-data-types

https://www.programiz.com/c-programming/c-operators

https://www.programiz.com/c-programming/c-input-output

You might also like