0% found this document useful (0 votes)
22 views36 pages

Updated Section 2 (1)

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views36 pages

Updated Section 2 (1)

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Course Title: Introduction to Computer & Computer Programming Course Code: CCE-1201

Section II: Introduction to Programming

Lesson 6, 7, 8, 9, 10, 11, 12, 13, 14 and 15

Syllabus
Definition of Software, its classification, Problem solving steps, Introduction of C and its structure, history
and characteristics, Introduction to keywords, Constants and identifiers, Fundamental of C variable and data
types, Rules of constants, Introduction to arithmetic, relational and logical operators, Introduction to
expressions, Managing data input, Managing data output.

Page 1
Course Title: Introduction to Computer & Computer Programming Course Code: CCE-1201

Lesson 6 - 7: Programming Basics

How can humans communicate with computer?

The simple answer is using programming language.

What is a computer program?


A computer program is a collection of instructions that performs a specific task when executed by a computer.

What is computer programming?


Computer programming is the process of designing and building an executable computer program
for accomplishing a specific computing task timely and efficiently.

Who is a computer programmer?


A computer programmer is a skilled professional who codes, tests, debugs, and maintains the comprehensive
instructions known as computer programs that devices should follow to execute their functions. Computer
programmers also conceptualize, design, and test logical structures to solve computer issues.

What is programming language?


A programming language is a vocabulary and set of grammatical rules for instructing a computer
or computing device to perform specific tasks.

Types of computer programming language

Page 2
Course Title: Introduction to Computer & Computer Programming Course Code: CCE-1201

Comparison of programming languages

Translator program
A translator takes a program written in source language as input and converts it into a program in target
language as output. It also detects and reports the error during translation.

Example:

Page 3
Course Title: Introduction to Computer & Computer Programming Course Code: CCE-1201

Different Types of Translators


There are 3 different types of translators such as compiler, interpreter and assembler.

Compiler
A compiler is a translator used to convert high-level programming language to low-level programming
language. It converts the whole program in one session and reports errors detected after the conversion.

Interpreter
Just like a compiler, is a translator used to convert high-level programming language to low-level programming
language. Interpreter translates line by line and reports the error once it encountered during the translation
process.

Page 4
Course Title: Introduction to Computer & Computer Programming Course Code: CCE-1201

Assembler
An assembler is a translator used to translate assembly language to machine language.

Difference between compiler and interpreter

Page 5
Course Title: Introduction to Computer & Computer Programming Course Code: CCE-1201

How to develop a program / Steps to solve problem

Program writing is a systematic process. It is not all about coding only. It is not a magical or random process.
It requires following a certain methodology. In order to write a program, following steps must be formally or
informally followed:

1. Problem Specification (Input => Process => Output)


The problem must be identified well before it can be resolved. The nature of the problem, the reasons and
the possibilities for solving the problem are considered in this step. The issues are:

• What will be the input?


• What will be the Output?
• Processing requirements.
2. Problem Analysis (DFD)
After identifying the problem, it needs to be divided into parts or modules. The following things need to be
done in this step:

• Building mathematical model of the problem [DFD, decision tree, system flowchart etc.]
• Timeline
3. Program Design (Algorithm/Flowchart)
Identify various processing steps needed to solve the problem and represent them in a particular way
(algorithm, pseudo code, flow chart etc.).

• Input design
• Output design
• Relationship between input and output design

Page 6
Course Title: Introduction to Computer & Computer Programming Course Code: CCE-1201

4. Program Development (Coding)


Add the syntax of the programming language to the above representation and it becomes the program.

5. Program Implementation (deploying program)


• Buying required hardware
• Testing program
• Debugging program
• Installing program/software

6. Documentation
Program needs to be documented for future use. Following documents need to be kept:

• Explanation of program
• Flowchart
• Source code
• Steps to run the program
• Details of testing and result

7. Program Maintenance
• Upgrading the program
• Changing program
• Supporting users

Program Design (Algorithm/Flowchart/Pseudo-code)


Before coding
Algorithm
It is a complete step by step representation of the solution of the problem, represented in English like language.
For example, we want to solve the following problem:

Problem: Write a program to find the average of n numbers

After analysis of this problem, we can write an abstract algorithm as

1. Read the value of n


2. Read n numbers
3. Add these n numbers
4. Divide the addition result by n to get the average
5. Print the average

In the above algorithm, steps 2 and 3 are not simple. Both of these require repetition of the work. The details
of that repetition can also be specified to make the algorithm clearer.

Page 7
Course Title: Introduction to Computer & Computer Programming Course Code: CCE-1201
The detailed algorithm is written below which will include the repetition details as well:

1. Read the value of n


