0% found this document useful (0 votes)
22 views55 pages

C Programming - Module 1 - 14 Nov 2023

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
22 views55 pages

C Programming - Module 1 - 14 Nov 2023

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 55

C Programming

Module 1
Module Coverage
• Introduction to C
• Algorithms, Flowchart and Pseudocode
• Environment setup
• Program Structure
• Header Files and Comments
• Input and Output
• Escape Sequences
• Format Specifiers
• Keywords and Identifiers
• Data Types
• Variables and Constants
Introduction to C
The C-language is a general-purpose and
procedural-oriented programming language.
It is a structured and machine-independent
programming language.
It was developed by Dennis Ritchie in 1972 at
the AT&T Bell Laboratories.

C is a simple programming language in the history


of computing programming language.
It is structure oriented.
Nowadays, many programming languages have
arrived with many features like C++, Python, Java
and more but C is a base of any language.
Initially C was developed to be used in UNIX
operating system, but nowadays it’s
compatibility has grown a lot ranging from
windows, Mac, Linux, Ubuntu and others.
Many of the important working principle of C
comes from BCPL, developed by Martin
Richards.
C supports a wide variety of built-in functions,
standard libraries and header files.
It follows a top-down approach. Many languages
have derived syntax directly or indirectly from
the C programming language.
For example, C++ is closely a superset of the C
language. Also, C programming language is very
popular for system-level apps.
Importance of C Language:
• Efficiency: C allows for direct memory manipulation and low-level
access to system resources. This results in highly efficient code
execution.
• Portability: C code can be easily ported to different platforms
without major modifications, thanks to its wide availability of
compilers and libraries.
• Speed: C is known for its fast execution speed, making it suitable
for developing performance-critical applications.
• Control: C gives programmers fine-grained control over memory
management and system resources.
• Compatibility: C code can be easily integrated with code written
in other languages like C++, Java, and Python.
Algorithms, Flowchart and
Pseudocode
An Algorithm is a sequence of instructions that are carried out in a
predetermined sequence in order to solve a problem or complete a
work.
In computer science, algorithms are used for a wide range of
operations, from fundamental math to intricate data processing.
One of the common algorithms used in C is the sorting algorithm. A
sorting algorithm arranges a collection of items in a certain order, such
as numerically or alphabetically.
How to write an Algorithm:
• First define the problem you want the algorithm to solve
• Break the problem down into smaller, manageable steps
• Write your algorithm in pseudocode or a programming
language
• Test your algorithm to make sure it is correct and efficient
Algorithm Example:
Algorithm 1: Sum of two numbers
Step 1 - Start
Step 2 - Declare three integers num1,
num2, sum
Step 3 - Read the values of num1 and num2
Step 4 - Add the values of num1 and num2
Step 5 - Save the output of step 4 in sum
Step 6 - Print sum
Step 7 - Stop
Assignment:
1. Algorithm to find whether a given number is odd or
even
2. Algorithm to find maximum of any three given
numbers
Flowchart is a graphical representation of an algorithm. Programmers
often use it as a program-planning tool to solve a problem.
It makes use of symbols which are connected among them to indicate
the flow of information and processing.
A flowchart represents an algorithm, workflow, or process via a
systematic flow of diagrams.
The flowchart shows the steps-by-steps representation as boxes of
various kinds for taking input, performing calculations, throwing the
output, and their order by connecting the boxes with arrows.
This diagrammatic representation illustrates a proper solution model to
a given specific problem.
Flowcharts are used in analyzing the problem in a smooth manner then
designing a solution for that problem then, and documenting or
managing a process or program in various fields.
Flowchart Example:
Algorithm 1: Sum of two numbers
Step 1 - Start
Step 2 - Declare three integers num1, num2,
sum
Step 3 - Read the values of num1 and num2
Step 4 - Add the values of num1 and num2
Step 5 - Save the output of step 4 in sum
Step 6 - Print sum
Step 7 - Stop
Assignment:
3. Flowchart for finding whether a given number
is odd or even
4. Flowchart for finding maximum of any three
given numbers
A Pseudocode is defined as a step-by-step description of an algorithm.
Pseudocode does not use any programming language in its
representation instead it uses the simple English language text as it is
intended for human understanding rather than machine reading.
Pseudocode is the intermediate state between an idea and its
implementation(code) in a high-level language.
Pseudocode is an important part of designing an algorithm, it helps the
programmer in planning the solution to the problem as well as the reader
in understanding the approach to the problem.

