Chapter1-Introduction To Programming in C
Chapter1-Introduction To Programming in C
Chapter One
INTRODUCTION TO PROGRAMMING IN C
1
Chapter1_Introduction To Programming 06/25/2024
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 ALGORITHM?
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
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:
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
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
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
Output
C Programming
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
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
#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
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
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:
37
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.
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.
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
! 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
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
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
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise Complement
50
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
55