Unit 02
Unit 02
What is C?
C was developed at Bell Laboratories as a general-purpose systems programming
language.
It has been used in the development of the UNIX™ operating system and has grown in
importance with the growth of UNIX™
Basic Structure of C Programs :
All human beings have a definite structure, i.e., head, neck, and four limbs connected to a
torso. Almost everything has a definite structure. Likewise, in the case of programming
languages, all of them have a definite structure. These structures have to be followed while
writing the code.
The structure of a C program can be mainly divided into six parts, each having its purpose. It
makes the program easy to read, easy to modify, easy to document, and makes it consistent in
format.
Section Description
Algorithm
You've to subtract the current year from your birth year and get your age.
Code:
Output
Different sections of the above code
Documentation
In a C program, single-line comments can be written using two forward slashes i.e., //, and we
can create multi-line comments using /* */. Here, we've used multi-line comments.
/**
* file: age.c
* author: you
* description: program to find our age.
*/
Link
Definition
A preprocessor directive in C is any statement that begins with the "#" symbol. The #define is a
preprocessor compiler directive used to create constants. In simple terms, #define basically
allows the macro definition, which allows the use of constants in our code.
We've created a constant BORN which is assigned a value of 2000. Generally, uppercase letters
are preferred for defining the constants. The above constant BORN will be replaced by 2000
throughout our code wherever used.
#define is typically used to make a source program easy to modify and compile in different
execution environments.
Global Declaration
This section includes all global variables, function declarations, and static variables. The
variables declared in this section can be used anywhere in the program. They're accessible to all
the functions of the program. Hence, they are called global variables.
int age(int current);
We've declared our age function, which takes one integer argument and returns an integer.
Main() Function
In the structure of a C program, this section contains the main function of the code. The C
compiler starts execution from the main() function. It can use global variables, static variables,
inbuilt functions, and user-defined functions. The return type of the main() function can be void
and also not necessarily int.
int main(void)
return 0;
Here, we've declared a variable named current and assigned the value as 2021. Then we've called
the printf() function, with calls the age() function, which takes only one parameter.
Subprograms
This includes the user-defined functions called in the main() function. User-defined functions are
generally written after the main() function irrespective of their order.
When the user-defined function is called from the main() function, the control of the program
shifts to the called function, and when it encounters a return statement, it returns to the main()
function. In this case, we've defined the age() function, which takes one parameter, i.e., the
current year.
This function is called in the main function. It returns an integer to the main function.
Library functions
Library functions are built-in functions that are grouped together and placed in a common location
called library.
Each function here performs a specific operation. We can use this library functions to get the pre-
defined output.
All C standard library functions are declared by using many header files. These library functions
are created at the time of designing the compilers.
We include the header files in our C program by using #include<filename.h>. Whenever the
program is run and executed, the related files are included in the C program.
Header File Functions
Some of the header file functions are as follows −
stdio.h − It is a standard i/o header file in which Input/output functions are declared
conio.h − This is a console input/output header file.
string.h − All string related functions are in this header file.
stdlib.h − This file contains common functions which are used in the C programs.
math.h − All functions related to mathematics are in this header file.
time.h − This file contains time and clock related functions.Built functions in stdio.h
ctype.h – All the functions which are related to character.
List of formatted and unformatted input output functions are shown in the figure
1. Formatted I/O Function:
The I/O procedure is known as "formatted I/O". It enables you to read or write data in a
certain format. Printf() and scanf() are two examples of C routines that handle formatted I/O. The
type and format of the data to be read or written are specified by format strings, which are used by
these operations. The program's execution replaces the placeholders for the data found in the
format strings with the actual data.
Syntax:
Here, the argument list comprises the variables or values to be printed, and the format string
determines the output format.
Here, the argument list comprises the variables that will receive the input, and the format string
describes the format of the input.
Example:
Output:
Syntax:
Here, count is the number of elements to be written, size is the size of each element to be written,
and the file pointer is a pointer to the file where the data will be written.
Syntax for using the fread() method with unformatted input:
In this syntax, a pointer to the buffer where the data will be read, the size of each element to be
read, the number of elements to be read, and a pointer to the file from which the data will be read.
Example
Output:
Explanation:
In the example, we first declare a file pointer (fp) and a character array (data). After that, the file
pointer is assigned to 'fp' after using the 'fopen()' method to open the 'file.txt' file in write mode.
The string "This is an example of unformatted output." is written to the file using
the 'fputs()' function. The file pointer is then moved to the file's beginning using
the 'fseek()' function. After that, the data is shown using the 'printf()' function after being read from
the file into the 'data' buffer using the 'fread()' function.
Formatted and Unformatted I/O differences
In C, there are a few distinctions between formatted and unformatted I/O. Some of these
variations include:
1. Unformatted I/O reads and writes data as a stream of bytes without any format,
whereas formatted I/O enables you to read and write data in a predefined format.
2. Flexibility: Formatted I/O offers greater options for output formatting and data
representation, whereas unformatted I/O offers less flexibility and is better suited to
reading and writing binary data.
3. Usability: Formatted I/O is more user-friendly for straightforward input and output
activities, whereas unformatted I/O necessitates more code and is better suited for intricate
input and output procedures.
4. Efficiency: Because unformatted I/O doesn't require any formatting or data type
conversion, it is more efficient than formatted I/O.
Conclusion - Formatted and Unformatted I/O operations are Input/Output operations that are
utilized in C programming. Unformatted I/O is used to read and write data as a stream of bytes
without any format, whereas formatted I/O is used to read and write data in a predefined format.
The choice of which form of I/O operation to use relies on the requirements of the program. Both
types of I/O operations have benefits and drawbacks.
Flow Chart
The Flowchart is the most widely used graphical representation of an algorithm and procedural
design workflows. It uses various symbols to show the operations and decisions to be followed in
a program. It flows in sequential order.
Types of Flowchart
o Horizontal Flowchart
o Panoramic Flowchart
o Vertical Flowchart
o Architectural Flowchart
Rules or guidelines of Flow
Chart:
Flowchart symbols:
o Terminal Symbol: In the flowchart, it is represented with the help of a circle for denoting
the start and stop symbol. The symbol given below is used to represent the terminal symbol.
o Input/output Symbol: The input symbol is used to represent the input data, and the
output symbol is used to display the output operation. The symbol given below is used
for representing the Input/output symbol.
o Processing Symbol: It is represented in a flowchart with the help of a rectangle box used
to represent the arithmetic and data movement instructions. The symbol given below is
used to represent the processing symbol.
o Decision Symbol: Diamond symbol is used for represents decision-making statements.
The symbol given below is used to represent the decision symbol.
o Connector Symbol: The connector symbol is used if flows discontinued at some point
and continued again at another place. The following symbol is the representation of the
connector symbol.
o Flow lines: It represents the exact sequence in which instructions are executed. Arrows
are used to represent the flow lines in a flowchart. The symbol given below is used for
representing the flow lines:
o Hexagon symbol (Flat): It is used to create a preparation box containing the loop setting
statement. The symbol given below is used for representing the Hexagon symbol.
o On-Page Reference Symbol: This symbol contains a letter inside that indicates the flow
continues on a matching symbol containing the same letters somewhere else on the same
page. The symbol given below is used for representing the on-page reference symbol.
o Off-Page Reference: This symbol contains a letter inside indicating that the flow
continues on a matching symbol containing the same letter somewhere else on a different
page. The symbol given below is used to represent the off-page reference symbol.
o Delay or Bottleneck: This symbol is used for identifying a delay in a flowchart. The
alternative name used for the delay is the bottleneck. The symbol given below is used to
represent the delay or bottleneck symbol.
o Internal storage symbol: The symbol given below is used to represent the internal storage
symbol.
Advantages of Flowchart in C:
Disadvantages of Flowchart in C:
Example 1:
Design a flowchart for finding the largest among three numbers entered by the user.
Example 3:
Design a flowchart for calculating the profit and loss according to the value entered by the user.
Example 4:
Example 5:
Design a flowchart for the multiplication of three numbers entered by the user.
Example 6:
Example 7:
Design a flowchart for calculating the Simple Interest according to the value entered by the user.
Example 8:
Design a flowchart for checking whether the number is positive or negative according to the
number entered by the user.
Decision control statements in C programming language
In any programming language, there is a need to perform different tasks based on the
condition. For example, consider an online website, when you enter wrong id or password it
displays error page and when you enter correct credentials then it displays welcome page. So
there must be a logic in place that checks the condition (id and password) and if the condition
returns true it performs a task (displaying welcome page) else it performs a different
task(displaying error page).
Using decision control statements we can control the flow of program in such a way
so that it executes certain statements based on the outcome of a condition (i.e. true or false).
In C Programming language we have following decision control statements.
1. if statement
3. switch-case statements
1. if statement
• The statements inside if body executes only when the condition defined by if
statement is true. If the condition is false then compiler skips the statement enclosed in if’s
body. We can have any number of if statements in a C program.
• It is one of the most simple form of decision control statements which is frequently
used in decision making. • When we need to execute a block of statements only when a given
condition is true then we use if statement
• The statements inside the body of “if” only execute if the given condition returns true.
If the condition returns false then the statements inside “if” are skipped.
• Syntax of if statement:
Flowchart of if statement in C
1. #include<stdio.h>
2. int main(){
3. int number=0;
4. printf("Enter a number:");
5. scanf("%d",&number);
6. if(number%2==0){
7. printf("%d is even number",number);
8. }
9. return 0;
10. }
Output
Enter a number:4
4 is even number
enter a number:5
Program to find the largest number of the three.
1. #include <stdio.h>
2. int main()
3. {
4. int a, b, c;
5. printf("Enter three numbers?");
6. scanf("%d %d %d",&a,&b,&c);
7. if(a>b && a>c)
8. {
9. printf("%d is largest",a);
10. }
11. if(b>a && b > c)
12. {
13. printf("%d is largest",b);
14. }
15. if(c>a && c>b)
16. {
17. printf("%d is largest",c);
18. }
19. if(a == b && a == c)
20. {
21. printf("All are equal");
22. }
23. }
Output
The if-else statement is used to perform two operations for a single condition. The if-else statement
is an extension to the if statement using which, we can perform two different operations, i.e., one
is for the correctness of that condition, and the other is for the incorrectness of the condition. Here,
we must notice that if and else block cannot be executed simiulteneously. Using if-else statement
is always preferable since it always invokes an otherwise case with every if condition. The syntax
of the if-else statement is given below.
1. if(expression){
2. //code to be executed if condition is true
3. }else{
4. //code to be executed if condition is false
5. }
1. #include<stdio.h>
2. int main(){
3. int number=0;
4. printf("enter a number:");
5. scanf("%d",&number);
6. if(number%2==0){
7. printf("%d is even number",number);
8. }
9. else{
10. printf("%d is odd number",number);
11. }
12. return 0;
13. }
Output
enter a number:4
4 is even number
enter a number:5
5 is odd number
Program to check whether a person is eligible to vote or not.
1. #include <stdio.h>
2. int main()
3. {
4. int age;
5. printf("Enter your age?");
6. scanf("%d",&age);
7. if(age>=18)
8. {
9. printf("You are eligible to vote...");
10. }
11. else
12. {
13. printf("Sorry ... you can't vote");
14. }
15. }
Output
The if-else-if ladder statement is an extension to the if-else statement. It is used in the scenario
where there are multiple cases to be performed for different conditions. In if-else-if ladder
statement, if a condition is true then the statements defined in the if block will be executed,
otherwise if some other condition is true then the statements defined in the else-if block will be
executed, at the last if none of the condition is true then the statements defined in the else block
will be executed. There are multiple else-if blocks possible. It is similar to the switch case
statement where the default is executed instead of else block if none of the cases is matched.
1. if(condition1){
2. //code to be executed if condition1 is true
3. }else if(condition2){
4. //code to be executed if condition2 is true
5. }
6. else if(condition3){
7. //code to be executed if condition3 is true
8. }
9. ...
10. else{
11. //code to be executed if all the conditions are false
12. }
Flowchart of else-if ladder statement in C
enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
Program to calculate the grade of the student according to the specified marks.
1. #include <stdio.h>
2. int main()
3. {
4. int marks;
5. printf("Enter your marks?");
6. scanf("%d",&marks);
7. if(marks > 85 && marks <= 100)
8. {
9. printf("Congrats ! you scored grade A ...");
10. }
11. else if (marks > 60 && marks <= 85)
12. {
13. printf("You scored grade B + ...");
14. }
15. else if (marks > 40 && marks <= 60)
16. {
17. printf("You scored grade B ...");
18. }
19. else if (marks > 30 && marks <= 40)
20. {
21. printf("You scored grade C ...");
22. }
23. else
24. {
25. printf("Sorry you are fail ...");
26. }
27. }
Output
1.Conditional loop
Computer Programming, conditional loops or repetitive control structures are a way for
Computer Program to repeat one or more various steps depending on conditions set either by the
programmer initially or real-time by the actual program. There are two types of conditional
loops, WHILE LOOP & DO WHILE LOOP. One or more expressions control both types of
loops. However, DO WHILE loops test the expression before the loop executes the first time and
repeat only when the expression is true. WHILE loops test the expression after the loop executes
at least once and repeat only when the expression is false.
2.Unconditional loop
If condition is always true, then the loop is infinite whereas if condition is always false
the code in the loop will never run. Unconditional Loops that repeat set of commands with no
condition, so loop execution is compulsory. We also know unconditional loops as infinite loops,
as its condition is always true. FOR LOOP is the type of unconditional loop
The looping simplifies the complex problems into the easy ones. It enables us to alter the flow of
the program so that instead of writing the same code again and again, we can repeat the same code
for a finite number of times. For example, if we need to print the first 10 natural numbers then,
instead of using the printf statement 10 times, we can print inside a loop which runs up to 10
iterations.
Advantage of loops in C
2) Using loops, we do not need to write the same code again and again.
3) Using loops, we can traverse over the elements of data structures (array or linked lists).
Types of C Loops
1. do while
2. while
3. for
do-while loop in C
The do-while loop continues until a given condition satisfies. It is also called post tested loop. It is
used when it is necessary to execute the loop at least once (mostly menu driven programs).
1. do{
2. //code to be executed
3. }while(condition);
1. while loop in C
The while loop in c is to be used in the scenario where we don't know the number of iterations in
advance. The block of statements is executed in the while loop until the condition specified in the
while loop is satisfied. It is also called a pre-tested loop.
1. while(condition){
2. //code to be executed
3. }
Flowchart of while loop in C
Let's see the simple program of while loop that prints table of 1.
1. #include<stdio.h>
2. int main(){
3. int i=1;
4. while(i<=10){
5. printf("%d \n",i);
6. i++;
7. }
8. return 0;
9. }
Output
1
2
3
4
5
6
7
8
9
10
Program to print table for the given number using while loop in C
1. #include<stdio.h>
2. int main(){
3. int i=1,number=0,b=9;
4. printf("Enter a number: ");
5. scanf("%d",&number);
6. while(i<=10){
7. printf("%d \n",(number*i));
8. i++;
9. }
10. return 0;
11. }
Output
Enter a number: 50
50
100
150
200
250
300
350
400
450
500
2. for loop in C
The for loop is used in the case where we need to execute some part of the code until the given
condition is satisfied. The for loop is also called as a per-tested loop. It is better to use for loop if
the number of iteration is known in advance.
1. for(initialization;condition;incr/decr){
2. //code to be executed
3. }
Flowchart of for loop in C
Let's see the simple program of for loop that prints table of 1.
1. #include<stdio.h>
2. int main(){
3. int i=0;
4. for(i=1;i<=10;i++){
5. printf("%d \n",i);
6. }
7. return 0;
8. }
Output
1
2
3
4
5
6
7
8
9
10
C Program: Print table for the given number using C for loop
1. #include<stdio.h>
2. int main(){
3. int i=1,number=0;
4. printf("Enter a number: ");
5. scanf("%d",&number);
6. for(i=1;i<=10;i++){
7. printf("%d \n",(number*i));
8. }
9. return 0;
10. }
Output
Enter a number: 2
2
4
6
8
10
12
14
16
18
20
3. do while loop in C
The do while loop is a post tested loop. Using the do-while loop, we can repeat the execution of
several parts of the statements. The do-while loop is mainly used in the case where we need to
execute the loop at least once. The do-while loop is mostly used in menu-driven programs where
the termination condition depends upon the end user.
1. do{
2. //code to be executed
3. }while(condition);
Example 1
1. #include<stdio.h>
2. #include<stdlib.h>
3. void main ()
4. {
5. char c;
6. int choice,dummy;
7. do{
8. printf("\n1. Print Hello\n2. Print Javatpoint\n3. Exit\n");
9. scanf("%d",&choice);
10. switch(choice)
11. {
12. case 1 :
13. printf("Hello");
14. break;
15. case 2:
16. printf("Javatpoint");
17. break;
18. case 3:
19. exit(0);
20. break;
21. default:
22. printf("please enter valid choice");
23. }
24. printf("do you want to enter more?");
25. scanf("%d",&dummy);
26. scanf("%c",&c);
27. }while(c=='y');
28. }
Output
1. Print Hello
2. Print Javatpoint
3. Exit
1
Hello
do you want to enter more?
y
1. Print Hello
2. Print Javatpoint
3. Exit
2
Javatpoint
do you want to enter more?
n
Flowchart of do while loop
do while example
There is given the simple program of c language do while loop where we are printing the table of
1.
1. #include<stdio.h>
2. int main(){
3. int i=1;
4. do{
5. printf("%d \n",i);
6. i++;
7. }while(i<=10);
8. return 0;
9. }
Output
1
2
3
4
5
6
7
8
9
10
Program to print table for the given number using do while loop
1. #include<stdio.h>
2. int main(){
3. int i=1,number=0;
4. printf("Enter a number: ");
5. scanf("%d",&number);
6. do{
7. printf("%d \n",(number*i));
8. i++;
9. }while(i<=10);
10. return 0;
11. }
Output
Enter a number: 5
5
10
15
20
25
30
35
40
45
50