2. Assign 0 to sum
3. Repeat n times
4. Read numbers
5. Add number to sum
6. End repeat
7. Divide sum by n to get the average
8. Print the average

This algorithm has every step equivalent to some programming language instruction and thus, is a
complete solution of the problem.

Pseudo Code
Another useful representation of the detailed step is pseudo code. It is a more formal representation than the
algorithm.

All pseudo code will start with keyword START and complete with keyword STOP or END.

The above written detailed algorithm can be written in form of pseudo code as follows:
1. START
2. Read n
3. Sum 0
4. for i 1 to n do
5. read number i
6. sum sum + number i
7. end for
8. average sum/n
9. print average
10. STOP

Flow Chart
Flowchart is a diagrammatic representation of an algorithm, process or program. Flowchart is very helpful in
writing program and explaining program to others.

Page 8
Course Title: Introduction to Computer & Computer Programming Course Code: CCE-1201
Symbols Used In Flowchart

Different symbols are used for different states in flowchart, for example: Input/output and decision making
has different symbols. The table below describes all the symbols that are used in making flowchart

Symbol Purpose Description

Flow line Used to indicate the flow of logic by connecting symbols.

Terminal(Stop/Start) Used to represent start and end of flowchart.

Input/output Used for input and output operation.

Processing Used for arithmetic operations and data-manipulations.

Used to represent the operation in which there are two alternatives, true
Decision
and false.

On-page Connector Used to join different flow line

Off-page Connector Used to connect flowchart portion on different page.

Predefined
Used to represent a group of statements performing one processing task.
Process/Function

Example
The flow chart for the above mentioned problem of finding average of n numbers will be drawn s shown in
the following figure:

Page 9
Course Title: Introduction to Computer & Computer Programming Course Code: CCE-1201

Calculate the sum of two numbers [Algorithm and Flowchart]

Find the bigger of two numbers [Algorithm and Flowchart]

Page 10
Course Title: Introduction to Computer & Computer Programming Course Code: CCE-1201

Series: 1+2+3+4+--------------------------------+n [Algorithm and Flowchart]

Exercise: Algorithms and Flowcharts


1) Take two numbers and perform subtraction
2) Take two numbers and perform division
3) Take two numbers and perform multiplication
4) Take two numbers and perform mod
5) Calculate the power of x^y (Using library function pow)
6) Calculate the absolute value of x (Using library function abs)
7) Calculate the square root of x (Using library function sqrt)
8) Calculate area of rectangle
9) Calculate area of circle
10)Calculate area of triangle
11)Calculate the area of triangle (You are given values (a, b, c) of three lines)
12)Convert Centigrade temperature to Fahrenheit
13) Convert Fahrenheit temperature to Centigrade

Page 11
Course Title: Introduction to Computer & Computer Programming Course Code: CCE-1201

Program Development - C Programming Language


For Coding

Define C programming.
C is a high-level and general-purpose programming language that is ideal for developing firmware or portable
applications. Originally intended for writing system software, C was developed at Bell Labs by Dennis
Ritchie for the Unix Operating System in the early 1970s.

C programming is considered as the base for other programming languages, that is why it is known as
mother language.

It can be defined by the following ways:

1. Mother language
2. System programming language
3. Procedure-oriented programming language
4. Structured programming language
5. Mid-level programming language

1) C as a mother language
C language is considered as the mother language of all the modern programming languages because most of
the compilers, JVMs, Kernels, etc. are written in C language, and most of the programming languages
follow C syntax, for example, C++, Java, C#, etc.
It provides the core concepts like the array, strings, functions, file handling, etc. that are being used in
many languages like C++, Java, C#, etc.
2) C as a system programming language
A system programming language is used to create system software. C language is a system programming
language because it can be used to do low-level programming (for example driver and kernel). It is
generally used to create hardware devices, OS, drivers, kernels, etc. For example, Linux kernel is written in
C. It can't be used for internet programming like Java, .Net, PHP, etc.
3) C as a procedural language
A procedure is known as a function, method, routine, subroutine, etc. A procedural language specifies a series of
steps for the program to solve the problem.
A procedural language breaks the program into functions, data structures, etc.
C is a procedural language. In C, variables and function prototypes must be declared before being used.
4) C as a structured programming language
A structured programming language is a subset of the procedural language. Structure means to break a
program into parts or blocks so that it may be easy to understand.
In the C language, we break the program into parts using functions. It makes the program easier to
understand and modify.
5) C as a mid-level programming language
C is considered as a middle-level language because it supports the feature of both low-level and high-level
languages. C language program is converted into assembly code, it supports pointer arithmetic (low-level), but
it is machine independent (a feature of high-level).
A Low-level language is specific to one machine, i.e., machine dependent. It is machine dependent, fast to run.
But it is not easy to understand.
A High-Level language is not specific to one machine, i.e., machine independent. It is easy to understand.

