You are on page 1of 30

Learning C Programming

Unit II
Basic of C Programming

10 Marks

Learning outcomes:
 Identify the given building block of a C program.
 Write simple ‗C‘ program using the given arithmetic
expressions
 Write a simple ‗C‘ Program demonstrating the given data
type conversion
 Write I/O Statements for the given data.

What is ‘C’ / History of ‘C’


C is a programming language developed at AT & T‘s Bell
Laboratories of USA in 1972. It was designed and written by a
man named Dennis Ritchie. In the late seventies C began to
replace the more familiar languages of that time like PL/I, ALGOL,
etc. Ritchie seems to have been rather surprised that so many
programmers preferred C to older languages like FORTRAN or
PL/I, or the newer ones like Pascal and APL.
Possibly why C seems so popular is because it is reliable, simple
and easy to use. Moreover, in an industry where newer

By, Mr. Jadhav S. B.


Learning C Programming

languages, tools and technologies emerge and vanish day in and


day out, a language that has survived for more than 4 decades
has to be really good.
Why C
There are several reasons for this:
1. Nobody can learn C++ or Java directly. Hence one should first
learn all the language elements using C language before start
learning C++, C# or Java.
2. C++, C# or Java make use of a principle called Object
Oriented Programming (OOP) to organize the program. You
would still need a good hold over the language elements of C
and the basic programming skills.
3. To use C++, C# or Java frameworks and tools you would be
still required to use the core C language elements—another
good reason why one should learn C before other
programming.
4. Major parts of popular operating systems like Windows, UNIX,
Linux is still written in C.
5. Commonly used Electronic devices like microwave oven,
washing machines and digital cameras are getting smarter by
the day. This smartness comes from a microprocessor, an
operating system and a program embedded in this devices.
These programs not only have to run fast but also have to
work in limited amount of memory. Even such programs are
written in C.

By, Mr. Jadhav S. B.


Learning C Programming

6. Most of the professional 3D computer games are developed by


using ‗C‘ for navigates objects.
7. For interacting with hardware devices is most important thing,
C provides several language elements that make this
interaction feasible without compromising the performance of
the hardware.
Structure of ‘C’:
Learning C is similar and easier. Instead of straight-away
learning how to write programs, we must first know what
alphabets, numbers and special symbols are used in C, then
how using them constants, variables and keywords are
constructed, and finally how are these combined to form an
instruction. A group of instructions would be combined later on
to form a program.
This is shown in figure below

By, Mr. Jadhav S. B.


Learning C Programming

Character set of ‘C’


A character denotes any alphabet, digit or special symbol
used to represent information. Following are the valid alphabets,
numbers and special symbols allowed in C.

Alphabets - A, B, ….., Y, Z
a, b, ……, y, z
Digits - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special symbols - ~ ‗ ! @ # % ^ & * ( ) _ - + = | \ { } [ ] : ; " '
<>,.?/

C Constants:
―A constant is an entity that doesn‘t change during program
execution‖. Types of C Constants
C constants can be divided into two major categories:
1. Primary Constants
2. Secondary Constants
These constants are further categorized as shown in Figure 1.2.

Figure 1.2

By, Mr. Jadhav S. B.


Learning C Programming

Primary Constants, Integer, Real and Character constants.


Rules for creating Integer constants:
1. An integer constant must have at least one digit.
2. It must not have a decimal point.
3. It can be either positive or negative.
4. If no sign precedes an integer constant it is assumed to
be positive.
5. No commas or blanks are allowed within an integer
constant.
The allowable range for integer constants is -32768 to
32767.
Ex.: 426,
+782,
-8000,
-7605
Rules for Constructing Real Constants
Real constants are often called Floating Point constants. The
real constants could be written in two forms—Fractional form
and Exponential form.
1. A real constant must have at least one digit.
2. It must have a decimal point.
3. It could be either positive or negative.
4. Default sign is positive.
5. No commas or blanks are allowed within a real constant.
Ex.: +325.34

By, Mr. Jadhav S. B.


Learning C Programming

426.0
-32.76
-48.5792
Rules for Constructing Character Constants
A character constant is a single alphabet, a single digit or a
single special symbol enclosed within single inverted
commas. The maximum length of a character constant can
be 1 character.
Ex.: 'A'
'I'
'5'
'='
Variable
It‘s an entity that may change during program execution is
called as variable.
Or
It‘s the name given to the memory location known as
variable.

Since the location whose name is x can hold different values


at different times x is known as a variable.

