3. Importance of C Language
Mostly the Device drivers are written in C.
Core libraries of Android are written in C.
Oracle, Mysql ... are written in C.
Unix operating system is developed in C.
Major parts of windows & other operating system are written in C.
C is called as mother of all programming language.
C covers basic features of all programming language.
If you learn the concepts of programming in C language, then you
can code easily in the other languages
3
4. In 1967, Martin Richards developed BCPL (Basic Combined Programming Language).
In 1970, Ken Thompson at AT&T Bell Labs developed programming language B by using BCPL.
Later, another scientist Dennis Ritchie attracted by B, and he added several instructions,
operators, functions, etc. and changed B completely.
Thus a new language was born, which he called C.
Used for developing UNIX OS.
C was developed by Dennis Ritchie in 1972.
4
Dennis Ritchie
5. The Computer languages are mainly divided in two types:
“High level languages” are the languages where we can write
programs easily using English words. For example, FORTRAN and
Pascal. Learning and applying these languages to develop programs
or software is very easy.
“Low level languages” interact with the hardware of the machine
directly and can control the memory and the processor. For example,
Assembly language and machine language. Execution of programs is
very fast but learning and writing programs in these languages is very
difficult.
C has the features of both high and low level languages, we can
call it a “Middle level language”.
5
Hardware
Low Level Language
(Assembly & Machine
Language)
High Level Language
(Fortran & Pascal)
C
Middle
Level
Language
6. 6
C Basic Commands Explanation
#include <header file name> This is a pre-processor command that includes header
files from the C library before compiling a C program
void main() This is the main function from where execution of any C
program begins.
{ This indicates the beginning of the main function.
/*comments*/ whatever is given inside the command “/* */” in any C
program, won’t be considered for compilation and
execution.
printf(“Hello_World! “); printf command prints the output onto the screen.
7. 7
Types
Working
#include <Header_file_name>
This is used to include in-built system header
files. It searches given header file in a standard
list of directories where all in-built header files are
stored. To include in-built header file we use
triangular bracket.
This is used to include user-defined system
header files. It searches given user defined
header file in a current directories where current c
9. To communicate with others, we use human languages like English, Hindi, etc.
Similarly to communicate with computers, we should use computer languages like C / C++ / Java.
There are many similarities between human languages and computer languages.
For Example:
Take English Language for understanding composition of C Language better step by step.
9
S. No. English Language C Language
1.
Learn alphabets Learn Character Set
2.
Create word using alphabets Learn how to construct words
Character Set
Word
C
Statement
Composition of a C Program
10. We should use only the following characters in writing a C program.
These characters can be combined to create C words.
10
Set Type Characters
Alphabets A, B, C, D,…….,Z, a, b, c, d,…….,z
Numeric digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special Characters + - * / % ? & | ! = [ ] ( ) { } < > ‘ “ @ # ^ . _ , : ; ~
11. We can divide the words in C into three groups:
Constants
Variables
Reserved words or key words
Constants:
Constants represent fixed values.
Constants value will not change in the program.
Note: Character constants should be enclosed in single quotes and the strings should be enclosed in
double quotes.
11
S. No. Values Constants Type
1. 5, -125, 255, etc. Integer Constants
2. 12.5, -3.14159, etc. Real Constants
3. ‘a’, ‘M’, ‘S’, etc. Character Constants
4. “Tarun”, “Software”, etc. String Constants
12. Variables:
Variables represent words which store varying (Changing) values.
For example:
Here, x is the name of a variable whose type is ‘int’. It store an integer number in variable x.
If we store an integer number in a variable, then it is called Integer type variable.
If we store a real number in a variable, then it is called Float type variable.
If we store a single character in a variable, then it is called Character type variable.
In the above example, empcode, emp_sal, and sex are the names of the variables.
12
int x;
//Data type declaration statements
int empcode;
float emp_sal;
char ch, sex, name[30];
13. Use of these variables to store values given below:
Here, empcode variable storing 1001 which is integer constant, emp_sal variable storing 7890.50 which is
real constant and sex variable storing ‘M’ which is character constant.
Points to Remember:
While writing the names of the variables, we should start the name with an alphabet.
We should not use more than 31 characters in the variable name.
We should not use any blanks or any special characters in the variables name, except underscore symbol ( _ ).
Variable should be declared first in a C program only once, after that it can be used at any time.
Reserved Words:
There are some words which can not be used as variables. They are used in some special meaning only.
They are called Reserved Words or Key Words. There are a total of 32 reserved words in C language.
13
empcode = 1001;
emp_sal = 7890.50;
sex = ‘M’;
auto break case char const continue default do double else enum extern float
for goto if int long register return void short while sizeof signed static
struct switch union typedef unsigned volatile
14. There are four types of Statements:
Data type declaration statements
Input/Output statements
Arithmetic statements
Control statements
14
15. Data type declaration statements
Data type declaration statements describe the data that the program is going to use.
Declaration statements come before any executable statements in c program.
15
//Data type declaration statements
int empcode;
float emp_sal;
char ch, sex, name[30];
16. Input/Output statements
The data given to a program is called Input The result given by the program is called Output.
To do any work we need functions in C. A function can be imagined as a set of statements aimed to
perform a task. There are various functions provided in the form of header files in C library.
To perform any task, functions are needed.
Input and Output statements are also a function [ scanf(),printf() etc].
16
C Standard Library Header Files Functions
C standard library contains header files and functions
17. The following table gives the list of basic input and output functions which are available as part of the header
file: stdio.h.
getchar() function:
Accepts single character as input.
getchar() function takes the character and stores it into a variable.
Here ‘ch’ represents a Char type variable.
Any function name in C ends with a pair of simple braces. For example: getchar() or putchar().
17
Input Functions Output Functions
getchar() putchar()
gets() puts()
scanf() printf()
ch = getchar();
18. putchar() function:
Display a single character as output on the monitor.
putchar() function is taking the variable ‘ch’ and it sends the content of that variable to the monitor.
putchar() will display the Character ‘A’ directly on the monitor.
18
putchar(ch);
putchar(‘A’);
19. Program 1:
/*Write a program to understand how to input a single character from the keyboard and how to display the
same character on the monitor.*/
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
ch = getchar();
putchar(ch);
getch();
}
19
Output
20. The first line represents comment line.
Comments describe the aim of a program or of any statement(s) in the program.
Comments are written inside /* and */.
Comments are not executed by the compiler. So, they are called non executable statements.
They are for increasing the readability (understanding) of the program.
Header Files:
These instructions instruct C compiler to include the header file: stdio.h and conio.h
stdio.h header file is a preprocessor file, where # tells start preprocessing from here, this file contains all the
standard input and output functions in it.
conio.h header file contains many C library functions for performing “console input and output” from a
program, e.g. getch(), getche(), clrscr(), etc.
It is compulsory to include these header file in C program.
20
/* To accept and display a single character */
#include<stdio.h>
#include<conio.h>
21. main() is the function name from where a C program execution starts.
Before main() function, we use ‘void’. It means ‘no value’.
So, main() function will not return any value.
It simply executes and display the result.
After main() function, we should write ‘{‘ right curly brace which represents the beginning of the main()
function and ‘}’ left curly brace which represents ending of the function.
The statements inside this function are executed by the compiler.
char ch;
ch is a variable declared as char type. So, it is possible to store a single character in ch.
ch = getchar();
getchar() function waits for input of a single character.
When we enter a character from the keyboard, it reads it and then stores it into the variable ch.
Storage is done by the symbol ‘=‘ which is called ‘assignment operator’.
putchar(ch);
putchar() function is displaying the content of ch on the monitor. 21
void main()
22. gets() function:
It accept a string from the keyboard and store it into a variable. A string represents a group of characters.
gets(str);
gets() function will accept a string from the keyboard and stores into the variable str.
puts() function:
Displays a string on the monitor.
puts(str);
puts(“Hello”);
This will display “Hello” on the screen.
22
23. Program 2:
A program to read and display the name of a person using gets() and puts().
#include<stdio.h>
#include<conio.h>
void main()
{
char str[20];
puts(“Type your Name:”);
gets(str);
puts(str);
getch();
}
23
Output
24. Observe the program. The first statement in the main() function is: char str[20];
It represents an array (group) of characters. The name of the array is str.
After the array name, we should write [ and ] braces. Here str[] array can have a maximum of 20 characters.
puts(“Type your Name:”);
This will display the message “Type your Name:” to the user.
gets(str);
When the user types the name, it is stored into the array str[] by the gets() function
puts(str);
The puts() function displays the name on the monitor.
24
25. scanf() function:
Accept any type of input. It may be a number, a character or a string.
The general format of writing a scanf() function is:
25
scanf(“format specifier”, variable list);
26. The format specifier is a string that can represents any of the following format characters shown in the Table:
26
Format specifier
Meaning
%c A single character
27. The variables in scanf() should be separated by a comma, as shown below:
scanf(“%d %d”, &num1, &num2);
Here, num1 and num2 are variables of integer types.
“%d” represents the format specifier for accepting decimal integer number. Since there are two integer
numbers to be accepted, we write “%d %d”.
The ‘&’ symbol before the variable name represents memory location (address) of the variable.
With numeric type of variables and character type of variables, we should mention ‘&’ symbol.
With strings we need not mention ‘&’ symbol, name of string itself represents the memory address internally.
scanf(“%s %f”, name, &sal);
“%s” represents the string type variable, i.e., name and the “%f” represents the float type variable, i.e., &sal.
Here sal represents a number and hence & symbol is placed before the variable.
There are another important point to be understood here:
scanf(“%d %d”, &num1, &num2);
To enter two integer numbers to this scanf() function, we can type the numbers separating them by a space
from the keyboard.
10 25
27
28. Suppose, we write the scanf() function as:
scanf(“%d, %d”, &num1, &num2);
Please observe a comma mark between the %d and %d in the format specifier.
It represents that we should type the input numbers separating them by a comma.
10, 25
Similarly, if we use a colon ( : ) or slash ( / ) in scanf() function, then we should use a colon or slash symbol
to separate the input data.
28
29. printf() function:
1. Display text as it is.
Let us see some example of using printf() function.
printf(“Hello World”);
This will display “Hello World” on the monitor.
2. Display value of variable or value of expression.
printf(“format specifier”, variable list);
The first argument of printf is a format specifier.
Each % sign in the format specifier is a formatting instruction.
Here, “format specifier” represents the same format strings used in scanf().
There is one difference with “%s”. If used with scanf(), it accepts only one word, where as if used with
printf(), it can display a group of words or whole string.
There is no need of & symbol to be used before any variable in printf().
printf can display character, or string or any numeric value.
29
30. We can also use the following backslash codes in printf() function. Backslash codes are also called escape
sequence.
30
32. This will display “Hello Tarun” on the monitor if name has “Tarun” in it.
This will display “Your salary= 7890.50” if the sal variable has 7890.50.
This will display the following output if name is “Tarun” and code is 125.
32
printf(“Hello %s”, name);
printf(“Your salary= %f”, sal);
printf(“Name= %snCode=%d”, name, code);
Name= Tarun
Code=125
33. C program using printf()
function
33
#include <stdio.h>
// program prints hello world
void main()
{
printf ("Hello world!");
}
Output: Hello world!
33
34. C program using printf()
function
34
#include <stdio.h>
// program prints hello world
int main()
{
printf ("Hello world!");
return 0;
}
Output: Hello world!
34
35. Other Example
35
#include <stdio.h>
// program prints a number of type int
int main() {
int number = 4;
printf (“Number is %d”, number);
return 0;
}
Output: Number is 4
35
36. More Example
36
#include <stdio.h>
// program reads and prints the same thing
int main() {
int number ;
printf (“ Enter a Number: ”);
scanf (“%d”, &number);
printf (“Number is %dn”, number);
return 0;
}
Output : Enter a number: 4
Number is 4
36
37. more and more
37
#include <stdio.h>
int main() {
/* this program adds
two numbers */
int a = 4; //first number
int b = 5; //second number
int answer = 0; //result
answer = a + b;
}
37
38. Program 3:
In this program, we will accept the name of a person and display Birthday wishes to the person.
#include<stdio.h>
#include<conio.h>
void main()
{
char name[20];
printf(“Your good name please:”);
scanf(“%[^n]”, name);
printf(“Hello %s”, name);
printf(“nHappy Birthday to you!”);
getch();
}
38
Output
39. Program 4:
C program to find sum of two numbers.
#include<stdio.h>
#include<conio.h>
void main()
{
int n1, n2, sum;
printf(“nEnter two numbers:”);
scanf(“%d%d”, &n1, &n2);
sum = n1+n2;
printf(“nSum=%d”, sum);
getch();
}
39
Output
40. A format specifier is nothing but the format string used in various forms
To specify the width of integer number, we can use “%nd” specifier.
“%5d” allots a space of 5 digits width and displays the integer value. The value is by default right aligned.
Minus symbol after % and before nd represents the value to be left aligned.
Plus symbol represents + symbol to be displayed before positive number
0 represents the blank spaces to be filled with 0s.
40
Function Output
printf(%5d”, 12345); 12345
41. To specify the width for float or double number, we can use “%w.df” specifier.
“%8.2f” represents a total of 8 digit space and in that a decimal point and after that 2 fraction digits.
“%.1f” means only one digit will be displayed in the fraction part and all the digits in the integer part.
41
printf(%8.2f”, 25.123456789); _ _ _ 25.12
printf(“%.1f”, 25.123456789); 25.1
42. String can also be formatted. “%ns” represents a string with width n characters.
“%10s” represents a string with width 10 characters. The string is right aligned. If more than 10 characters are
there in the string, then all those characters are displayed.
A minus after the % and before ns represents that the string is to be left justified.
42
Function Output
printf(%s”, “Hello”); Hello
43. We can write several programs on a paper using our pen and brain. But how can we know our program
works and gives expected result or not? For this purpose, we should execute the program on a computer
and verify the results.
Executing a program takes several steps.
In the first step, we should type our C program on any editor and save it with a .c extension. This saves
and stores program source code at some location in computer system.
Then compile the program using C compiler. The compiler converts the program source code into
equivalent machine code. The machine code is called object code. The file is generated with .obj as
extension name.
The next step is to include the additional machine code needed by the program from the C library. This is
called Linking.
For example: if we use printf() function in a C program, then that function code which is available in the C library
should be included into that C program.
Once, linking is completed, we get executable file with .exe extension name.
Finally, the executable file should be run by the C compiler to obtain the output.
Since, the executable file contains the machine code instructions which are understandable to the
processor, the processor will be able to run it and display the output.
43
44. C compiler
compiler?
Programmer can use high level language such as C
CPU knows machine language
C compiler
Commercial compiler: Microsoft Visual C/C++ (ver. 6.0)
Free compiler: gcc
44
Compiler
C program
int main…
Machine
language
010101…
46. 46
C Source Code (.c)
Compile
Object Code (.obj)
Link
Executable Code (.exe)
Run
Output
The execution sequence of a C Program
47. In DOS operating system, most if the programmers use Turbo C or Turbo C++ compilers to execute C
programs.
To work with Turbo C in any directory of your choice, you should first set the path to TCBIN directory in
system variables.
Then you can create your own directory and execute the C programs in that directory.
Steps to be followed during execution of C program:
At DOS prompt, type TC and press Enter button. The Turbo C Editor will be displayed.
47
48. To type a fresh program, we should open a new file. This can be done by selecting: File -> New Option, or
by pressing ALT+F+N keys. Now we can type the program.
To open already existing file, we should use File -> Open Option or by pressing ALT+F+O keys.
After typing the program, save the program by typing ALT+F+S keys or by pressing F2 button. When the
program is saved, type the program name with .c extension.
48
49. The next step is to compile the program. For this purpose, we should use ALT+C. If any errors are displayed,
they should be corrected and the program should be saved again. Then again compile the program to be
sure that there are no errors. When the compilation is successful, it will display success message with 0
warnings and 0 errors.
49
50. When compilation is done, linking will also be done, So, the next step is to rum the program. To run the
program, press ALT+R.
You will reach DOS prompt. Any inputs for the program should be given here. Then the output will displayed.
After displaying the output, it will come back to the editor where our source code (program) is found.
To view the output again, press ALT+F5 buttons. After viewing the output, press any button to come out.
To come out of the editor, we can press ALT+X. Then we can see the DOS prompt.
50
51. Click on the Help button in the menu.
Then Click on Contents button.
Then Click on Header files, the list of header files will be displayed. Select header file you need.
51
52. Header file contains several functions. The list of functions available in that header file will be displayed.
Select which ever the function you need.
52
53. Now complete information on that function will be displayed. We can drag the scroll bar to view the entire
page details.
By double clicking the highlighted words, we can directly go to information related to that word.
Another way to get quick help while typing the program is to keep the cursor on the word and then press
Control+F1.
53
54. By pressing F7 button, we can check the output of each statement of the program, while it is being executed.
After typing a program, press F7.
The control of the execution goes to the first statement in the program and that first statement is executed.
We can see the first statement being highlighted.
Then press F7 again to see the execution of the second statement in your program.
In this way, press the F7 button repeatedly to see the execution of the statements one by one.
This will help us to trace any logical errors in the program.
Debugging (removing errors) will become easy.
54
55. It is possible to type and execute a C program in UNIX operating system. Along with the UNIX, there should
be ANSI C compiler available in your computer. We can take the help of vi editor in UNIX to type the C
programs.
The common commands related to vi editor:
Open the vi editor by typing vi command at shell prompt (i.e., $ prompt). Once the vi editor is opened, you
can type your C program.
For example: if our program name is sum.c then we can type at shell prompt as:
Once the program tying is completed, then save it and come out of the editor.
For this purpose, we should use :wq command in the editor.
For compiling and linking, we can use cc command at shell prompt, as:
Here, cc represents c compiler.
55
$ vi sum.c
$ cc sum.c
56. By default, the program executable file will be created with the file name a.out.
So, we can run it by typing a.out at shell prompt, as:
Then the output will be displayed.
This file a.out can be renamed and used as and when required.
Note:
At the time of compilation, sometimes we may want to do mathematical calculations for which we need to
include <math.h> header file along with the program.
Here, area.c is our program name, -lm option represents that the header file <math.h> should include into the
program.
56
$ a.out
$ cc area.c -lm
57. Q1. Why C is called Middle level language?
Ans. High level languages are suitable for developing the software easily since they use English words. Low level
languages are suitable for developing software that interacts directly with the hardware. Both these features are available
in C and hence C is called Middle level language.
Q2. Can you nest a comment inside another comment in C?
Ans. No, it is not possible to write a comment inside another comment.
Q3. What is returned by main() function, by default?
Ans. main() function or any other function in C by default returns an integer type value. By writing ‘void’ before main()
function, we are indicating that main() function is not returning any value. If we do not write ‘void’ before main(), then it
returns an integer value.
Q4. What is the use of the main() function in C?
Ans. main() function is the starting point of execution of a C program. Every C program should have a main() function.
Q5. How can you accept hexadecimal numbers in C?
Ans. In scanf() function, we should use “%x” as format string to accept hexadecimal numbers, as:
int num;
scanf(“%x”, &num);
Similarly, we can accept octal numbers using “%o” format string in scanf().
57
58. Q6. Why should we place & symbol before numbers and characters type of variables in scanf() and why not before string
type variables?
Ans. The ‘&’ symbol represents the memory address where the variable value is stored. For numeric type variable and
character type variable, the variable name and its memory address are different. So, we should place & before the
variable to access the memory address.
But, in case of string type variables, the variable name itself represents the memory address and hence again & symbol
is not required to be placed before them.
Q7. What is object code?
Ans. Object code is nothing but the machine code equivalent of the source program. Object code is generated by C
Compiler.
Q8. What is executable code?
Ans. When the C library is linked into object code, then it becomes an executable file.
Q9. What is the output of printf(“%d”)?
Ans. Please observe the variable is missing in the printf(). When C compiler sees the specifier “%d”, it jumps into
memory. Since the variable is not found in the memory, it comes out with some garbage value.
58
59. Q10. What is the difference between printf() function and sprint() function?
Ans. printf() function displays data on standard output device, i.e. monitor. sprintf() function sends data to a character
type array.
For example:
printf(“HELLO”); displays “HELLO” on monitor.
sprintf(arr, “HELLO”), stores “HELLO” into the array ‘arr’.
59