Page 12
Course Title: Introduction to Computer & Computer Programming Course Code: CCE-1201

Structure of a C Program

Every C program consists of one or more modules called functions. One of the functions must be called
main. The program will always begin by executing the main function, which may access other functions. Any
other function definitions must be defined separately, either ahead of or after main.

Each function must contain:

1. A function heading, which consists of the function name, followed by an optional list of arguments,
enclosed in parentheses.

2. A list of argument declarations, if arguments are included in the heading.

3. A compound statement, which comprises the remainder of the function.

The arguments are symbols that represent information being passed between the function and other parts of
the program. (Arguments are also referred to as parameters.)

Each compound statement is enclosed within a pair of braces, i.e., { }. The braces may contain one or more
elementary statements (called expression statements) and other compound statements. Thus compound
statements may be nested, one within another. Each expression statement must end with a semicolon (;).

Comments (remarks) may appear anywhere within a program, as long as they are placed within the delimiters
/* and */ (e.g., /* this is a comment */). Such comments are helpful in identifying the program's principal
features or in explaining the underlying logic of various program features.

Page 13
Course Title: Introduction to Computer & Computer Programming Course Code: CCE-1201

Example: A simple C Program


File: main.c

#include <stdio.h>
int main() {
printf("Hello C Programming\n");
return 0;
}
#include <stdio.h> includes the standard input output library functions. The printf() function is defined
in stdio.h .
int main() The main() function is the entry point of every program in c language.

printf() The printf() function is used to print data on the console.

return 0 The return 0 statement, returns execution status to the OS. The 0 value is used for successful
execution and 1 for unsuccessful execution.

Lesson 8: History and Features of C


History of C Language
C programming language was developed in 1972 by Dennis Ritchie at bell laboratories of AT&T
(American Telephone & Telegraph), located in the U.S.A.
Dennis Ritchie is known as the founder of the c language.
It was developed to overcome the problems of previous languages such as B, BCPL, etc.
Initially, C language was developed to be used in UNIX operating system. It inherits many features of
previous languages such as B and BCPL.
Let's see the programming languages that were developed before C language.

Language Year Developed By

Algol 1960 International Group

BCPL 1967 Martin Richard

B 1970 Ken Thompson

Traditional C 1972 Dennis Ritchie

K&RC 1978 Kernighan & Dennis Ritchie

ANSI C 1989 ANSI Committee

ANSI/ISO C 1990 ISO Committee

C99 1999 Standardization Committee

Page 14
Course Title: Introduction to Computer & Computer Programming Course Code: CCE-1201

Features of C Language
C is the widely used language. It provides many features that are given below.

1. Simple
2. Machine Independent or Portable
3. Mid-level programming language
4. structured programming language
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
10. Extensible

1) Simple
C is a simple language in the sense that it provides a structured approach (to break the problem into parts),
the rich set of library functions, data types, etc.
2) Machine Independent or Portable
Unlike assembly language, c programs can be executed on different machines with some machine specific
changes. Therefore, C is a machine independent language.
3) Mid-level programming language
Although, C is intended to do low-level programming. It is used to develop system applications such as
kernel, driver, etc. It also supports the features of a high-level language. That is why it is known as mid-level
language.
4) Structured programming language
C is a structured programming language in the sense that we can break the program into parts
using functions. So, it is easy to understand and modify. Functions also provide code reusability.
5) Rich Library
C provides a lot of inbuilt functions that make the development fast.
6) Memory Management
It supports the feature of dynamic memory allocation. In C language, we can free the allocated memory at
any time by calling the free() function.
7) Speed
The compilation and execution time of C language is fast since there are lesser inbuilt functions and hence
the lesser overhead.
8) Pointer
C provides the feature of pointers. We can directly interact with the memory by using the pointers. We can
use pointers for memory, structures, functions, array, etc.
9) Recursion
In C, we can call the function within the function. It provides code reusability for every function.
Recursion enables us to use the approach of backtracking.
10) Extensible
C language is extensible because it can easily adopt new features.

Page 15
Course Title: Introduction to Computer & Computer Programming Course Code: CCE-1201

Lesson 9: Steps in C Program


Flow of C Program
The C program follows many steps in execution. To understand the flow of C program well, let us see a
simple program first.

File: simple.c
#include <stdio.h>
int main(){
printf("Hello C Language");
return 0;
}
Let's try to understand the flow of above program by the figure given below.
1) C program (source code) is sent to preprocessor first. The preprocessor is responsible to convert
preprocessor directives into their respective values. The preprocessor generates an expanded source code.
2) Expanded source code is sent to compiler which compiles the code and converts it into assembly code.
3) The assembly code is sent to assembler which assembles the code and converts it into object code. Now
a simple.obj file is generated.
4) The object code is sent to linker which links it to the library such as header files. Then it is converted
into executable code. A simple.exe file is generated.
5) The executable code is sent to loader which loads it into memory and then it is executed. After
execution, output is sent to console.