By, Mr. Jadhav S. B.


Learning C Programming

Types of C Variables
Variables can contain integer, real or character constants
hence it‘s devided into three catagories. an integer variable
can hold only an integer constant, a real variable can hold
only a real constant and a character variable can hold only a
character constant. .
Rules for Constructing Variables
1. A variable name is any combination of 1 to 31 alphabets,
digits or underscores. Some compilers allow variable
names whose length could be up to 247 characters.
2. The first character in the variable name must be an
alphabet or underscore.
3. No commas or blanks spaces are allowed within a variable
name.
4. No special symbol other than an underscore (as in
gross_sal) can be used in a variable name.
It‘s compulsory to declare the variable before using it in the
program.
Syntax:
variable_type name_of_variable;
Eg: int add;
float per;
Identifiers:
It‘s is a name used to identify a variable, function, or any
other user defined item

By, Mr. Jadhav S. B.


Learning C Programming

Note: an identifier is a ―name given to entity‖ in a program


whereas, a variable is a ―name given to memory location‖,
that is used to hold value, which may get modified during
program execution.

Tokens in C
C program consists of various tokens and a token is either a
keyword, an identifier, a constant, a string literal, or a
symbol. For example, the following C statement consists of
five token.
printf("Hello, World! \n");
token1: printf
token2: (
token3: "Hello, World! \n"
token4: )
token5 ;

By, Mr. Jadhav S. B.


Learning C Programming

Datatypes:
Each variable in C has an associated data type. Each data
type requires different amounts of memory and has some
specific operations which can be performed over it.

fundamental data types are:


1. int - Integer data types
2. float - Floating types
3. char - Character types
int - Integer data types
Integers are whole numbers that can have both positive and
negative values but no decimal values. In C programming,
keyword ‗int‘ is used for declaring integer variable.

By, Mr. Jadhav S. B.


Learning C Programming

For example:
int id;
Here, id is a variable of type integer.
You can declare multiple variable at once in C programming.
float - Floating types
It can hold real numbers such as: 2.34, -9.382, 5.0 etc. You can
declare a floating point variable in C by using
either float or double keyword. For example:

float accountBalance;
double bookPrice;

Here, both accountBalance and bookPrice are floating type


variables.
In C, floating values can be represented in exponential form as
well. For example:

float normalizationFactor = 22.442e2;

char - Character types


Keyword char is used for declaring character type variables. For
example:
char test = 'h';
Here, test is a character variable. The value of test is 'h'.

By, Mr. Jadhav S. B.


Learning C Programming

By, Mr. Jadhav S. B.


Learning C Programming

C Keywords
Keywords are the words whose meaning has already defined
to the compiler. The keywords cannot be used as variable
names because if we do so we are trying to assign a new
meaning to the keyword, which is not allowed by the
computer. The keywords are also called ‗Reserved words‘.
There are only 32 keywords available in C.

Figure: 1.3
Rules for creating C programs:
1. Each instruction in a C program is written as a separate
statement.
2. The statements in a program must appear in the same
order in which we wish them to execute.
3. Blank spaces may be inserted between two words to
improve the readability of the statement. However, no
blank spaces are allowed within a variable, constant or
keyword.
4. All statements are entered in small case letters.

By, Mr. Jadhav S. B.


Learning C Programming

5. Every C statement must end with a ;(Semicolon).


Let us write our first C program for printing ―Hello World‖.
Line 1: // Program for printing Hello World message
Line 2: #include<stdio.h>
Line 3: main()
Line4: {
Line 5: printf(―Hello World‖);
Line 6: }
where,
line 1: is a comment/description about the program.
Line 2: is a ‗<stdio.h>‘ standard input/ouput directory for
standard library functions for input/output in a program.
Line 3: main() is first function in the C program, from where
execution of the program will starts. All statements that
belong to main( ) are enclosed within a pair of braces { }
as shown below.
Line 4: & Line 6: open & close curly braces.
Line 5: printf( ) – standard output library function used to
print the output message on the screen/console.
Compilation of C program:
Following are the steps to compile/execute C program using
the ‗Turboc3‘ compiler.
1. Install the Turboc3 compiler in your system, by default it‘s
installed on the directory ―C:\TurboC++\Disk‖.
2. Double click on ―Turboc++‖ icon on the desktop.

By, Mr. Jadhav S. B.


Learning C Programming

3. Open ‗File‘ menu, click on ‗new‘.

4. Type the above program in the editor, save it with name