Pseudocode is an intermediate state between algorithm and program that


plays supports the transition of the algorithm into the program.
Pseudocode Example:
BEGIN
NUMBER s1, s2, sum
OUTPUT("Input number1:")
INPUT s1
OUTPUT("Input number2:")
INPUT s2
sum=s1+s2
OUTPUT sum
END
Assignment:
5. Pseudocode for finding whether a given number is odd
or even
6. Pseudocode for finding maximum of any three given
numbers
Algorithm Flowchart Pseudocode
An Algorithm is used to A Flowchart is pictorial A Pseudocode is a step-
provide a solution to a representation of flow of an by-step description of an
particular problem in algorithm. algorithm in code-like
form of a well-defined structure using plain
step-based form. English text.
An algorithm only uses A Flowchart uses standard symbols Pseudocode also uses
simple English words for input, output decisions and reserved keywords like if-
start stop statements. Only uses else, for, while, etc.
different shapes like box, circle and
arrow.
These are a sequence of These are nothing but the These are fake codes as
steps of a solution to a graphical representation of the the word pseudo means
problem algorithm for a better fake, using code like
understanding of the code structure and plain
English text
There are no rules to There are certain rules for drawing There are certain rules for
writing algorithms Flowchart writing pseudocode
Environment Setup
To compile and run a C language program, we need a C compiler.
To setup a C language compiler in our Computer/laptop, there are two
ways:
• Download a full-fledged IDE like Turbo C or Microsoft Visual C++,
which comes along with a C language compiler.
• Or, we use any text editor to edit the program files and download
the C compiler separately.
Turbo C IDE is the oldest IDE for C programming. It is freely available
over internet and is good for a beginner.
If you do not wish to setup an IDE and prefer the old school way, then
download the C compiler which is called “gcc” from the gcc website
https://gcc.gnu.org/install/
Using the Tab “File” to either
create a new program or to open
the existing one and finally to
save the program with extension
“<name>.c”. Example:
firstprogram.c

Writing a new C program “Hello


World”.
Compiling C program either
using the Tab “Compile” or using
the key board control “Alt+F9” to
check errors present in the
program.

Running C program either using


the tab “Run” or using the key
board control “Ctrl+F9” to view
the program output.
Succesful compile and run steps
give us the output.
Without an IDE
• Once you have downloaded and installed the gcc compiler, all you
have to do is, open any text editor, write the C program code and
save it with the name “<any name>.c” For example: hello.c.
• Open Command prompt or Terminal (if you use Ubuntu or Mac OS),
and go to the directory where you have saved the “hello.c” program
file.
• Type the command “gcc hello.c” to compile the code. This will
compile the code, and if there are no errors then it will produce an
output file with name “a.out” (default name).
• Now, to run the program, type in “./a.out” and you will see the
output displayed on your screen.
Program Structure
The Documentation section is the part of
the program where the programmer gives
the details associated with the program.

The Link section is used to declare all the


header files that will be used in the
program. This leads to the compiler being
told to link the header files to the system
libraries.
The Definition section is used to define
different constants to be used throughout
the program.
The Global declaration section of the code
is the part where the global variables are
declared.
Every C program needs to have a main
function. Each main function contains two
parts “Declaration” part and “Execution”
part. The declaration part is the part where
all the variables are declared. The execution
must have atleast one statement and
contains the logic. Both the declaration and
execution parts must be written within the
curly braces.

The Subprogram section contains all the