Page 16
Course Title: Introduction to Computer & Computer Programming Course Code: CCE-1201

printf() and scanf() in C


The printf() and scanf() functions are used for input and output in C language. Both functions are inbuilt
library functions, defined in stdio.h (header file).
printf() function
The printf() function is used for output. It prints the given statement to the console.
The syntax of printf() function is given below:
printf("format string",argument_list);
The format string can be %d (integer), %c (character), %s (string), %f (float) etc.

scanf() function
The scanf() function is used for input. It reads the input data from the console.
scanf("format string", &argument_list);

Page 17
Course Title: Introduction to Computer & Computer Programming Course Code: CCE-1201

Lesson 10: Variables and Constants

What is variable in C?
A variable is a name of the memory location. It is used to store data. Its value can be changed, and it can
be reused many times.
It is a way to represent memory location through symbol so that it can be easily identified.
Let's see the syntax to declare a variable:
type variable_list;
The example of declaring the variable is given below:
int a;
float b;
char c;
Here, a, b, c are variables. The int, float, char are the data types.
We can also provide values while declaring the variables as given below:
int a=10, b=20; //declaring 2 variable of integer type
float f=20.8;
char c='A';

Rules for defining variables


o A variable can have alphabets, digits, and underscore.
o A variable name can start with the alphabet, and underscore only. It can't start with a
digit. o No whitespace is allowed within the variable name.
o A variable name must not be any reserved word or keyword, e.g. int, float, etc.

Valid variable names:


int a;
int _ab;
int a30;
Invalid variable names:
int 2;
int a b;
int long;

Types of Variables in C
There are many types of variables in c:

1. local variable
2. global variable
3. static variable
4. automatic variable
5. external variable

Page 18
Course Title: Introduction to Computer & Computer Programming Course Code: CCE-1201
1. Local Variable

A variable that is declared inside the function or block is called a local variable.

It must be declared at the start of the block.

void function1()
{
int x=10; //local variable
}
You must have to initialize the local variable before it is used.

2. Global Variable

A variable that is declared outside the function or block is called a global variable. Any function can change
the value of the global variable. It is available to all the functions.

It must be declared at the start of the block.

int value=20; //global variable


void function1()
{
int x=10; //local variable
}

3. Static Variable

A variable that is declared with the static keyword is called static variable.

It retains its value between multiple function calls.

void function1()

int x=10; //local variable


static int y=10; //static variable
x=x+1;
y=y+1;
printf("%d, %d", x ,y);
}

If you call this function many times, the local variable will print the same value for each function call, e.g,
11,11,11 and so on. But the static variable will print the incremented value in each function call, e.g. 11,
12, 13 and so on.

Page 19
Course Title: Introduction to Computer & Computer Programming Course Code: CCE-1201
4. Automatic Variable
All variables in C that are declared inside the block, are automatic variables by default. We can explicitly
declare an automatic variable using auto keyword.
void main()
{
int x=10; //local variable (also automatic)
auto int y=20; //automatic variable
}

5. External Variable
We can share a variable in multiple C source files by using an external variable. To declare an external
variable, you need to use extern keyword.

myfile.h
extern int x=10; //external variable (also global)
program1.c
#include "myfile.h"
#include <stdio.h>
void printValue()
{
printf("Global variable: %d", x);
}

Constants in C
Constants refer to fixed values that the program may not alter during its execution. These fixed values are
also called literals. Constants can be of any of the basic data types like an integer constant, a floating
constant, a character constant, or a string literal. There are enumeration constants as well. Constants are
treated just like regular variables except that their values cannot be modified after their definition.

List of Constants in C

Constant Example

Decimal Constant 10, 20, 450 etc.

Real or Floating-point Constant 10.3, 20.2, 450.6 etc.

Octal Constant 021, 033, 046 etc.

Hexadecimal Constant 0x2a, 0x7b, 0xaa etc.

Character Constant 'a', 'b', 'x' etc.

String Constant "c", "c program", "c in javatpoint" etc.

Page 20
Course Title: Introduction to Computer & Computer Programming Course Code: CCE-1201

Defining Constants
There are two simple ways in C to define constants −

• Using #define preprocessor.


• Using const keyword.

1. The #define Preprocessor

Given below is the form to use #define preprocessor to define a constant −


#define identifier value
The following example explains it in detail −
#include <stdio.h>

#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'

int main()
{
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return 0;
}
When the above code is compiled and executed, it produces the following result − value of area : 50

2. The const Keyword