―hello.c‖, all c program file must have the extension ‗.c‘.

5. Click on ‗compile‘(or press Alt+F9) to compile the


program.
6. Click on ‗run‘(or press Ctrl+F9) to execute the program,
we will get the output as bellow.

By, Mr. Jadhav S. B.


Learning C Programming

Operators in ‘C’
An operator is a symbol that tells the compiler to perform specific
mathematical or logical functions. C language is rich in built-in
operators and provides the following types of operators:
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Misc Operators
The following table shows all the arithmetic operators supported
by the C language.

By, Mr. Jadhav S. B.


Learning C Programming

Eg: // Program to understand all the arithmetic operators


available in C:
#include <stdio.h>
main( )
{
int a = 21;
int b = 10;
int c ;
c = a + b;
printf("Addition is %d\n", c );
c = a - b;
printf("Subtraction is %d\n", c );
c = a * b;

By, Mr. Jadhav S. B.


Learning C Programming

printf("Multiplication is %d\n", c );
c = a / b;
printf("Division is %d\n", c );
c = a % b;
printf("Modular division is %d\n", c );
//(final value of c is 1)
c=c++;
printf("After increment %d\n", c );
c=c--;
printf("After Decrement is %d\n", c );
}
When you compile and execute the program, it produces the
following result:

Relational Operators
The following table shows all the relational operators supported
by C.

By, Mr. Jadhav S. B.


Learning C Programming

Example: //Program to understand all the relational operators


available in C:
#include <stdio.h>
main( )
{
int a = 21;
int b = 10;
int c ;
if(a==b)
{
printf("a is equal to b\n" );

By, Mr. Jadhav S. B.


Learning C Programming

}
else
{
printf("a is not equal to b\n" );
}
if ( a < b )
{
printf("a is less than b\n" );
}
else
{
printf("a is not less than b\n" );
}
if ( a > b )
{
printf("a is greater than b\n" );
}
else
{
printf("a is not greater than b\n" );
}
/* Lets change value of a and b */
a = 5;
b = 20;
if ( a <= b )

By, Mr. Jadhav S. B.


Learning C Programming

{
printf("a is either less than or equal to b\n" );
}
if ( b >= a )
{
printf("b is either greater than or equal to b\n" );
}
}
When you compile and execute the program, it produces the
following output:

Logical Operators
Following table shows all the logical operators supported by C
language.

By, Mr. Jadhav S. B.


Learning C Programming

Example: //Program to understand all the logical operators


available in C:
#include <stdio.h>
main( )
{
int a = 5;
int b = 20;
int c ;
if ( a && b )
{
printf("Condition is true\n" );
}
if ( a || b )
{

By, Mr. Jadhav S. B.


Learning C Programming

printf("Condition is true\n" );
}}
When you compile and execute the program, it produces the
following output:

Misc Operators ↦ sizeof & ternary


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

#include <stdio.h>
main( )
{

/* example of ternary operator */


int a = 10,b;
b = (a == 1) ? 20: 30;
printf( "Value of b is %d\n", b );

By, Mr. Jadhav S. B.


Learning C Programming

b = (a == 10) ? 20: 30;


printf( "Value of b is %d\n", b );
}
Output:

Operators Precedence in C
Operator precedence determines how an expression is evaluated.
Certain operators have higher precedence than others; for
example, the multiplication operator has a higher precedence
than the addition operator.
For example, x = 7 + 3 * 2;
here, x is assigned 13, not 20 because operator * has a higher
precedence than +, so it first gets multiplied with 3*2 and then
adds into 7.

Type Conversion:
Type Conversion (also called casting) is a way to convert a
variable from one data type to another data type. For example, if
you want to store a 'long' value into a simple integer then you
can type cast 'long' to 'int'. You can convert the values from one
type to another explicitly using the cast operator as follows −
Syntax:

By, Mr. Jadhav S. B.


Learning C Programming

target_variable_name=(target_type) source_variable_name;
Eg:
b=(float) a;
Consider the following example where the cast operator causes
the division of one integer variable by another to be performed
as a floating-point operation
#include <stdio.h>
main()
{

int a=5;
float b;

b=(float) a;
printf("Value of b: %f\n",b);
}
Output:
Value of b:5.000000

C Input and Output


Input means to provide the some input data to the program
and Output means to display data on screen or write the data to
a printer or a file.
C programming language provides many built-in functions to read
& write data, which can be used in our program to take input
from user and to output the result on screen.
scanf() and printf() functions
The standard input-output header file, named stdio.h contains the
definition of the functions printf() and scanf(), which are used to
display output on screen and to take input from user respectively.