user-defined functions of the program.
Example C program: To find the area of a Circle
/
***************************************************************************************
*********
File Name: areaofcircle.c
Author: vrsyrn
Date & Time: 08/11/2023; 03:00 PM
Description: a program to calculate area of circle when user enters the radius
***************************************************************************************
**********/
#include<stdio.h> //link section
#define pi 3.14; //definition section
float area(float r); //global declaration
int main() //main function
{
float r;
printf(" Enter the radius:n");
scanf("%f",&r);
printf("the area is: %f",area(r));
return 0;
}
float area(float r) //User defined function
Header files and Comments
In C Programming language, there are many predefined
functions available which make the program very easy to
write.
These predefined functions are available in the C library
and to use all these functions you need to declare a
particular header file because the header file then
makes a call to the C library and uses that particular
function in your program.
You can include the header files by C Pre-processing
directives i.e., “#include”, and must contain a “.h”
extension at the end.
For example, #include<stdio.h>, this is the header file
which stands for standard input-output function, like this
is the basic header file which is necessary for writing any
program in C, as it allows you to perform input and
Header Explanation Example
File
<stdio.h> (Standard input-output header) To perform input and scanf()
output operations printf()
<conio.h> (Console input-output header) To perform console input clrscr()
and console output operations getch()
<string.h (String header) To perform string manipulation operations strlen()
> strcpy()
<math.h> (Math header) To perform mathematical operations sqrt()
pow()
<stdlib.h> (Standard library header) To perform standard utility malloc()
functions like dynamic memory allocation calloc()
<ctype.h> (Character type header) To perform character type isaplha()
functions isdigit()
<time.h> (Time header) To perform functions related to date and setdate()
time of CPU getdate()
The Comments in C are human-readable explanations or notes in the
source code of a C program.
A comment makes the program easier to read and understand. These are
the statements that are not executed by the compiler or an interpreter.
It is considered to be a good practice to document our code using
comments.
A person reading a large code will be confused if comments are not
provided about details of the program.
There are 2 types of comments in the C language.
• Single Line Comments (//) - It starts and ends in the same line
• Multi-Line Comments (/* ......... */) - In this type of comment, the C
compiler ignores everything written from (/*) to (*/).
Single line Multi line
Comment Comment
#include<stdio.h> #include<stdio.h>
int main() int main(){
{ /*printing information
//printing information Multi-Line Comment*/
printf("Hello C");
printf("Hello C"); return 0;
return 0; }
}
Program
#1
Aim: To write a C program that prints Hello World message.
/
********************************************************************************
****************
File Name: program1.c
Author: vrsyrn
Date & Time : 08/11/2023; 03:35 PM
Description: a program to display “Hello World!!” message
********************************************************************************
*****************/
#include<stdio.h> // Header file
void main() // main function
{
printf(" Hello World!!"); // to display the output on screen
}
Output:
/* End of Program */
Note 1:
• In the C Programming Language, the #include directive tells the
preprocessor to insert the contents of another file into the source code
at the point where the #include directive is found.
• The C language is case-sensitive. It can distinguish between upper
case and lower case characters and treat the keywords and identifiers
accordingly.
• Every C program must contain a main() function.
• main() function is the entry point of any C program. It is the point at
which execution of program is started.
• The main function may contain any number of statements. These
statements are executed sequentially in the order which they are
written.
• When a C program is executed, the execution control goes directly to
the main() function.
Note 1 (contd..):
• The void keyword before the main() specifies that the function doesn't
return a value. void specifies that the function takes no parameters.
• The ANSI (American National Standards Institute) standard says "no"
to the ‘void main’ and thus using it can be considered wrong.It's a
non-standard thing.
• We can use the ‘int’ keyword as the return type of the main function in
c to depict that the function is returning an integer value. If the
returned value from the main function in C is 0, then the program has
been executed successfully.
• 0 is the standard for the “successful execution of the program”.
• A return statement ends the execution of a function,
and returns control to the calling function.
• return(0) in the main function means that the program executed
successfully.
Note 1 (contd..):
• The printf() function is used for output. It prints the given statement to
the console.
• Semicolons are end statements in C language.
• The Semicolon tells that the current statement has been terminated
and other statements following are new statements.
• Usage of Semicolon in C will remove ambiguity and confusion while
looking at the code.
• When the previous program is executed, the output just disappears
after coming and leave us no time to view or record the output
(Windows OS).
• To make the output standby till our next command, we can make use
of getch() function coming under the header file <conio.h> that tells
the compiler to wait for a character after displaying the output.
Program
#make
Aim: To enhance the program 1 and 2 the output wait in standby mode.
/
*****************************************************************************************
*******************************
File Name: program2.c
Author: vrsyrn
Date & Time : 08/11/2023; 03:45 PM
Description: a program to display “Hello World!!” message and wait in standby mode
after displaying the output
*****************************************************************************************
*******************************/
#include<stdio.h> // Header file
#include<conio.h>
int main() // main function
{
printf(" Hello World!!"); // to display the output on
screen
getch();
return 0;
Output:
Note 2:
• When the previous program is executed, we could observe two “Hello
World!!” messages on the console (monitor) because we have run two
programs in the same console and the previous outputs would still be
there on the console.
• clrscr() is a function that can clear the console output during the
execution of the c program. This function is defined in the <conio. h>
header file.
• Using of clrscr() is always optional but it should be placed only after
variable or function declaration.
• <conio.h> header file is not recongnised in gcc compiler, it throws an
error if we use clrscr() or <conio.h>. For gcc compiler, cls() function is
used to clear the console screen. This function is present in the
standard library header file <stdlib>.
Program #
Aim: To enhance the program 2 by3adding your personal details and display the same on
the console (monitor).
/
*****************************************************************************************
*******************************
File Name: program3.c
Author: vrsyrn
Date & Time : 08/11/2023; 04:00 PM
Description: a program to display our personal details
*****************************************************************************************
*******************************/
#include<stdio.h> // Header file
#include<conio.h>
int main() // main function
{
clrscr(); // to clear the screen (console)
printf(“Student Name: Sooraj");
printf("Student ID: YE112");
printf("Designation: Trainee");
printf("Branch: Vijayawada");
printf("Address: House No: 12-360");
printf("Modern Food Steet");
printf("Benz Circle");
printf("Vijayawada - 520010");
printf("Andhra Pradesh");
getch();
return 0;
}
/* End of Program */

Output:
Note 3:
• When we execute program 3, the output may seem to be clumsy and
not in a good presentation.
• This is because there is no proper formatting in the output. In order to
achieve the program output in a neat format, we have to make use of
“Escape Sequences” in C programming language.
Escape Sequences
An Escape Sequence in C is used to conveniently format the strings and
outputs of a program.
The escape sequence does not appear in the output when written in a
character or string literal, rather it is represented through its
functionality.
The escape sequence consists of a backslash and any other character
from the C character set.
Below are the 15 types of escape sequences that C provides:
Escape Meaning Description
Sequence
\a Alarm or Beep Generates a beep that alerts the user when the
program is executed.
\n New Line Starts a new line in the output/string.
\t Horizonal Tab Adds a horizontal tab in the output/string.
Escape Meaning Description
Sequence
\r Carriage Return Places the cursor at the start of the current
line.
\f Form Feed Places the cursor at the start of the next
page.
\v Vertical Tab Adds a vertical tab in the output/string.
\\ Backslash Displays a backslash in the output/string.
\' Single Quote Displays a single quote in the output/string.
\" Double Quote Displays a double quote in the output/string.
\nnn Octal Number Represents an octal number.
\xhh Hexadecimal Represents a hexadecimal number.
number
\0 Null Adds a 0 character and usually denotes the
termination of a string.
\b Backspace Backspaces a single character.
\? Question Mark Displays a question mark.
Program
Aim: To enhance the program 3 and#display
4 the output in a neat format.
/
*****************************************************************************************
*******************************
File Name: program4.c
Author: vrsyrn
Date & Time : 08/11/2023; 04:15 PM
Description: a program to display the output in a neat format
*****************************************************************************************
*******************************/
#include<stdio.h> // Header file
#include<conio.h>
int main() // main function
{
clrscr();
printf("Student Name\t: Sooraj\n");
printf("Student ID\t: YE112\n");
printf("Designation\t: Trainee\n");
printf("Branch\t\t: Vijayawada\n");
printf("Qualification\t: B.Tech\n");
printf("Address\t\t: House No: 12-360\n");
printf("\t\t Modern Food Steet\n");
printf("\t\t Benz Circle\n");
printf("\t\t Vijayawada - 520010\n");
printf("\t\t Andhra Pradesh");
getch();
return 0;
}

/* End of Program */

Output:
Note 4:
• printf() statement is used to display any text on the screen.
• The Escape sequences \n and \t are used to align the text.
Format Specifiers
The Format Specifier in C is used to tell the compiler about the type of
data to be printed or scanned in input and output operations.
They always start with a % symbol and are used in the formatted string
in functions like printf(), scanf, sprintf(), etc.
The C language provides a number of format specifiers that are
associated with the different data types such as %d for int, %c for char,
etc. Below are the most commonly used format specifiers in C.

Format Description
Specifier
%d or %i It is used to print the signed integer value where signed integer
means that the variable can hold both positive and negative values.
%u It is used to print the unsigned integer value where the unsigned
integer means that the variable can hold only positive value.
Format Description
Specifier
%o It is used to print the octal unsigned integer where octal integer
value always starts with a 0 value.
%x It is used to print the hexadecimal unsigned integer where the
hexadecimal integer value always starts with a 0x value. In this,
alphabetical characters are printed in small letters such as a, b, c,
etc.
%X It is used to print the hexadecimal unsigned integer, but %X prints
the alphabetical characters in uppercase such as A, B, C, etc.
%f It is used for printing the decimal floating-point values. By default, it
prints the 6 values after '.'.
%e/%E It is used for scientific notation. It is also known as Mantissa or
Exponent.
%g It is used to print the decimal floating-point values, and it uses the
fixed precision, i.e., the value after the decimal in input would be
exactly the same as the value in the output.
Format Description
Specifier
%p It is used to print the address in a hexadecimal form.

%c It is used to print the unsigned character.


%s It is used to print the strings.

%ld It is used to print the long-signed integer value.


Input and Output
In C, Input refers to providing it with some information or data to be
utilised in the program.
On the other hand, Output refers to writing the data and information on
any printer file and displaying it on the screen.
A standard library is available in the C language for reading any input
and generating the output to be displayed on the console.
C language offers us several built-in functions for performing input/output
operations. The following are the functions used for standard input and
output:
• printf()
• scanf()
• getchar() and putchar()
• gets() and puts()
printf():
• This is the most used function in the C language.
• This function is defined in the stdio.h header file and is used to show
output on the console (standard output).
• Examples: printf("Welcome to vrsyrn");
printf("Value of x is: %d", x);

scanf():
• When we want to take input from the user, we use the scanf() function
and store the input value into a variable. This function is defined in
the stdio.h header file.
• Examples: scanf("%x", &variable);
scanf("%d", &user_input);
getchar():
• The getchar() function reads a character from the terminal and returns
it as an integer. This function reads only a single character at a time.
• This function is defined in the stdio.h header file.
• Examples: getchar();

putchar():
• 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. This function is defined in the
stdio.h header file.
• Examples: c = getchar();
putchar(c);
gets():
• In ‘C’ scanf( ) is not capable of receiving a multiword string, therefore,
names such as “Rajeev Sharma” would be unacceptable.
• gets() function is used to scan a line of text from input device and will
be terminated by a newline character.
• Example: printf (“enter your name");
gets (name);

puts():
• puts() writes a string to standard output which is previously read by
gets() upto but not including the null character. These are under
stdio.h header file.
• Example: printf (“enter your name");
gets (name);
puts (name);

You might also like