You can use const prefix to declare constants with a specific type as follows −
const type variable = value;

The following example explains it in detail −

#include <stdio.h>
main()
{
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';

int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
}
When the above code is compiled and executed, it produces the following result − value of area : 50
Note that it is a good programming practice to define constants in CAPITALS.

Page 21
Course Title: Introduction to Computer & Computer Programming Course Code: CCE-1201

Differences between #define and const in C?


define is a preprocessor directive. Things defined by #define are replaced by the preprocessor
before compilation begins.

const variables are actual variables like other normal variable.

The big advantage of const over #define is type checking. We can also have pointers to const variables, we can pass
them around, typecast them and any other thing that can be done with a normal variable. One disadvantage that one
could think of is extra space for variable which is immaterial due to optimizations done by compilers.

In general const is a better option if we have a choice. There are situations when #define cannot be replaced by
const. For example, #define can take parameters. #define can also be used to replace some text in a program
with another text

Lesson 11: Data Types and Keywords


Data Types in C
A data type specifies the type of data that a variable can store such as integer, floating, character, etc.

There are the following data types in C language.

Types Data Types

Basic Data Type int, char, float, double

Derived Data Type array, pointer, structure, union

Enumeration Data Type Enum

Void Data Type Void

Page 22
Course Title: Introduction to Computer & Computer Programming Course Code: CCE-1201

Basic Data Types


The basic data types are integer-based and floating-point based. C language supports both signed and
unsigned literals.
The memory size of the basic data types may change according to 32 or 64-bit operating system.
Let's see the basic data types. Its size is given according to 32-bit architecture.

Data Types Memory Size Range

Char 1 byte −128 to 127

signed char 1 byte −128 to 127

unsigned char 1 byte 0 to 255

Short 2 byte −32,768 to 32,767

signed short 2 byte −32,768 to 32,767

unsigned short 2 byte 0 to 65,535

Int 2 byte −32,768 to 32,767

signed int 2 byte −32,768 to 32,767

unsigned int 2 byte 0 to 65,535

short int 2 byte −32,768 to 32,767

signed short int 2 byte −32,768 to 32,767

unsigned short int 2 byte 0 to 65,535

long int 4 byte -2,147,483,648 to 2,147,483,647

signed long int 4 byte -2,147,483,648 to 2,147,483,647

unsigned long int 4 byte 0 to 4,294,967,295

Float 4 byte

Double 8 byte

long double 10 byte

Page 23
Course Title: Introduction to Computer & Computer Programming Course Code: CCE-1201

Type Casting in C
Typecasting allows us to convert one data type into other. In C language, we use cast operator for
typecasting which is denoted by (type).

Syntax:

1. (type)value;

Note: It is always recommended to convert the lower value to higher for avoiding data loss.

Without Type Casting:

int f= 9/4;
printf("f : %d\n", f ); //Output: 2
With Type Casting:
float f=(float) 9/4;
printf("f : %f\n", f ); //Output: 2.250000

Example: Type Casting

Let's see a simple example to cast int value into the float.
#include<stdio.h>
int main(){
float f= (float)9/4;
printf("f : %f\n", f );
return 0;
}
Output:
f : 2.250000

Keywords in C
A keyword is a reserved word. You cannot use it as a variable name, constant name, etc. There are only
32 reserved words (keywords) in the C language.

A list of 32 keywords in the c language is given below:

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

Page 24
Course Title: Introduction to Computer & Computer Programming Course Code: CCE-1201

Lesson 12-13: Operators


Definition of Operator
An operator is simply a symbol that is used to perform operations. There can be many types of operations
like arithmetic, logical, bitwise, etc.

There are following types of operators to perform different types of operations in C language.

o Arithmetic Operators
o Relational Operators o
Shift Operators
o Logical Operators o
Bitwise Operators
o Ternary or Conditional Operators o
Assignment Operator
o Misc Operator

Arithmetic Operators
The following table shows all the arithmetic operators supported by the C language. Assume variable A holds
10 and variable B holds 20 then −

Operator Description Example

+ Adds two operands. A+B=30

− Subtracts second operand from the first. A−B=-10

* Multiplies both operands. A*B=200

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

% Modulus Operator and remainder of after an integer division. B%A=0

++ Increment operator increases the integer value by one. A++ = 11

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

Example: Arithmetic Operators

