PWC Unit-1 Part-2 (Basics of Programming)
PWC Unit-1 Part-2 (Basics of Programming)
Subject
Basics of Logic Development
Unit – 2 (Part – 1)
Basics of Programming
CONTENTS
1. Introduction to Programming Language
1.1. History of C Language
1.2. Features (Characteristics) of C Language
2. Structure of a C Program
3. Compiling Process of a C Program
4. Character Set of C Language
5. C Tokens
6. Keywords
7. Identifiers
8. Constants
8.1. Integer Constants
8.2. Real Constants
8.3. Single Character Constants
8.4. String Literals or String Constants
8.5. Backslash Character Constants/Escape Sequences
9. Variables
9.1. Declaring a Variable
9.2. Initializing a Variable
10. Data Types
10.1. Primary or Fundamental Data Types
10.2. Derived Data Types
10.3. User-Defined Data Types
11. Creating Constants in C
11.1. const Keyword
11.2. #define Preprocessor Directive
11.3. const vs #define
11.4. volatile Keyword
12. Basic Input and Output in C
12.1. Reading Input from Keyboard
12.2. Printing onto Screen
13. Operators
13.1. Arithmetic Operators
13.2. Relational Operators
13.3. Logical Operators
13.4. Assignment Operators
13.5. Increment and Decrement Operators
13.6. Conditional Operator (Ternary Operator)
13.7. Bitwise Operators
13.8. Special Operators
14. Operator Precedence and Associativity
15. Type Conversion/Type Casting
15.1. Implicit Type Conversion
15.2. Explicit Type Conversion (Type Casting)
16. Basic C Programs
of these languages and many more additional concepts that make it unique from
other languages.
‘C’ is a powerful programming language which is strongly associated with the
UNIX operating system. Even most of the UNIX operating system is coded in ‘C’.
Initially ‘C’ programming was limited to the UNIX operating system, but as it started
spreading around the world, it became commercial, and many compilers were
released for cross-platform systems.
Today ‘C’ runs under a variety of operating systems and hardware platforms. As
it started evolving many different versions of the language were released. At times it
became difficult for the developers to keep up with the latest version as the systems
were running under the older versions. To assure that ‘C’ language will remain
standard, American National Standards Institute (ANSI) defined a commercial
standard for ‘C’ language in 1989. Later, it was approved by the International
Standards Organization (ISO) in 1990. ‘C’ programming language is also called as
‘ANSI C’.
Table 2.1: History of C
Languages such as C++/Java are developed from ‘C’. These languages are
widely used in various technologies. Thus, ‘C’ forms a base for many other languages
that are currently in use.
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.
2. Structure of a C Program
Example –
/*********************************
* Author: Name
* Date: 7/10/2012
* Purpose: Theme of the program
********************************/
• Link Section - The link section is used to include the external header files in
which the pre-defined functions are available. To use the pre-defined functions
in our C programs, these files must be linked with our program. Files can be
included by using the “include” directive.
Example –
#include<stdio.h>
must appear between the opening and the closing braces. The main() function
may call other user defined functions.
• Subprogram section - It contains all the user-defined functions that are called
in the main functions. User-defined functions are generally placed immediately
after the main function, although they may appear in any order.
The compilation is a process of converting the source code into object code. It is
done with the help of the compiler. The compiler checks the source code for the
syntactical or structural errors, and if the source code is error-free, then it generates
the object code.
The c compilation process converts the source code taken as input into the object
code or machine code. The compilation process can be divided into four steps, i.e.,
Pre-processing, Compiling, Assembling, and Linking.
The preprocessor takes the source code as an input, and it removes all the
comments from the source code. The preprocessor takes the preprocessor directive
and interprets it. For example, if <stdio.h>, the directive is available in the program,
then the preprocessor interprets the directive and replace this directive with the
content of the 'stdio.h' file.
The following are the phases through which our program passes before being
transformed into an executable form:
o Preprocessor
o Compiler
o Assembler
o Linker
• Preprocessor - The source code is the code which is written in a text editor and
the source code file is given an extension ".c". This source code is first passed
to the preprocessor, and then the preprocessor expands this code. After
expanding the code, the expanded code is passed to the compiler.
• Compiler - The code which is expanded by the preprocessor is passed to the
compiler. The compiler converts this code into assembly code. Or we can say
that the C compiler converts the pre-processed code into assembly code.
• Assembler - The assembly code is converted into object code by using an
assembler. The name of the object file generated by the assembler is the same
as the source file. The extension of the object file in DOS is '.obj,' and in UNIX,
the extension is 'o'. If the name of the source file is 'hello.c', then the name of
the object file would be 'hello.obj'.
• Linker - Mainly, all the programs written in C use library functions. These
library functions are pre-compiled, and the object code of these library files is
stored with '.lib' (or '.a') extension. The main working of the linker is to combine
the object code of library files with the object code of our program.
Sometimes the situation arises when our program refers to the functions
defined in other files; then linker plays a very important role in this. It links the
object code of these files to our program.
Therefore, we conclude that the job of the linker is to link the object
code of our program with the object code of the library files and other files.
The output of the linker is the executable file. The name of the executable file
is the same as the source file but differs only in their extensions. In DOS, the
extension of the executable file is '.exe', and in UNIX, the executable file can
be named as 'a.out'.
5. C Tokens
6. Keywords
Every word used in a C program is classified as either a keyword or as an
identifier. A keyword in C is a reserved word which has a specific meaning.
Keywords in C cannot be used as identifiers. Keywords serve as the basic building
blocks for program statements.
Keywords in C are always in lowercase. ANSI C supports 32 keywords which are
listed in table 8.1.
Table 8.1: ANSI C Keywords
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
7. Identifiers
Identifiers refer to the names of variables, functions and arrays. These are user-
defined names and consist of sequence of letters and digits, with a letter as a first
character. Both uppercase and lowercase letters can be used, although lowercase
letters are generally used. The underscore character is also permitted in identifiers.
There are certain rules while writing identifiers. They are as follows:
Some valid examples of decimal integer constants are 133, +45, -15, 0,
342332, etc. Embedded spaces and non-digit characters are cannot be used
between digits. For example, 34 983, 21,000, $500 are illegal numbers.
A hexadecimal integer consists of numbers from 0 to 9 and 10, 11, 12, 13, 14
and 15 are represented as A, B, C, D, E and F. Hexadecimal numbers are always
preceded by 0x or 0X. Some valid examples of hexadecimal integer constants
are 0x54, 0X23, +0x1F, -0X56 etc.
mantissa e exponent
Every character constant will have an associated integer value known as ASCII
code. Since each character constant has an associated integer value, we can
perform arithmetic operations on them.
In this case \n is used to move the cursor to next new line. Even though the
escape sequences consist of a backslash (\) and a character or symbol, it is
treated as a single character. C supports the following escape sequences.
9. Variables
In the programs, generally we need to store values in the memory and perform
operations on those values. This can be achieved in C by the concept of variables.
A variable is a data name (identifier) that may be used to store a data value.
Each variable identified by a unique identifier in a program called variable name. A
variable may take different values at different times during execution.
For using variables in our programs, there are essentially two steps:
type variable-name;
The “type” in the above syntax represents the data type. The “variable-name”
is the identifier.
There are certain rules that must be followed while writing the variable name.
They are as follows:
Syntax –
variable-name = value;
The value we assign to the variable depends on the data type of the variable.
Example –
int a;
a = 10;
The declaration and initialization can be combined into a single line as below:
int a = 10;
In ANSI C, the data types are divided into three categories. They are:
• Integer data types - Integers are whole numbers with a range of values
supported by a particular machine.
Generally, integers occupy one word of storage, and since the word sizes of
machines vary (typically, 16 or 32 bits) the size of an integer that can be stored
depends on the computer.
If we use a 16-bit word length, the size of the integer value is limited to the
range –32768 to +32767 (that is, –215 to +215–1). A signed integer uses one
bit for sign and 15 bits for the magnitude of the number. Similarly, a 32-bit word
length can store an integer ranging from -2,147,483,648 to 2,147,483,647 (that
is, –231 to +231–1).
In order to provide some control over the range of numbers and storage
space, C has three classes of integer storage, namely short int, int, and long int, in
both signed and unsigned forms.
ANSI C defines these types so that they can be organized from the smallest to
the largest. For example, short int represents fairly small integer values and
requires half the amount of storage as a regular int number uses. Unlike signed
integers, unsigned integers use all the bits for the magnitude of the number and
are always positive. Therefore, for a 16-bit machine, the range of unsigned
integer numbers will be from 0 to 65,535 (that is, 0 to 216–1).
We declare long and unsigned integers to increase the range of values. The
use of qualifier signed on integer is optional because the default declaration
assumes a signed number.
Syntax –
int variable_name;
Example –
int num1;
short int num2;
long int num3;
Table 12.1 shows all the allowed combinations of basic types and qualifiers
and their size and range on a 16-bit machine.
• Floating-point data types – Floating point (or real) numbers are stored in 32 bits
(on all 16-bit and 32-bit machines), with 6 digits of precision. Floating point
numbers are defined in C by the keyword float. When the accuracy provided by
a float number is not sufficient, the type double can be used to define the
number.
A double data type number uses 64 bits giving a precision of 14 digits. These
are known as double precision numbers. Remember that double type represents
the same data type that float represents, but with a greater precision. To extend
the precision further, we may use long double which uses 80 bits.
Syntax –
float variable_name;
Example –
float num1;
double num2;
long double num3;
Syntax –
char variable_name;
Example –
char ch = 'a’;
• Void type - The void type has no values. This is usually used to specify the type of
functions. The type of a function is said to be void when it does not return any
value to the calling function. It can also play the role of a generic type, meaning
that it can represent any of the other standard types.
Syntax –
Here, type represents the existing data type and identifier represents the new
name in place of type. Remember that typedef is not capable of creating any
new data type but provides only an alternative name to an existing data type.
Example –
Syntax –
v1 = value3;
v4 = value1; // assigning values to variables
Example –
enum color {green, blue, red, pink}; //green, blue, red, pink
are constants or values
enum color flowers, leaves; //flowers and leaves are variables
flowers = red;
leaves = green;
Syntax –
Example –
Syntax –
Example –
#define PI 3.142
Take care that there is no semi-colon (;) at the end of #define statement. In the
above example we have assigned the value 3.142 to the symbol PI. Now,
whenever PI is encountered in the program, it will be replaced with the value
3.142.
If you don’t want the program to modify the value of date variable, but it can
be modified by external factors, then date can be declared as both volatile and
const as shown below –
The control string specifies the type of value to read from the keyboard and
the ampersand symbol & is an operator to specify the address of the variable(s).
Example –
Example –
int a = 10;
13. Operators
An operator is a symbol that tells a computer to perform certain mathematical or
logical operations. Operators are used in programs to manipulate data and
variables.
Operators are usually a part of the mathematical or logical expressions.
Generally, the usage of an operator is as shown below:
operand1 op operand2
In the above format, operand1 and operand2 can be either data or variables or
expressions. op is the operator. In C, based on the number of operands on which an
operator can operate, the operators are divided into three types namely, unary,
binary, and ternary.
Unary operators work on single operand, binary operators work on two
operands and ternary operators work on three operands.
In C, based on the functionality, operators are classified into 8 categories. They
are:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment and Decrement Operators
6. Conditional Operators
7. Bitwise Operators
8. Special Operators
Integer division truncates any fractional part. The modulo division operator (%)
produces the remainder of an integer division. The modulo operator cannot be
used on floating point values.
Table 13.1: Arithmetic operators
Operator Meaning Example
+ Addition or unary plus a+b
– Subtraction or unary minus a-b
* Multiplication a*b
/ Division (Quotient) a/b
% Modulo (Remainder) a%b
/* Program illustrating the use of arithmetic operators */
#include <stdio.h>
int main ()
{
int x = 25;
int y = 4;
printf ("%d + %d = %d\n", x, y, x + y);
printf ("%d - %d = %d\n", x, y, x - y);
printf ("%d * %d = %d\n", x, y, x * y);
printf ("%d / %d = %d\n", x, y, x / y);
printf ("Reminder when %d divided by %d = %d\n", x, y, x % y);
return 0;
}
Output –
25 + 4 = 29
25 - 4 = 21
25 * 4 = 100
25 / 4 = 6
Reminder when 25 divided by 4 = 1
20 > 10 // true
20 < 10 // false
#include <stdio.h>
int main ()
{
int a = 20, b = 10;
printf ("Two numbers are (a,b) = %d %d\n", a, b);
if (a > b)
printf ("a is greater than b\n");
if (a < b)
printf ("a is less than b\n");
if (a >= b)
printf ("a is greater than or equal to b\n");
if (a <= b)
printf ("a is less than or equal to b\n");
if (a == b)
printf ("a is equal to b\n");
if (a != b)
printf ("a is not equal to b\n");
return 0;
}
Output –
Logical NOT is a unary operator. In an expression, we can use more than one
logical operator. If more than one operator is used, ! (NOT) is evaluated first,
then && (AND) and then || (OR). We can use the parentheses to change the
order of evaluation.
For example, if we have a = 2, b = 3 and c = 5 then,
#include <stdio.h>
int main ()
{
int a = 2, b = 3, c = 1;
if (a > b && a > c)
printf ("a is big");
else if (b > c)
printf ("b is big");
else
printf ("c is big");
return 0;
}
Output –
b is big
var op = exp;
#include <stdio.h>
int main ()
{
int x = 10;
int y;
int z = 0;
x++; /* x incremented using postfix notation x=11 */
++x; /* x incremented using prefix notation x=12 */
y = ++x; /* x is incremented first and then assigned to
y. y=13 x=13 */
printf ("Value of x=%d y=%d and z=%d\n", x, y, z);
z = y--; /* y assigned to z first and then decremented.
z=13 y=12 */
printf ("Value of x=%d y=%d and z=%d\n", x, y, z);
return 0;
}
Output –
Value of x=13 y=13 and z=0
Value of x=13 y=12 and z=13
#include <stdio.h>
#include <conio.h>
int main ()
{
int x, y, max, min;
printf ("Give two integer numbers:\n");
scanf ("%d%d", &x, &y);
max = (x > y) ? x : y;
min = (x < y) ? x : y;
printf ("maximum of %d and %d is = %d\n", x, y, max);
printf ("minimum of %d and %d is = %d\n", x, y, min);
return 0;
}
Output –
The << and >> operators are used to shift the bits in left and right directions
respectively. After the << or >> operator some integer number is written.
Let us understand with example.
char x=15;
char y=8;
char z;
y (8) → 0 0 0 0 1 0 0 0
z = y << 1 (16) → 0 0 0 1 0 0 0 0
So, we can see that the left shift by one bit multiplies the number by 2. If we
left shift it by 2 bits, the number is multiplied by 4.
y (8) → 0 0 0 0 1 0 0 0
z = y >> 2 (2) → 0 0 0 0 0 0 1 0
Each one-bit shift on right divides the number by 2. We shifted 2 bits towards
right, so y divided by 4. Here, the answer may be truncated if the operand is not
even number.
first assigns the value 10 to x, then assigns 5 to y, and finally assigns 15 (i.e.,
10+5) to value.
• The sizeof operator – The sizeof operator is a compile time operator and
when used with an operand, it returns the size of its operand in bytes.
For example,
int i, j;
j = sizeof (i); /* it will give j = 2. Since integer
occupies 2 bytes and i is an integer */
Example –
#include <stdio.h>
int main()
{
int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e;
e = (a + b) * c / d; // ( 30 * 15 ) / 5
printf("Value of (a + b) * c / d is : %d\n", e );
e = ((a + b) * c) / d; // (30 * 15 ) / 5
printf("Value of ((a + b) * c) / d is : %d\n" , e );
e = (a + b) * (c / d); // (30) * (15/5)
printf("Value of (a + b) * (c / d) is : %d\n", e );
e = a + (b * c) / d; // 20 + (150/5)
printf("Value of a + (b * c) / d is : %d\n" , e );
return 0;
}
Output –
Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is : 90
Value of (a + b) * (c / d) is : 90
Value of a + (b * c) / d is : 50
bool -> char -> short int -> int -> unsigned int -> long ->
unsigned -> long long -> float -> double -> long double
It is possible for implicit conversions to lose information, signs can be lost (when
signed is implicitly converted to unsigned), and overflow can occur (when long
long is implicitly converted to float).
#include <stdio.h>
int main ()
{
int a,b;
float c;
double d;
a = 5;
c = 5.5;
d = 4.0;
b = a * c + d / 10;
printf ("value of b = %d\n",b);
return 0;;
}
Output –
value of b = 27
Explanation –
(typename) expression
Here, typename is the name of data type we want to convert the expression
to. The converted value is used during evaluation of expression only, it does not
change the basic data type of operand(s) of an expression.
For example, (float) 21 converts int 21 to float 21.0.
#include <stdio.h>
int main ()
{
int sum = 47;
int n = 10;
float avg;
avg = sum / 10; /* avg without type cast */
printf ("avg = sum / n = %f\n",avg);
avg = (float) sum / n; /*avg with type cast on sum */
printf ("avg = (float) sum / n = %f\n",avg);
avg = (float) (sum / n); /* avg without type cast on (sum / n) */
printf ("avg = (float) (sum / n) = %f\n",avg);
return 0;
}
Output –
Explanation –
o In the first line of output, integer arithmetic takes place; while in second,
sum which is 47 is converted into 47.0 and 10 becomes 10.0. So,
floating point arithmetic takes place.
o While in the last line of output, float type casting takes place on sum / n
which is 4, converted into float becomes 4.0.
#include <stdio.h>
int main ()
{
printf ("Name: Viral Panchal\n");
printf ("College Name: CGPIT\n");
printf ("Branch Name: Computer Engineering\n");
printf ("Subject: Basics of Logic Development\n");
printf ("Enrolment No.: 201204101510005\n");
return 0;
}
Output –
#include <stdio.h>
int main ()
{
char c;
int n;
float f;
printf ("Enter a character: ");
scanf ("%c", &c); // Taking Character as input from the user
printf ("The character that you have entered is %c\n", c);
printf ("Enter integer number: ");
scanf ("%d", &n); // Taking integer as input from user
printf ("The integer number you have entered is %d", n);
printf ("\nEnter a floating-point number: ");
Output –
Enter a character: v
The character that you have entered is v
Enter integer number: 19
The integer number you have entered is 19
Enter a floating-point number: 23.76
The float or fraction that you have entered is 23.760000
#include<stdio.h>
int main ()
{
float no1, no2, add, sub, multi, div;
printf ("Entre number 1: ");
scanf ("%f", &no1);
printf ("Enter number 2: ");
scanf ("%f", &no2);
add = no1 + no2;
sub = no1 - no2;
multi = no1 * no2;
div = no1 / no2;
printf ("Addition = %f\n", add);
printf ("Subtraction = %f\n", sub);
printf ("Multiplication = %f\n", multi);
printf ("Division = %f\n", div);
}
Output –
Entre number 1: 5
Enter number 2: 4
Addition = 9.000000
Subtraction = 1.000000
Multiplication = 20.000000
Division = 1.250000
#include<stdio.h>
int main ()
{
float f, c;
printf ("Enter Temperature in Celsius: ");
scanf ("%f", &c);
f = 1.8 * c + 32;
printf ("Temperature in Fahrenheit = %0.2f\n", f);
return 0;
}
Output –
#include<stdio.h>
int main ()
{
int no1, no2, temp;
printf ("Enter No.1: ");
scanf ("%d", &no1);
printf ("Enter No.2: ");
scanf ("%d", &no2);
printf ("Before Interchange\nNo.1 = %d and No.2 = %d", no1, no2);
temp = no1;
no1 = no2;
no2 = temp;
printf ("\nAfter Interchange\nNo.1 = %d and No.2 = %d\n", no1, no2);
return 0;
}
Output –
Enter No.1: 5
Enter No.2: 8
Before Interchange
No.1 = 5 and No.2 = 8
After Interchange
No.1 = 8 and No.2 = 5
#include<stdio.h>
int main ()
{
int a,b;
printf ("Enter No.1: ");
scanf ("%d", &a);
printf ("Enter No.2: ");
scanf ("%d", &b);
printf ("Before Interchange\nNo.1 = %d and No.2 = %d",a,b);
a=a+b;
b=a-b;
a=a-b;
printf ("\nAfter Interchange\nNo.1 = %d and No.2 = %d\n",a,b);
return 0;
}
Output –
Enter No.1: 5
Enter No.2: 8
Before Interchange
No.1 = 5 and No.2 = 8
After Interchange
No.1 = 8 and No.2 = 5