0% found this document useful (0 votes)
7 views

Chapter1-Introduction To Programming in C

Uploaded by

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

Chapter1-Introduction To Programming in C

Uploaded by

atakilti
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 55

Chapter1_Introduction To Programming 06/25/2024

Chapter One

INTRODUCTION TO PROGRAMMING IN C

1
Chapter1_Introduction To Programming 06/25/2024

WHAT IS COMPUTER PROGRAM?

 Before you understand what is computer programming, you need to


understand what is computer program?
 Definition:
 A computer program is a sequence of instructions written using a Computer
Programming Language to perform a specified task by the computer
 Let’s see two important terms, which I have used in the above definition:
 Sequence of instructions
 Computer Programming Language
 To understand these terms, consider a situation when someone asks you
about how to go to a nearby Square, Romanat. What exactly do you do to
tell him the way to go to Romanat?
 You will use Human Language to tell the way to go to Romanat something
as follows:
 First go straight to MU main campus, after 2.5 kilometers, take left from the main
campus and then drive around 2.5 kilometers and you will find Romanat Avenue
at the left.
2
Chapter1_Introduction To Programming 06/25/2024

WHAT IS COMPUTER PROGRAM?

 Here, you have used English Language to give several steps to be taken to reach to ROMANAT.
If they will be followed in the following sequence, then you will reach ROMANAT:
1. Go straight to MU main campus
2. Drive 2.5 kilometers
3. Take left
4. Drive around 2.5 kilometers
5. Search for ROMANAT at your left side
 Now, try to map the situation with computer program.
 Following is a simple program written in C programming Language:
 printf( "Hello, World!“);
 Above computer program instructs computer to print "Hello, World!" on computer screen.
 A computer program is also called a computer software, which can range from two lines to millions of
lines of instructions.
 Computer program instructions are also called program source code and computer programming is also
called program coding.
 A computer machine without a computer program is just a dump box and thus computer program brings a
computer machine to live state.
 Like human has several languages to communicate their message, computer scientists have
developed several computer-programming languages to provide instructions to the computer (i.e.,
to write computer programs).
3
Chapter1_Introduction To Programming 06/25/2024

WHAT IS COMPUTER PROGRAMMING?


 If you understood what is computer program, then the act of writing computer
programs is called computer programming.
 As mentioned earlier, there are 100s of programming languages, which can be
used to write computer programs and following are few of them: Java, C, C++,
Python, PHP, Perl, Ruby
 What Computer Program can do?
 Today computer programs are being used in almost every field, household,
agriculture, medical, entertainment, defense, communication, etc. Following are
few applications of computer programs:
 MS Word, MS Excel, Adobe Photoshop, Internet Explorer, Chrome, etc., are example
of computer programs.
 Computer programs are being used to develop graphics and special effects in movie
making.
 Computer programs are being used to perform Ultrasounds, X-Rays, and other medical
examinations.
 Computer programs are being used in our mobile phones for SMS, Chat, and voice
communication.
4
Chapter1_Introduction To Programming 06/25/2024

WHAT IS ALGORITHM?

 From programming point of view, an algorithm is a step-by-step procedure to resolve any


problem. An algorithm is an effective method expressed as a finite set of well-defined instructions.
 Thus, a computer programmer lists down all the steps required to resolve a problem before
jumping to write actual code. Following is a simple example of an algorithm to find out a largest
number from a given list of numbers:
1. Get a list of numbers L1, L2, L3....LN
2. Assume L1 is the largest, Largest = L1
3. Take next number Li from the list and do the following
4. If Largest is less than Li
5. Largest = Li
6. If Li is last number from the list then
7. Print value stored in Largest and come out
8. Else repeat same process starting from step 3
 most of the Human Interface Languages (Tigrigna, English, Amharic, Oromipha, etc.) are made of
several elements like verbs, nouns, adjectives, adverbs, propositions, and conjunctions, etc.
 Similar to Human Interface Languages, Computer Programming Languages are also made of
several elements like: Programming Environment, Basic Syntax, Data Types, Variables,
Keywords, Basic Operators, Decision Making, Loops etc.
5
Chapter1_Introduction To Programming 06/25/2024

COMPUTER PROGRAMMING ENVIRONMENT

 it is the first thing we need to start programming with any Programming


Language.
 When we are saying Environment Setup, it simply means we need to have a
base on top of which we can do our programming. Thus, we need to have
required software setup, i.e., installation on our PC which will be used to
write our Computer Program, Compile and Execute it. For example, if you
need to browse Internet, then you need the following setup on your machine:
 A working Internet Connection to connect to the Internet.
 Web Browser like Internet Explorer, Chrome, or Safari, etc.
 Similar way, you will need following setup to start with programming using
any programming language.
 A text editor to create computer program.
 This is a Software, which will be used to write your computer program. Your Windows
machine must have a Notepad, which can be used to type your program
 A compiler to compile program into binary format.
 An interpreter to execute program directly.
6
Chapter1_Introduction To Programming 06/25/2024

WHAT IS COMPILER?

 The conversion from text program to binary file is done by another software
called Compiler and this process of conversion from text formatted program to
binary format file is called program compilation. Finally, you can execute
binary file to perform the programmed task. Following flow diagram gives an
illustration of the process:
 So, if you are going to write
your program in any such
language, which needs
compilation like C, C++,
Java and Pascal, etc., then
you will need to install their
compilers before you start
programming in such
languages.

7
Chapter1_Introduction To Programming 06/25/2024

WHAT IS INTERPRETER?

 There are programming languages like Python, PHP and Perl, which do not
need any compilation into binary format, rather an interpreter can be used to
read such program line by line and execute it directly without any further
conversion.
 So, if you are going to write
your program in any such language, which
does not need compilation like PHP, Python,
Perl, and Ruby, etc., then you will need to
install their interpreters before you start
Programming in such languages.

8
Chapter1_Introduction To Programming 06/25/2024

COMPUTER PROGRAMMING BASIC SYNTAX

 Hello World Program in C


 This little Hello World program will help us in understanding various basic concepts related to C
Programming.
#include <stdio.h>
int main()
{
/* printf() function to write Hello, World! */
printf( "Hello, World!" );
return 0;
}
 Try to change the content inside printf() instead of Hello World! and then check its result. It just
prints whatever you keep inside two double quotes.
 For now just forget about #include <stdio.h> statement, but keep a note that you have to put this
statement at the top of a C program.
 So, every C program starts with main(), which is called main function and then it is followed by a
left curly brace. Rest of the program instruction is written in between and finally a right curly brace
ends the program.
 The coding part inside these two curly braces is called program body. The left curly brace can be in
the same line as main(){ or in the next line like it has been mentioned in the above program.
9
Chapter1_Introduction To Programming 06/25/2024

EXPLANATION OF HOW THIS PROGRAM WORKS

 Every program starts from main() function.


 printf() is a library function to display output which only
works if #include<stdio.h>is included at the beginning.
 Here, stdio.h is a header file (standard input output header
file) and #include is command to paste the code from the
header file when necessary. When compiler encounters
printf() function and doesn't find stdio.h header file,
compiler shows error.
 Code return 0; indicates the end of program.
 You can ignore this statement but, it is good programming
practice to use return 0;.
10
Chapter1_Introduction To Programming 06/25/2024

COMPUTER PROGRAMMING BASIC SYNTAX


 Functions: are small units of programs and they are used to carry out a specific
task. For example, above program makes use of two functions (a) main() and (b)
printf(). Here, function main() provides the entry point for the program execution
and another function printf() is being used to print an information on computer
screen.
 Comments: A C program can have statements enclosed inside /*.....*/. Such
statements are called comments and these comments are used to make program
user friendly and easy to understand the program. Good thing about comments is
that they are completely ignored by compilers and interpreters
 Whitespaces
 When we write a program using any programming language, we use various
printable characters to prepare programming statements. These printable
characters are a, b, c,......z, A, B, C,.....Z, 1, 2, 3,...... 0, !, @, #, $, %, ^, &, *, (, ),
-, _, +, =, \, |, {, }, [, ], :, ;, <, >, ?, /, \, ~. `. ", '.
 Apart from these characters, there are some characters which we use very
frequently but they are invisible in your program and these characters are spaces,
tabs (\t), new lines(\n). These characters are called whitespaces.
11
Chapter1_Introduction To Programming 06/25/2024

COMPUTER PROGRAMMING BASIC SYNTAX


 Semicolons: Every individual statement in C Program, must be ended with a semicolon ; For example, if you want
to write "Hello, World!" twice, then it will be written as follows:
#include <stdio.h>
main()
{
/* printf() function to write Hello, World! */
printf( "Hello, World!\n" );
printf( "Hello, World!" );
}
 This program will produce the following result:
Hello, World!
Hello, World!
Here, we are using new line character \n in first printf() function to create a new line.
Let us see what happens if I do not use this new line character:
#include <stdio.h>
main()
{
/* printf() function to write Hello, World! */
printf( "Hello, World!" );
printf( "Hello, World!" );
}
 This program will produce following result: 12
Chapter1_Introduction To Programming 06/25/2024

PROGRAM EXPLANATION
 Let's try to understand how the above C program to print “Hello, World!” works.
First the above program is converted into a binary format using C compiler. So
let’s save this code as test.c file name and compile it as follows:
$gcc test.c -o demo
 If there is any grammatical error (Syntax errors in computer terminologies), then
we fix it before converting it into binary format. If everything goes fine then it
produces binary file called demo. Finally we execute produced binary demo as
follows:
$./demo
Which produces following result:
Hello, World!
 Here, when we execute binary demo file, what computer does is, it enters inside
the program starting from main() and encounters a printf() statements. So printf()
function instructs computer to print the given line at the computer screen.
 Finally it encounters a right curly brace which indicates the end of main()
function and exit of the program
13
Chapter1_Introduction To Programming 06/25/2024

PROGRAM EXPLANATION
 Syntax Error
 If you do not follow rules defined by the programming language then at

the time of compilation you will get syntax error and program will not be
compiled. From syntax point of view, even a single dot or comma or
single semicolon matters and you should take care of such small syntax as
well. Following is Hello, World! program but here semicolon is missing,
when we compile following program:
#include <stdio.h>
main()
{
printf("Hello, World!")
}
 This program will produce following result:

main.c: In function 'main':


main.c:7:1: error: expected ';' before '}' token 14
Chapter1_Introduction To Programming 06/25/2024

COMPUTER PROGRAMMING - DATA TYPES


 As its name indicates, a data type represents a type of the data which you can process using
your computer program. It can be numeric, alphanumeric, decimal, etc. Let's take one example
where we want to record student information in a notebook. Here is following important
information, which we can record:
Name: Zara Ali
ClassYear: 1st
Section: J
Age: 18
Weight:56.75
Sex: F
 This example is dealing with a mix of different data. Let's put it as follows:
 Student name "Zara Ali" is a sequence of characters which is also called a string.
 Student class “1st " has been represented by a mix of integer and a string of two characters. Such a mix
is called alphanumeric.
 Student section has been represented by single character which is 'J'.
 Student age has been represented by integer number which is 18.
 Student weight has been represented by floating number which is 56.75.
 Student sex has been represented by a single character which is 'F'.
 Programming languages use different keywords to specify different data types. For example C
and Java programming languages use int to specify integer data whereas char specifies 15a
Chapter1_Introduction To Programming 06/25/2024

COMPUTER PROGRAMMING - DATA TYPES


 Here are few common data types supported by C programming language:
 These data types are called primitive data types and you can use these data
types to build more complex data types, which are called user-defined data
type, for example a string will be a sequence of characters.
Type Keywor Value range which can be represented by this data type
d
Character char -128 to 127 or 0 to 255 or 1 byte
Number int -32, 768 to 32, 767 or -2, 147, 483, 648 to
2, 147, 483, 647 or 2 to 4bytes
Small short -32, 768 to 32, 767 or 2bytes
Number
Long Number long -2, 147, 483, 648 to
2, 147, 483, 647 or 4 bytes

Floating float 1.2E-38 to 3.4E38 till 6 decimal places


Number
16
Chapter1_Introduction To Programming 06/25/2024

DIFFERENCE BETWEEN FLOAT AND DOUBLE

 Generally the size of float (Single precision float data


type) is 4 bytes and that of double (Double precision float
data type) is 8 bytes. Floating point variables has a
precision of 6 digits whereas the precision of double is 14
digits.
 Note: Precision describes the number of significant
decimal places that a floating value carries.
 float var2;
 double var3;
 Here, both var2 and var3 are floating type variables.
 In C, floating values can be represented in exponential
form as well. For example: float var3=22.442e2
17
Chapter1_Introduction To Programming 06/25/2024

QUALIFIERS
 Sign qualifiers:
 Whether a variable can hold only positive value or both values is specified
by sign qualifiers. Keywords signed and unsigned are used for sign
qualifiers.
 unsigned int a; // unsigned variable can hold zero and positive values only.
 It is not necessary to define variable using keyword signed because, a
variable is signed by default.
 Sign qualifiers can be applied to only int and char data types.
 For a int variable of size 4 bytes it can hold data from -2 31 to 231-1 but,
if that variable is defined unsigned, it can hold data from 0 to 2 32 -1.
 Constant qualifiers
 Constant qualifiers can be declared with keyword const.
 An object declared by const cannot be modified.
 const int p=20; The value of p cannot be changed in the program.

18
Chapter1_Introduction To Programming 06/25/2024

QUALIFIERS

 Qualifiers alters the meaning of base data types to


yield a new data type.
 Size qualifiers:
 Size qualifiers alters the size of basic data type. The
keywords long and short are two size qualifiers. For
example: long int i;
 The size of int is either 2 bytes or 4 bytes but,
when long keyword is used, that variable will be
either 4 bytes or 8 bytes. If the larger size of
variable is not needed then, short keyword can be
used in similar manner as long keyword.
19
Chapter1_Introduction To Programming 06/25/2024

COMPUTER PROGRAMMING - VARIABLES


 Variables are the names you give to computer memory locations which are used to store values in a computer program. For example,
assume you want to store two values 10 and 20 in your program and at later stage you want to use these two values. Let's see how you
will do it, here are the following three simple steps:
 Create variables with appropriate names.
 Store your values in those two variables.
 Retrieve and use stored values from the variables.
 Creating variables: is also called declaring variables in C programming language. Different programming languages have different
ways of creating variables inside your program. For example, C programming language has the following simple way of creating
variables:
#include <stdio.h>
main()
{
int a;
int b;
}
 Above program creates two variables, i.e., reserves two memory locations with names a and b. We created these variables using int
keyword to specify variable data type which means we want to store integer values in these two variables. Similar way, you can
create variables to store long, float, char or any other data type. For example:
/* variable to store long value */
long a;
/* variable to store float value */
float b;
 You can create variables of similar type by putting them in a single line but separated by comma as follows:
#include <stdio.h>
main()
{
int a, b; 20
Chapter1_Introduction To Programming 06/25/2024

COMPUTER PROGRAMMING - VARIABLES


 Following are few important points to remember about variables:
 A variable name can hold a single type of value. For example, if variable a has
been defined int type, then it can store only integer.

 C programming language requires a variable creation, i.e., declaration before its


usage in your program. You can not use a variable name in your program without
creating it.

 You can use a variable name only once inside your program. For example, if a
variable a has been defined to store an integer value, then you can not define a
again to store any other type of value.

 You can give any name to a variable like age, sex, salary, year1990 or anything
else you like to give, and start their names using alphabets only instead of digit.
 Almost none of the programming languages allow to start their variable names
with a digit, so 1990year will not be a valid variable name where as year1990 or
ye1990ar are valid variable names.
21
Chapter1_Introduction To Programming 06/25/2024

STORING VALUES IN VARIABLES


#include <stdio.h>
main()
{
int a;
int b;
a = 10; /* 10 is being stored in variable a */
b = 20; /* 20 is being stored in variable b*/
}
 we keep variable name in the left hand side of an equal sign = and

whatever value we want to store in the variable, we keep that value in the
right hand side.
 Now variable a has value 10 and variable b has value 20.

 In other words we can say, when the above program is executed, the
memory location named a will hold 10 and memory location b will hold
20. 22
Chapter1_Introduction To Programming 06/25/2024

INPUT OUTPUT (I/O)


 ANSI standard has defined many library functions for input and output in C language. Functions printf() and scanf() are the most
commonly used to display out and take input respectively.
 Let us consider an example:
#include <stdio.h> //This is needed to run printf() function.
int main()
{
printf("C Programming"); //displays the content inside quotation
return 0;
}

Output
C Programming

 Explanation of How this program works


1. Every program starts from main() function.
2. printf() is a library function to display output which only works if #include<stdio.h> is included at the
beginning.

3. Here, stdio.h is a header file (standard input output header file) and #include is command to paste the
code from the header file when necessary. When compiler encounters printf() function and doesn't find
stdio.h header file, compiler shows error.

4. Code return 0; indicates the end of program. You can ignore this statement but, it is good programming
practice to use return 0;.
23
Chapter1_Introduction To Programming 06/25/2024

I/O OF DATA TYPES IN C


#include<stdio.h>
int main()
 I/O of integers in C {
#include<stdio.h> int c;
int main() printf("Enter a number\n");
scanf("%d", &c);
{
printf("Number=%d", c);
int c=5; return 0;
printf("Number=%d“, c); }
return 0; Output
Enter a number
} 4
Output Number=4
 Number=5 The scanf() function is used to take input from
user. In this program, the user is asked a input
 Inside quotation of and value is stored in variable c. Note the '&'
printf() there, is a sign before c. &c denotes the address of c and
value is stored in that address.

conversion format string "%d"


(for integer).
 If this conversion format string matches with remaining argument, i.e, c in this case,
24
Chapter1_Introduction To Programming 06/25/2024

CONTINUED…
•I/O of characters and ASCII code
 I/O of floats in C
#include <stdio.h> #include <stdio.h>
int main() int main()
{
{ char var1;
float a; printf("Enter character: ");
printf("Enter value: "); scanf("%c",&var1);
printf("You entered %c.",var1);
scanf("%f",&a); return 0;
printf("Value=%f",a); }
//%f is used for floats instead of %d
Output
return 0; Enter character: g
} You entered g.
Output Conversion format string "%c" is used in case
of characters.
Enter value: 23.45
Value=23.450000
Conversion format string "%f" is used for floats to take input and to display floating
value of a variable. 25
Chapter1_Introduction To Programming 06/25/2024

I/O OF CHARACTERS AND ASCII CODE

#include <stdio.h>
int main()
{
char var1;
printf("Enter character: ");
scanf("%c",&var1);
printf("You entered %c.",var1);
return 0;
}
Output
Enter character: g
You entered g.
Conversion format string "%c" is used in case of characters. 26
Chapter1_Introduction To Programming 06/25/2024

CONTD
 When character is typed in the above program, the character itself is not recorded, a numeric
value(ASCII value) is stored. And when we displayed that value by using "%c", that character
is displayed.
#include <stdio.h>
int main()
{
char var1;
printf("Enter character: ");
scanf("%c",&var1);
printf("You entered %c.\n",var1); /* \n prints the next line(performs work of enter). */
printf("ASCII value of %d",var1);
return 0;
}
Output
Enter character:
g
103
When, 'g' is entered, ASCII value 103 is stored instead of g.
27
Chapter1_Introduction To Programming 06/25/2024

VARIATIONS IN OUTPUT FOR INTEGER AN FLOATS

 Integer and floating-points can be displayed in different formats in C programming as:


#include<stdio.h>
int main()
{
printf("Case 1:%6d\n",9876); /* Prints the number right justified within 6 columns */
printf("Case 2:%3d\n",9876 ) /* Prints the number to be right justified to 3 columns but, there are 4 digits so
number is not right justified */
printf("Case 3:%.2f\n",987.6543); /* Prints the number rounded to two decimal places */
printf("Case 4:%.f\n",987.6543); /* Prints the number rounded to 0 decimal place, i.e, rounded to integer */
printf("Case 5:%e\n",987.6543); /* Prints the number in exponential notation(scientific notation) */
return 0;
}
Output
Case 1: 9876
Case 2: 9876
Case 3: 987.65
Case 4: 988
Case 5: 9.876543e+002
28
Chapter1_Introduction To Programming 06/25/2024

VARIATIONS IN INPUT FOR INTEGER AND FLOATS


#include <stdio.h>
int main()
{
int a,b;
float c,d;
printf("Enter two intgers: "); /*Two integers can be taken from user
at once as below*/
scanf("%d%d",&a,&b);
printf("Enter intger and floating point numbers:"); /*Integer and
floating point number can be taken at once from user as below*/
scanf("%d%f",&a,&c);
return 0;
}
Similarly, any number of inputs can be taken at once from user.
29
Chapter1_Introduction To Programming 06/25/2024

ACCESSING STORED VALUES IN VARIABLES


 If we do not make use of stored values in the variables then there is no point in creating variables and storing values
in them. We know that above program has two variables a and b and they store values 10 and 20, respectively. So
let's try to print the values stored in these two variables. Following is a C program, which prints the values stored in
variables:
#include <stdio.h>
main()
{
int a;
int b;
a = 10;
b = 20;
printf( "Value of a = %d\n", a );
printf( "Value of b = %d\n", b );
}
When above program is executed, it produces the following result:
Value of a = 10
Value of b = 20
 We are making use of %d, which will be replaced with the values of given variable in printf() statements. We can
print both values using a single printf() statement as follows:

printf( "Value of a = %d and value of b = %d\n", a, b );


When above program is executed, it produces the following result:
Value of a = 10 and value of b = 20 30
Chapter1_Introduction To Programming 06/25/2024

EXAMPLES
First let's see how to print various types of numbers available in C programming
language:
#include <stdio.h>
main() Rest of the coding is very obvious but we used %.3f to print
{ float and double, which indicates number of digits after
short s; decimal to be printed. When above program is executed, it
int i; produces the following result:
long l;
float f; s: 10
double d; i: 1000
s = 10; l: 1000000
i = 1000; f: 230.470
l = 1000000; d: 30949.374
f = 230.47;
d = 30949.374;
printf( "s: %d\n", s);
printf( "i: %d\n", i);
printf( "l: %ld\n", l);
printf( "f: %.3f\n", f);
printf( "d: %.3f\n", d);
}
31
Chapter1_Introduction To Programming 06/25/2024

MATH OPERATIONS ON NUMBERS


 Following table lists down various useful built-in mathematical functions
available in C programming language which can be used for various important
mathematical calculations. For example, if you want to calculate square root of
a number for example, 2304, then you have built-in function available to
calculate square root for this number.
Builtin function Purpose

double cos(double); takes an angle (as a double) and returns the


cosine
double sin(double); returns the sine.
double log10(double); takes a number and returns the natural log
of that number.
double pow(double, double); The first is a number you wish to raise and
the second is the power you wish to raise it
to
double sqrt(double); it gives you this square root.
int abs(int); the absolute value of an integer
32
Chapter1_Introduction To Programming 06/25/2024

EXAMPLE
 Following a simple example to show few of the mathematical operations. To utilize
these functions, you need to include the math header file <math.h> header file in your
program in similar way you have included stdio.h:
#include <stdio.h>
#include <math.h>
main() When above program is executed, it produces the
{ following result:
short s;
int i; sin(s): -0.544021
long l; abs(i): -0.544021
float f; floor(f): 230.000000
double d;
s = 10;
sqrt(f): 15.181238
i = 1000; pow(d, 2): 5.635876
l = 1000000;
f = 230.47;
d = 2.374;
printf( "sin(s): %f\n", sin(s));
printf( "abs(i): %f\n", abs(i));
printf( "floor(f): %f\n", floor(f));
printf( "sqrt(f): %f\n", sqrt(f));
printf( "pow(d, 2): %f\n", pow(d, 2));
} 33
Chapter1_Introduction To Programming 06/25/2024

CHARACTERS
 in computer programming any single digit number like 0, 1, 2,....and special characters like $, %,
+, -.... etc., are also treated as characters and to assign them in a character type variable you
simply need to put them inside a single qoutation mark.
 For example, following statement defines a character type variable ch and we assign a value 'a' to
it:
char ch = 'a';
 Here, ch is a variable of character type which can hold a character of the implementation's
character set and 'a' is called character literal or a character constant. Not only a, b, c,....but
when any number like 1, 2, 3.... or any special character like !, @, #, #, $,.... is kept inside a single
quotes, then they will be treated as a character literal and can be assigned to a variable of
character type, so following is a valid statement:
char ch = '1';
 A character data type consumes 8 bits of memory which means you can store anything in a
character whose ASCII value lies in between -127 to 127, so in total it can hold one of 256
different values. Bottom-line is that a character data type can store any of the characters available
on your keyboard including special characters like !, @, #, #, $, %, ^, &, *, (, ), _, +, {, }, etc.
 It's worth to explain it little further that you can keep only a single alphabet or single digit number
inside single quotes and more than one alphabets or digits are not allowed inside single quotes. So
following statements are invalid in C programming:
char ch1 = 'ab';
34
char ch2 = '10';
Chapter1_Introduction To Programming 06/25/2024

EXAMPLE
 Following is a simple example, which shows how to define, assign and print
characters in C Programming language:
#include <stdio.h>
main()
{ Here, we used %c to print a character data type.
char ch1; When above program is executed, it produces the
char ch2; following result:
char ch3; ch1: a
char ch4; ch2: 1
ch1 = 'a'; ch3: $
ch2 = '1'; ch4: +
ch3 = '$';
ch4 = '+';
printf( "ch1: %c\n", ch1);
printf( "ch2: %c\n", ch2);
printf( "ch3: %c\n", ch3);
printf( "ch4: %c\n", ch4);
}

35
Chapter1_Introduction To Programming 06/25/2024

ESCAPE SEQUENCES:
 Many programming languages support a concept called Escape Sequence. So
when a character is preceded by a backslash (\), then it is called an escape
sequence and has special meaning to the compiler. For example, following is a
valid character and it is called new line character:
char ch = '\n';
Escape Description
Sequence
\t Inserts a tab in the text at this point
\b Inserts a backspace in the text at this point.
\n Inserts a newline in the text at this point.
\r Inserts a carriage return in the text at this point.
\f Inserts a form feed in the text at this point.
\’ Inserts a single quote character in the text at this point
\\’’ Inserts a double quote character in the text at this point.
\\ Inserts a backslash character in the text at this point.
36
Chapter1_Introduction To Programming 06/25/2024

EXAMPLE
 Following is a simple example which shows how the compiler interprets an
escape sequence in a print statement:

When this program is executed, it produces the


#include <stdio.h> following result:
main() Test for tabspace and a newline
{ will start here
char ch1;
char ch2;
char ch3;
char ch4;
ch1 = '\t';
ch2 = '\n';
printf( "Test for tabspace %c and a newline %c will start
here", ch1, ch2);
}

37
Chapter1_Introduction To Programming 06/25/2024

C PROGRAMMING RESERVED KEYWORDS

 Here is a table having almost all the keywords supported by C


Programming language:
auto else long switch
break enum register typedef
case extern return union
char float shortunsigned
const for signed void
continue goto sizeof volatile
default if static while
do int struct
double
38
Chapter1_Introduction To Programming 06/25/2024

OPERATORS
 An operator in a programming language is a symbol that tells the
compiler or interpreter to perform specific mathematical, relational
or logical operation and produce final result.
 Arithmetic Operators: Computer programs are widely used for
mathematical calculations. We can write a computer program which
can do simple calculation like adding two numbers (2 + 3) and we
can also write a program, which can solve a complex equation like
P(x) = x4 + 7x3 - 5x + 9.
 These two statements are called arithmetic expressions in a
programming language and plus, minus used in these expressions
are called arithmetic operators and values used in these expressions
like 2, 3 and x, etc., are called operands. Few of the important
arithmetic operators available in C programming language are +, -,
*, / and %(gives remainder of an integer division).
39
Chapter1_Introduction To Programming 06/25/2024

OPERATORS
 Following is a simple example of C Programming to understand above mathematical
operators:
#include <stdio.h> When this program is
main() executed, it produces the
{ following result:
int a=10, b=20 Value of c = 30
c = a + b; Value of c = -10
printf( "Value of c = %d\n", c); Value of c = 200
c = a - b; Value of c = 2
printf( "Value of c = %d\n", c); Value of c = 0
c = a * b;
printf( "Value of c = %d\n", c);
c = b / a;
printf( "Value of c = %d\n", c);
c = b % a;
printf( "Value of c = %d\n", c);
40
Chapter1_Introduction To Programming 06/25/2024

ASSIGNMENT OPERATORS
 The most common assignment operator is =. This operator assigns
the value in right side to the left side. For example:
var=5 //5 is assigned to var
a=c; //value of c is assigned to a
5=c; // Error! 5 is a constant.

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

41
Chapter1_Introduction To Programming 06/25/2024

RELATIONAL OPERATORS
 Following table lists down few of the important relational operators available in C
programming language. Assume variable A holds 10 and variable B holds 20, then:
Operator Description Example
== Checks if the values of two operands are equal (A == B) is not true.
or not, if yes then condition becomes true.

!= Checks if the values of two operands are equal (A != B) is true.


or not, if values are not equal then condition
becomes true.
> Checks if the value of left operand is greater (A > B) is not true.
than the value of right operand, if yes then
condition becomes true.
< Checks if the value of left operand is less than (A < B) is true.
the value of right operand, if yes then
condition becomes true.
>= Checks if the value of left operand is greater (A >= B) is not true.
than or equal to the value of right operand, if
yes then condition becomes true.
<= Checks if the value of left operand is less than (A <= B) is true.
or equal to the value of right operand, if yes
then condition becomes true. 42
Chapter1_Introduction To Programming 06/25/2024

RELATIONAL OPERATORS
#include <stdio.h>
main()
{
Here, lets see one example of C
int a=10, b=20; Programming which makes use of if
/* Here we check whether a is equal to 10 or not */ conditional statement. Though this
if( a == 10 ) statement will be discussed later in a
{ separate chapter, but in short we use if
printf( "a is equal to 10\n");
statement to check a condition and if
}
/* Here we check whether b is equal to 10 or not */
condition is true then body of if
if( b == 10 ) statement is executed otherwise body of
{ if statement is skipped.
printf( "b is equal to 10\n");
} When this program is executed, it
/* Here we check if a is less b than or not */ produces the following result:
if( a < b )
a is equal to 10
{
printf( "a is less than b\n");
a is less than b
} a is not equal to b
/* Here we check whether a and b are not equal */
if( a != b )
{
printf( "a is not equal to b\n");
}
} 43
Chapter1_Introduction To Programming 06/25/2024

LOGICAL OPERATORS

 Logical operators help us in taking decision based on certain conditions.


Suppose we want to combine the result of two conditions, then logical AND
and OR logical operators help us in giving final result. 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

&& (A && B) is false.


Called Logical AND operator. If both the operands are
non-zero, then condition becomes true.
|| Called Logical OR Operator. If any of the two (A || B) is true.
operands is non-zero, then condition becomes true.

! Called Logical NOT Operator. Use to reverses the !(A && B) is true.
logical state of its operand. If a condition is true
then Logical NOT operator will make false
44
Chapter1_Introduction To Programming 06/25/2024

LOGICAL OPERATORS
#include <stdio.h> understand all the
main() logical operators
{ available in C
int a = 1; programming
language:
int b = 0;
if ( a && b ) When you compile
{ and execute the above
pintf("This will never print because condition is false\n" ); program, it produces
the following result:
}
if ( a || b ) •This will be printed
{ print because
printf("This will be printed print because condition is true\n" ); condition is true
} •This will be printed
print because
if ( !(a && b) ) condition is true
{
printf("This will be printed print because condition is true\n" );
}
} 45
Chapter1_Introduction To Programming 06/25/2024

THE SIZEOF OPERATOR


 It is a unary operator which is used in finding the size of data type, constant,
arrays, structure etc. For example:
#include <stdio.h> Output
Size of int=4 bytes
int main() Size of float=4 bytes
{ Size of double=8 bytes
int a; Size of char=1 byte
float b;
double c;
char d;
printf("Size of int=%d bytes\n",sizeof(a));
printf("Size of float=%d bytes\n",sizeof(b));
printf("Size of double=%d bytes\n",sizeof(c));
printf("Size of char=%d byte\n",sizeof(d));
return 0;
}
46
Chapter1_Introduction To Programming 06/25/2024

CONDITIONAL OPERATOR
 Conditional operator takes three operands and consists of two symbols ? and : . Conditional operators are used
for decision making in C. For example:
c=(c>0)?10:-10;
 If c is greater than 0, value of c will be 10 but,
 if c is less than 0, value of c will be -10 Output
#include <stdio.h> Enter 1 if the year is leap year
int main() otherwise enter n: 1
Number of days in February = 29
{
char feb;
int days;
printf("Enter 1 if the year is leap year otherwise enter 0: ");
scanf("%c",&feb);
days=(feb==‘1’)?29:28;
/*If test condition (feb==‘1') is true, days will be equal to 29. */
/*If test condition (feb==‘1') is false, days will be equal to 28. */
printf("Number of days in February = %d",days); return 0;
}
47
Chapter1_Introduction To Programming 06/25/2024

INCREMENT AND DECREMENT OPERATORS

 In C, ++ and - - are called increment and decrement


operators respectively. Both of these operators are
unary operators, i.e, used on single operand. ++
adds 1 to operand and -- subtracts 1 to operand
respectively.
 For example:

Let a=5 and b=10


 a++; //a becomes 6
 a--; //a becomes 5
 ++a; //a becomes 6
 --a; //a becomes 5 48
Chapter1_Introduction To Programming 06/25/2024

DIFFERENCE BETWEEN ++ AND - - OPERATOR AS POSTFIX AND PREFIX

 When i++ is used as prefix(like: ++var), ++var will increment the value of var and
then return it but, if ++ is used as postfix(like: var++), operator will return the value
of operand first and then only increment it. This can be demonstrated by an example:
#include <stdio.h>
int main()
{
int c=2, d=2;
printf("%d\n",c++); //this statement displays 2 then, only c incremented by 1 to
3.
printf("%d",++c); //this statement increments 1 to c then, only c is displayed.
return 0;
}
Output
2
4

49
Chapter1_Introduction To Programming 06/25/2024

BITWISE OPERATORS

 A bitwise operator works on each bit of data.


Bitwise operators are used in bit level
programming.
Operators Meaning of Operators
& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

~ Bitwise Complement

<< Shift left

>> Shift right

50
Chapter1_Introduction To Programming 06/25/2024

BITWISE AND OPERATOR


 Remember it is different than &&, the logical
AND operator. The & operator operates on two
operands. While operating upon these two
operands they are compared on a bit-by-bit basis.
Hence both the operands must be of the same
type (either char or int).
First bit Second bit Firsyt & second
bit
0 0 0
0 1 0
1 0 0
1 1 1 51
Chapter1_Introduction To Programming 06/25/2024

BITWISE OR OPERATOR
 Another important bitwise operator is the OR
operator which is represented as |. The rules that
govern the value of the resulting bit obtained
after ORing of two bits is shown in the truth table
below.
First bit Second bit First | second bit
0 0 0
0 1 1
1 0 1
1 1 1

52
Chapter1_Introduction To Programming 06/25/2024

BITWISE XOR OPERATOR


 The XOR operator is represented as ^ and is also
called an Exclusive OR Operator. The OR
operator returns 1, when any one of the two bits
or both the bits are 1, whereas XOR returns 1
only if one of the two bits is 1. The truth table for
the XOR operator is given below.
First bit Second bit First bit ^ second
bit
0 0 0
0 1 1
1 0 1
1 1 0 53
Chapter1_Introduction To Programming 06/25/2024

1) RIGHT SHIFT OPERATOR


 It shifts each bit in its left operand to the right. The number of places the bits are
shifted depends on the number following the operator (i.e. its right operand).
 Thus, ch >> 3 would shift all bits in ch three places to the right.
 Similarly, ch >> 5 would shift all bits 5 places to the right.
 For example, if the variable ch contains the bit pattern 11010111, then,
ch >> 1 would give 01101011 and ch >> 2 would give 00110101.
 Note that as the bits are shifted to the right, blanks are created on the left. These
blanks must be filled somehow. They are always filled with zeros.
 Note that if the operand is a multiple of 2 then shifting the operand one bit to
right is same as dividing it by 2 and ignoring the remainder. Thus,
 64 >> 1 gives 32
 64 >> 2 gives 16
 128 >> 2 gives 32
 but,
 27 >> 1 is 13
 49 >> 1 is 24 .
54
Chapter1_Introduction To Programming 06/25/2024

2) LEFT SHIFT OPERATOR


 This is similar to the right shift operator, the only
difference being that the bits are shifted to the
left, and for each bit shifted, a 0 is added to the
right of the number.

55

You might also like