#include <stdio.h>
main()
{
int a = 21;
int b = 10;
int c ;

Page 25
Course Title: Introduction to Computer & Computer Programming Course Code: CCE-1201

c = a + b;
printf("Line 1 - Value of c is %d\n", c );

c = a - b;
printf("Line 2 - Value of c is %d\n", c );

c = a * b;
printf("Line 3 - Value of c is %d\n", c ); Output:
Line 1 - Value of c is 31
c = a / b; Line 2 - Value of c is 11
printf("Line 4 - Value of c is %d\n", c ); Line 3 - Value of c is 210
Line 4 - Value of c is 2
c = a % b; Line 5 - Value of c is 1
printf("Line 5 - Value of c is %d\n", c );
Line 6 - Value of c is 21
c = a++; Line 7 - Value of c is 22
printf("Line 6 - Value of c is %d\n", c );

c = a--;
printf("Line 7 - Value of c is %d\n", c );
}

Relational Operators
The following table shows all the relational operators supported by C. Assume variable A holds 10 and
variable B holds 20 then −

Operator Description Example

== Checks if the values of two operands are equal or not. If yes, (A == B) is not true.
then the condition becomes true.

!= Checks if the values of two operands are equal or not. If the (A != B) is true.
values are not equal, then the condition becomes true.

> Checks if the value of left operand is greater than the value (A > B) is not true.
of right operand. If yes, then the condition becomes true.

< Checks if the value of left operand is less than the value of (A < B) is true.
right operand. If yes, then the condition becomes true.

>= Checks if the value of left operand is greater than or equal to (A >= B) is not true.
the value of right operand. If yes, then the condition becomes
true.

<= Checks if the value of left operand is less than or equal to the (A <= B) is true.
value of right operand. If yes, then the condition becomes
true.

Page 26
Course Title: Introduction to Computer & Computer Programming Course Code: CCE-1201
Example of relational operators

#include <stdio.h>
main() {
int a = 21;
int b = 10;
int c ;
if( a == b ) {
printf("Line 1 - a is equal to b\n" );
} else {
printf("Line 1 - a is not equal to b\n" );
}

if ( a < b ) {
printf("Line 2 - a is less than b\n" );
Output:
} else {
printf("Line 2 - a is not less than b\n" ); Line 1 - a is not equal to b
} Line 2 - a is not less than b
if ( a > b ) { Line 3 - a is greater than b
printf("Line 3 - a is greater than b\n" ); Line 4 - a is either less than or equal to b
} else { Line 5 - b is either greater than or equal to b
printf("Line 3 - a is not greater than b\n" );
}
/* Lets change value of a and b */
a = 5;
b = 20;
if ( a <= b ) {
printf("Line 4 - a is either less than or equal to b\n" );
}
if ( b >= a ) {
printf("Line 5 - b is either greater than or equal to b\n" );
}
}

Logical Operators
Following table shows all the logical operators supported by C language. Assume variable A holds 1
and variable B holds 0, then −

Operator Description Example

&& Called Logical AND operator. If both the operands are non-zero, (A && B) is false.
then the condition becomes true.

|| Called Logical OR Operator. If any of the two operands is non- (A || B) is true.


zero, then the condition becomes true.

! Called Logical NOT Operator. It is used to reverse the logical !(A && B) is true.
state of its operand. If a condition is true, then Logical NOT
operator will make it false.

Page 27
Course Title: Introduction to Computer & Computer Programming Course Code: CCE-1201
Example: Logical Operators

#include <stdio.h>
main() {
int a = 5;
int b = 20;
int c ;
if ( a && b ) {
printf("Line 1 - Condition is true\n" );
}
if ( a || b ) {
printf("Line 2 - Condition is true\n" );
}
/* lets change the value of a and b */
a = 0;
Output:
b = 10;
if ( a && b ) { Line 1 - Condition is true
printf("Line 3 - Condition is true\n" ); Line 2 - Condition is true
} else { Line 3 - Condition is not true
printf("Line 3 - Condition is not true\n" ); Line 4 - Condition is true
}
if ( !(a && b) ) {
printf("Line 4 - Condition is true\n" );
} }

Bitwise Operators
Bitwise operator works on bits and performs bit-by-bit operation. The truth tables for &, |, and ^ is as follows −

p q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1
Assume A = 60 and B = 13 in binary format, they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011

Page 28
Course Title: Introduction to Computer & Computer Programming Course Code: CCE-1201
The following table lists the bitwise operators supported by C. Assume variable 'A' holds 60 and variable
'B' holds 13, then −

Operator Description Example

& Binary AND Operator copies a bit to the result if it (A & B) = 12, i.e., 0000
exists in both operands. 1100

| Binary OR Operator copies a bit if it exists in either (A | B) = 61, i.e., 0011 1101
operand.

^ Binary XOR Operator copies the bit if it is set in one (A ^ B) = 49, i.e., 0011 0001
operand but not both.

~ Binary One's Complement Operator is unary and has (~A ) = ~(60), i.e,. -0111101
the effect of 'flipping' bits.

<< Binary Left Shift Operator. The left operands value is


moved left by the number of bits specified by the A << 2 = 240 i.e., 1111 0000
right operand.