By, Mr. Jadhav S. B.


Learning C Programming

#include<stdio.h>
void main()
{
// defining a variable
int i;
/*
displaying message on the screen
asking the user to input a value
*/
printf("Please enter a value...");
/*
reading the value entered by the user
*/
scanf("%d", &i);
/*
displaying the number as output
*/
printf( "\nYou entered: %d", i);
}
When you will compile the above code, it will ask you to enter a
value. When you will enter the value, it will display the value you
have entered on screen.
The %d inside the scanf() or printf() functions. It is known
as format string and this informs the scanf() function, what type

By, Mr. Jadhav S. B.


Learning C Programming

of input to expect and in printf() it is used to give a heads up to


the compiler, what type of output to expect.

Format
String Meaning

%d Scan or print an integer as signed decimal number

%f Scan or print a floating point number

%c To scan or print a character

%s To scan or print a character string. The scanning ends


at whitespace.

Character Input/Output Statements:


getchar() & putchar() functions
The getchar() function reads a character from the terminal and
returns it as an integer. This function reads only single character
at a time.
The putchar() function displays the character passed to it on the
screen and returns the same character. This function too displays
only a single character at a time.
//Write a program to accept a character from user & print it.
#include <stdio.h>
void main( )
{
int c;

By, Mr. Jadhav S. B.


Learning C Programming

printf("Enter a character:");
c = getchar();
putchar(c);
}
Output:
Enter a character: f
f
When you will compile the above code, it will ask you to enter a
character, then it will display the character have entered?
gets() & puts() functions
The gets() function reads a line from stdin(standard input) until
either a terminating newline or EOF (end of file) occurs.
The puts() function writes the string str and a trailing newline
to stdout.
#include<stdio.h>
void main()
{
/* character array of length 100 */
char str[100];
printf("Enter a string:");
gets( str );
puts( str );
getch();
}

By, Mr. Jadhav S. B.


Learning C Programming

Output:
Enter a string: gramin
gramin
When you will compile the above code, it will ask you to enter a
string. When you will enter the string, it will display the value you
have entered.
Difference between scanf() and gets()
The main difference between these two functions is
that scanf() stops reading characters when it encounters a space,
but gets() reads space as character too.

Comments in C:
In the C Programming Language, you can place comments in
your source code that are not executed as part of the program.
Single Line Comment:
1. Its used to provide one line descriptor of line.
2. Single Line Comment Can be Placed Anywhere
3. Single Line Comment Starts with ‗//‘
4. Any Symbols written after ‗//‘ are ignored by Compiler
Eg: // This is single line comment
Multiline Comment:
1. Its used to write the description of the program in more than
one line
2. Multi line comment can be placed anywhere.
3. Multi line comment starts with /*.

By, Mr. Jadhav S. B.


Learning C Programming

4. Multi line comment ends with */.


5. Any symbols written between '/*' and '*/' are ignored by
Compiler.
Eg: /* This is multiline comment in
C programming language */

Important Questions:
1. Explain History of c language?
2. Define terms
i. Identifier.
ii. Token
iii. Operator
3. Explain logical and relational operator .
4. Explain conditional operator with example.
5. What are the rules for creating integer, real constants?
6. Write a program to accept a number from user & display whether it‟s even
or odd.
7. Write a program to take marks for 3 subjects, calculate the percentage &
display it.
8. Explain the variable declaration and definition.
9. Explain formatted input and formatted output statements.
10.Explain arithmetic operators with example.
11.Write a program to find whether the character entered through keyboard is a
vowel or consonant.
12.Explain conditional operator with example.

By, Mr. Jadhav S. B.


Learning C Programming

13.Write a „C‟ program to accept two integer Nos from user and print the
result.
14.What is constant? Give any two examples.
15.State four rules for choosing variable name?
16.State different basic data type in „C‟.
17.Write output of the following program.
void main()
{
char str[5]={„a‟,‟b‟,‟c‟,‟d‟,‟e‟,‟/‟};
printf(“%s”,str);
}
18.Define token? List tokens in ‟C‟.
19.Enlist different format specifiers.
20.Program to calculate sum of 5 subjects and find percentage.
21.Program to swap two no‟s.
22.Program to Check Whether a Character is Vowel or Consonant.

By,
Mr. Jadhav S.B.
Sr. Lecturer GPVN

By, Mr. Jadhav S. B.

You might also like