>> Binary Right Shift Operator. The left operands value


is moved right by the number of bits specified by the
A >> 2 = 15 i.e., 0000 1111
right operand.

Example of Bitwise Operators

#include <stdio.h>
main() {
unsigned int a = 60; /* 60 = 0011 1100 */
unsigned int b = 13; /* 13 = 0000 1101
*/ int c = 0;

c = a & b; /* 12 = 0000 1100 */


printf("Line 1 - Value of c is %d\n", c );

c = a | b; /* 61 = 0011 1101 */
printf("Line 2 - Value of c is %d\n", c );
Output:
c = a ^ b; /* 49 = 0011 0001 */
printf("Line 3 - Value of c is %d\n", c ); Line 1 - Value of c is 12
Line 2 - Value of c is 61
c = ~a; /*-61 = 1100 0011 */ printf("Line Line 3 - Value of c is 49
4 - Value of c is %d\n", c ); Line 4 - Value of c is -61
Line 5 - Value of c is 240
c = a << 2; /* 240 = 1111 0000 */ Line 6 - Value of c is 15
printf("Line 5 - Value of c is %d\n", c );
c = a >> 2; /* 15 = 0000 1111 */
printf("Line 6 - Value of c is %d\n", c );
}

Page 29
Course Title: Introduction to Computer & Computer Programming Course Code: CCE-1201

Assignment Operators
The following table lists the assignment operators supported by the C language −

Operator Description Example

= Simple assignment operator. Assigns values C = A + B will assign the value of


from right side operands to left side operand A + B to C

+= Add AND assignment operator. It adds the right


operand to the left operand and assign the result C += A is equivalent to C = C + A
to the left operand.

-= Subtract AND assignment operator. It subtracts


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

*= Multiply AND assignment operator. It


multiplies the right operand with the left
C *= A is equivalent to C = C * A
operand and assigns the result to the left
operand.

/= Divide AND assignment operator. It divides the


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

%= Modulus AND assignment operator. It takes


C %= A is equivalent to C = C %
modulus using two operands and assigns the
A
result to the left operand.

<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2

>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2

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

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

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

Page 30
Course Title: Introduction to Computer & Computer Programming Course Code: CCE-1201
Example Assignment Operators

#include <stdio.h>
main() {

int a = 21;
int c ;

c = a;
printf("Line 1 - = Operator Example, Value of c = %d\n", c );

c += a;
printf("Line 2 - += Operator Example, Value of c = %d\n", c );

c -= a;
printf("Line 3 - -= Operator Example, Value of c = %d\n", c );

c *= a;
printf("Line 4 - *= Operator Example, Value of c = %d\n", c );

c /= a;
printf("Line 5 - /= Operator Example, Value of c = %d\n", c );

c = 200; Output:
c %= a; Line 1 - = Operator Example, Value of c = 21
printf("Line 6 - %= Operator Example, Value of c = %d\n", c ); Line 2 - += Operator Example, Value of c = 42
Line 3 - -= Operator Example, Value of c = 21
c <<= 2; Line 4 - *= Operator Example, Value of c = 441
printf("Line 7 - <<= Operator Example, Value of c = %d\n", c ); Line 5 - /= Operator Example, Value of c = 21
Line 6 - %= Operator Example, Value of c = 11
Line 7 - <<= Operator Example, Value of c = 44
c >>= 2; Line 8 - >>= Operator Example, Value of c = 11
printf("Line 8 - >>= Operator Example, Value of c = %d\n", c ); Line 9 - &= Operator Example, Value of c = 2
Line 10 - ^= Operator Example, Value of c = 0
c &= 2; Line 11 - |= Operator Example, Value of c = 2
printf("Line 9 - &= Operator Example, Value of c = %d\n", c );

c ^= 2;
printf("Line 10 - ^= Operator Example, Value of c = %d\n", c );

c |= 2;
printf("Line 11 - |= Operator Example, Value of c = %d\n", c );
}

Page 31
Course Title: Introduction to Computer & Computer Programming Course Code: CCE-1201

Misc Operators: sizeof & ternary

Besides the operators discussed above, there are a few other important operators including sizeof and
? : supported by the C Language.

Operator Description Example

sizeof() sizeof(a), where a is integer, will


Returns the size of a variable.
return 4.

& &a; returns the actual address of the


Returns the address of a variable.
variable.

* Pointer to a variable. *a;

?: If Condition is true? then value X :


Conditional Expression.
otherwise value Y

Example: Misc Operators

#include <stdio.h>

main() {

int a = 4;
short b;
double c;
int* ptr;

/* example of sizeof operator */


printf("Line 1 - Size of variable a = %d\n", sizeof(a) );
printf("Line 2 - Size of variable b = %d\n", sizeof(b) );
printf("Line 3 - Size of variable c= %d\n", sizeof(c) );

/* example of & and * operators */


ptr = &a; /* 'ptr' now contains the address of 'a'*/
printf("value of a is %d\n", a);
printf("*ptr is %d.\n", *ptr);
Output:
/* example of ternary operator */
Line 1 - Size of variable a = 4
a = 10;
Line 2 - Size of variable b = 2
b = (a == 1) ? 20: 30;
Line 3 - Size of variable c= 8
printf( "Value of b is %d\n", b );
value of a is 4
*ptr is 4.
b = (a == 10) ? 20: 30;
Value of b is 30
printf( "Value of b is %d\n", b );
Value of b is 20
}

Page 32
Course Title: Introduction to Computer & Computer Programming Course Code: CCE-1201

Precedence of Operators in C

The precedence of operator species that which operator will be evaluated first and next. The
associativity specifies the operator direction to be evaluated; it may be left to right or right to left.
Let's understand the precedence by the example given below:

int value=10+20*10;

The value variable will contain 210 because * (multiplicative operator) is evaluated before + (additive operator).
The precedence and associativity of C operators is given below:

Category Operator Associativity

Postfix ()[]->.++-- Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational <<=>>= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

Page 33
Course Title: Introduction to Computer & Computer Programming Course Code: CCE-1201

Lesson 14: Comments and Escape Sequence


Comments in C
Comments in C language are used to provide information about lines of code. It is widely used for
documenting code. There are 2 types of comments in the C language.

1. Single Line Comments


2. Multi-Line Comments
1. Single Line Comments
Single line comments are represented by double slash //. Let's see an example of a single line comment in C.

#include<stdio.h>
int main(){
//printing information Output:
printf("Hello C"); Hello C
return 0;
}

2. Multi Line Comments


Multi-Line comments are represented by slash asterisk /* ... */. It can occupy many lines of code, but it can't
be nested. Syntax:
/*
code
to be commented
*/
Let's see an example of a multi-Line comment in C.
#include<stdio.h>
int main(){
/*printing information
Multi-Line Comment*/ Output:
printf("Hello C"); Hello C
return 0;
}

Escape Sequence in C
An escape sequence in C language is a sequence of characters that doesn't represent itself when used
inside string literal or character.

It is composed of two or more characters starting with backslash \. For example: \n represents new line.

Page 34
Course Title: Introduction to Computer & Computer Programming Course Code: CCE-1201
List of Escape Sequences in C

Escape Sequence Meaning

\a Alarm or Beep

\b Backspace

\f Form Feed

\n New Line

\r Carriage Return

\t Tab (Horizontal)

\v Vertical Tab

\\ Backslash

\' Single Quote

\" Double Quote

\? Question Mark

\nnn octal number

\xhh hexadecimal number

\0 Null

Escape Sequence Example

#include<stdio.h>
int main(){
int number=50;
printf("You\nare\nlearning\n\'c\' language\n\"Do you know C language\"");
return 0; Output:
} You
are
learning
'c' language
"Do you know C language"

Page 35
Course Title: Introduction to Computer & Computer Programming Course Code: CCE-1201

Lesson 15: Class Test 1


Based on Lesson 12, 13 and 14

Review Questions for Section II


Q1. Define C programming.
Q2. "C is considered as a Structured programming language." Justify this statement.
Q3. "C is considered as a mid-level programming language." Justify this statement.
Q4. Illustrate the structure of a basic C program.
Q5. Explain the process of developing a program.
Q6. What are the differences between Algorithms and Psedo-code?
Q7. Explain Software Development Life Cycle (SDLC).
Q8. List some widely used features of C language.
Q9. The following code depicts a simple C program
#include <stdio.h>
int main(){
printf("Hello C Language");
return 0;
}
Write the steps to execute this program.
Q10. Explain the differences between printf() and scanf() function.
Q11. Write a C program to print cube of a given number.
Q12. Write a C program to print sum of two numbers.
Q13. What is variable in C?
Q14. What are the rules for defining a variable in C?
Q15. Explain the differences between local and global variable.
Q16. Write short notes on:
a) local variable
b) global variable
c) static variable
d) automatic variable
e) external variable
Q17. Define constants.
Q18. Explain the Differences between #define preprocessor and const keyword used in C?
Q19. Define data types.
Q20. List and explain four basic data types used in c language.
Q21. Define type casting.
Q22. Define operators.
Q23. Write a C program to find whether a given year is leap year or not.
Q24. Define comments.
Q25. How many types of comments are used in C language? Explain each type of comment.
Q26. What is escape sequence?
Q27. List commonly used escape sequence in C programming language.
Q28. Plus class lectures

Page 36

You might also like