0% found this document useful (0 votes)
24 views59 pages

c prog

The C programming language, created by Dennis Ritchie in 1972, is a general-purpose, structured, and machine-independent language widely used for developing applications and operating systems. Learning C is beneficial as it serves as a foundation for many other programming languages, offering features like modular programming, portability, and a rich set of built-in functions. Key concepts include data types, variables, tokens, and input/output functions, which are essential for writing efficient C programs.

Uploaded by

prema latha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views59 pages

c prog

The C programming language, created by Dennis Ritchie in 1972, is a general-purpose, structured, and machine-independent language widely used for developing applications and operating systems. Learning C is beneficial as it serves as a foundation for many other programming languages, offering features like modular programming, portability, and a rich set of built-in functions. Key concepts include data types, variables, tokens, and input/output functions, which are essential for writing efficient C programs.

Uploaded by

prema latha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 59

What is C Programming Language?

Basics, Introduction
History of C language

In 1972, a great computer scientist Dennis Ritchie created a new


programming language
called ‘C’ at the Bell Laboratories. It was created from ‘ALGOL’,
‘BCPL’ and ‘B’ programming
languages. ‘C’ programming language contains all the features of
these languages and many
more additional concepts that make it unique from other
languages.
What is C Programming Langauge?
C is a general-purpose programming language that is extremely
popular, simple, and flexible to use. It is a structured
programming language that is machine-independent and
extensively used to write various applications, Operating
Systems like Windows, and many other complex programs like
Oracle database, Git, Python interpreter, and more.
It is said that ‘C’ is a god’s programming language. One can say,
C is a base for the programming. If you know ‘C,’ you can easily
grasp the knowledge of the other programming languages that
uses the concept of ‘C’
Why learn C Language?
As we studied earlier, ‘C’ is a base language for many programming languages. So, learning ‘C’
as the main language will play an important role while studying other programming
languages. It shares the same concepts such as data types, operators, control statements and
many more. ‘C’ can be used widely in various applications. It is a simple language and
provides faster execution. There are many jobs available for a ‘C’ developer in the current
market.
‘C’ is a structured programming language in which program is divided into various modules.
Each module can be written separately and together it forms a single ‘C’ program. This
structure makes it easy for testing, maintaining and debugging processes.
‘C’ contains 32 keywords, various data types and a set of powerful built-in functions that make
programming very efficient.
Various compilers are available in the market that can be used for executing programs written
in this language.
It is a highly portable language which means programs written in ‘C’ language can run on
other machines. This feature is essential if we wish to use or execute the code on another
How C Programming Language Works?
C is a compiled language. A compiler is a special tool that compiles the program and
converts it into the object file which is machine readable.
After the compilation process, the linker will combine different object files and creates
a single executable file to run the program.

The following diagram shows the execution of a ‘C’ program


Nowadays, various compilers are available online, and you can use any of
those compilers. The functionality will never differ and most of the
compilers
will provide the features required to execute both ‘C’ and ‘C++’ programs.
Following is the list of popular compilers available online:
•Clang compiler
•MinGW compiler (Minimalist GNU for Windows)
•Portable ‘C’ compiler
•Turbo C
C Basic Commands
Following are the basic commands in C programming language:
C Basic commands Explanation

This command includes standard input output header file(stdio.h) from the C library
#include <stdio.h>
before compiling a C program
int main() It is the main function from where C program execution begins.
{ Indicates the beginning of the main function.
/ Whatever written inside this command “/* */” inside a C program,
*_some_comments_*/ it will not be considered for compilation and execution.

printf(“Hello_World! “); This command prints the output on the screen.

getch(); This command is used for any character input from keyboard.
return 0; This command is used to terminate a C program (main function) and it returns 0.
} It is used to indicate the end of the main function.
How to write Comments in C Programming
What Is Comment In C Language?

A comment is an explanation or description of the source code of the


program. It helps a developer explain logic of the code and improves
program readability. At run-time, a comment is ignored by the compiler.
There are two types of comments in C:
1) A comment that starts with a slash asterisk /* and finishes with an
asterisk slash */ and you can place it anywhere in your code, on the same
line or several lines.
2) Single-line Comments which uses a double slash // dedicated to
comment single lines
Why do you need comments?

A good programmer who writes codes understood by a human is better than a


programmer who generates codes understood only by the machine.
So, it is highly recommended to insert comments to your code because it is good
programming practice. Comments do not affect a program because the compiler
ignores them.
Comments help the developer understand the logic/algorithm of the code if he
revisits it after a long time.
C Tokens, Identifiers, Keywords: What is Tokens & Its Types
What is a Character set?

Like every other language, ‘C’ also has its own character set. A program is a set of
instructions that, when executed, generate an output. The data that is processed
by a program consists of various characters and symbols. The output generated is
also a combination of characters and symbols.
A character set in ‘C’ is divided into,
 Letters
 Numbers
 Special characters
 White spaces (blank spaces)
1) Letters - Uppercase characters (A-Z),Lowercase characters (a-z)
2) Numbers - All the digits from 0 to 9
3) White spaces- Blank space,New line,Carriage return,Horizontal tab
4) Special characters
Special Character Description
, (comma) { (opening curly bracket)
. (period) } (closing curly bracket)
; (semi-colon) [ (left bracket)
: (colon) ] (right bracket)
? (question mark) ( (opening left parenthesis)
‘ (apostrophe) ) (closing right parenthesis)
” (double quotation mark) & (ampersand)
! (exclamation mark) ^ (caret)
|(vertical bar) + (addition)
/ (forward slash) – (subtraction)
\ (backward slash) * (multiplication)
~ (tilde) / (division)
_ (underscore) > (greater than or closing angle bracket)
$ (dollar sign) < (less than or opening angle bracket)
% (percentage sign) # (hash sign)
What is Token in C?

TOKEN is the smallest unit in a ‘C’ program. It is each and every word and
punctuation that you come across in your C program. The compiler breaks a
program into the smallest possible units (Tokens) and proceeds to the
various stages of the compilation. C Token is divided into six different types,
viz, Keywords, Operators, Strings, Constants, Special Characters, and
Identifiers.
Keywords and Identifiers
In ‘C’ every word can be either a keyword or an identifier.
Keywords have fixed meanings, and the meaning cannot be changed.
They act as a building block of a ‘C’ program. There are a total of 32 keywords in ‘C’.
Keywords are written in lowercase letters.
Following table represents the keywords in ‘C’-
Keywords in C Programming Language
auto double int struct
break else long switch
case enum register typedef
char extern return union
const short float unsigned
continue for signed void
default goto sizeof volatile
do if static while
An identifier is nothing but a name assigned to an element in a program.
Example, name of a variable, function, etc. Identifiers in C language are the
user-defined names consisting of ‘C’ standard character set. As the name
says, identifiers are used to identify a particular element in a program.
Each identifier must have a unique name. Following rules must be
followed for identifiers:
1) The first character must always be an alphabet or an underscore.
2) It should be formed using only letters, numbers, or underscore.
3) A keyword cannot be used as an identifier.
4) It should not contain any whitespace character.
5) The name must be meaningful.
What is a Variable?

A variable is an identifier which is used to store some value. Constants can never
change at the time of execution. Variables can change during the execution of a
program and update the value stored inside it.
A single variable can be used at multiple locations in a program. A variable
name must be meaningful. It should represent the purpose of the variable.

Example: Height, age, are the meaningful variables that


represent the purpose it is being used for. Height
variable can be used to store a height value. Age
variable can be used to store the age of a person

A variable must be declared first before it is used somewhere inside the


program. A variable name is formed using characters, digits and an underscore.
Following are the rules that must be followed while creating a variable:

1) A variable name should consist of only characters, digits and an underscore.


2)A variable name should not begin with a number.
3) A variable name should not consist of whitespace.
4) A variable name should not consist of a keyword.
5) ‘C’ is a case sensitive language that means a variable named ‘age’ and ‘AGE’
are different.
Following are the examples of valid variable names in a ‘C’ program:
height or HEIGHT_height_height1My_name

Following are the examples of invalid variable names in a ‘C’ program:


1heightHei$ghtMy name

For example, we declare an integer variable my_variable and assign it the value 48:
int my_variable;my_variable = 48;

By the way, we can both declare and initialize (assign an initial value) a variable in a
single statement:
int my_variable = 48;
Data types
‘C’ provides various data types to make it easy for a programmer to select a
suitable data type as per the requirements of an application. Following are
the three data types:

There are five primary fundamental data types,


1) int for integer data
2) char for character data
3)float for floating point numbers
4) double for double precision floating point numbers
5) void
Integer data type

Integer is nothing but a whole number. An integer typically is of 2 bytes which means it
consumes a total of 16 bits in memory. A single integer value takes 2 bytes of memory.
An integer data type is further divided into other data types such as short int, int, and
long int.
Each data type differs in range even though it belongs to the integer data type family.
The size may not change for each data type of integer family.
The short int is mostly used for storing small numbers, int is used for storing averagely
sized integer values, and long int is used for storing large integer values.
Whenever we want to use an integer data type, we have place int before the identifier
such as,
int age;
Here, age is a variable of an integer data type which can be used to store integer values.
Floating point data type
Like integers, in ‘C’ program we can also make use of floating point data types. The
‘float’ keyword is used to represent the floating point data type. It can hold a floating
point value which means a number is having a fraction and a decimal part. A floating
point value is a real number that contains a decimal point. Integer data type doesn’t
store the decimal part hence we can use floats to store decimal part of a value.

Generally, a float can hold up to 6 precision values. If the float is not sufficient, then we
can make use of other data types that can hold large floating point values. The data type
double and long double are used to store real numbers with precision up to 14 and 80
bits respectively.

While using a floating point number a keyword float/double/long double must be placed
before an identifier. The valid examples are,
float division;double BankBalance;
Character data type
Character data types are used to store a single character value
enclosed in single quotes.
A character data type takes up-to 1 byte of memory space.
Example,
Char letter;
Type declaration of a variable
int main()
{
int x, y;
float salary = 13.48;
char letter = 'K’;
x = 25;
y = 34;
int z = x+y;
printf("%d \n", z);
printf("%f \n", salary);
printf("%c \n", letter);
return 0;
}
Output:
5913.480000K
We can declare multiple variables with the same data type on a single line by
separating them with a comma. Also, notice the use of format specifiers
in printf output function float (%f) and char (%c) and int (%d).
C Input and Output

C language offers us several built-in functions for performing


input/output operations. Following are the functions used for
standard input and output:

1.printf() function - Show Output


2.scanf() function - Take Input
3.getchar() and putchar() function
4.gets() and puts() function
The printf() function
The printf() function is the most used function in the C language

rintf() Code Examples

1. Print a sentence
Let's print a simple sentence using the printf() function.
#include <stdio.h>
int main()
{ // using printf()

printf("Welcome to Studytonight“
);
return 0;
}
2. Print an Integer value

We can use the printf() function to print integer value coming from a
variable using the %d format specifier.

For example,
#include <stdio.h>
int main()
{
int x = 10; // using printf()
printf("Value of x is: %d", x);
return 0;
}
3. Print a Character value
The %c format specifier is used to print character variable
value using the printf() function.

#include <stdio.h>
int main()
{ // using printf()
char gender = 'M';
printf("John's Gender is: %c", gender);
return 0;
}
4. Print a Float and a Double value

In the code example below, we have used


the printf() function to print values of
a float and double variable.

For float value we use the %f format specifier and


for double value we use the %lf format specifier.

#include <stdio.h>int main()


{
// using printf()
float num1 = 15.50;
double num2 = 15556522.0978678;
printf("Value of num1 is: %f \n", num1);
printf("Value of num2 is: %lf", num2);
return 0;
}
5. Print multiple outputs

We can use a single printf() function to display values of multiple


variables.

#include <stdio.h>
int main()
{ // using printf() for multiple outputs
int day = 20;
int month = 11;
int year = 2021;
printf("The date is: %d-%d-%d", day, month, year);
return 0;
}
2. The scanf() function
When we want to take input from the user, we use the scanf() function
and store the input value into a variable.

scanf() Code Examples


Let's start with a simple example.
1. Input Integer value
If we have to take an integer value input from the user, we have to
define an integer variable and then use the scanf() function.

#include <stdio.h>int main() { // using scanf()


int user_input;
printf("Please enter a number: ");
scanf("%d", &user_input);
printf("You entered: %d", user_input);
return 0;
}
2. Input Float value
Just like integer value, we can take input for any different datatype.
Let's see an example for float type value.
#include <stdio.h>
int main() {
// using scanf()
float user_input;
printf("Please enter a decimal number: ");
scanf("%f", &user_input);
printf("You entered: %f", user_input);
return 0;}

We have used the %f format specifier and defined


a float type variable. Try doing the same for taking
a double type value as user input. The format specifier
for double is %lf.
3. Input Character value
Let's see how we can take a simple character input
from user.

#include <stdio.h>
int main() {
// using scanf()
char gender;
printf("Please enter your gender (M, F or O): ");
scanf("%c", &gender);
printf("Your gender: %c", gender);
return 0;}
4. Take Multiple Inputs from User
In the below code example, we are taking multiple inputs from the user and
saving them into different variables.

#include <stdio.h>
int main()
{ // using scanf() for multiple inputs char gender;
int age;
printf("Enter your age and then gender(M, F or O): ");
scanf("%d %c", &age, &gender);
printf("You entered: %d and %c", age, gender);
return 0;}
Difference
The main difference between these two functions is that scanf() stops
reading characters when between scanf()
it encounters and
a space, butgets()
gets() reads
space as a character too.
If you enter a name as Study Tonight using scanf() it will only read
and store Study and will leave the part of the string after space.
But gets() function will read it completely.
Let's see the scanf() function in action:

#include <stdio.h>
int main() {
char n1[50], n2[50];
printf("Please enter n1: ");
scanf("%s", n1);
printf("You entered: %s", n1);
return 0;
}
Now let's see the gets() function in action:

#include <stdio.h>
int main() {
char n1[50], n2[50];
printf("Please enter n1: ");
gets(n1);
printf("You entered: %s", n1);
return 0;
}
C Conditional Statement: IF, IF Else
and Nested IF Else with Example
What is a Conditional Statement in C?
Conditional Statements in C programming are used to make decisions
based on the conditions. Conditional statements execute sequentially when
there is no condition around the statements. If you put some condition for a
block of statements, the execution flow may change based on the result
evaluated by the condition. This process is called decision making in ‘C.’
In ‘C’ programming conditional statements are possible with the help of the
following two constructs:
1. If statement
2. If-else statement
It is also called as branching as a program decides which statement to execute
based on the result of the evaluated condition.
If statement

It is one of the powerful conditional statement. If statement is responsible for


modifying the flow of execution of a program. If statement is always used with a
condition. The condition is evaluated first before executing any statement inside the
body of If. The syntax for if statement is as follows:
if (condition)
instruction;
The condition evaluates to either true or false. True is always a non-zero value, and
false is a value that contains zero. Instructions can be a single instruction or a code
block enclosed by curly braces { }.
Following program illustrates the use of if construct in ‘C’ programming:
#include<stdio.h>
int main()
{
int num1=1;
int num2=2;
if(num1<num2) //test-condition
{
printf("num1 is smaller than num2");
}
return 0;
}
Output:
num1 is smaller than num2
The above program illustrates the use of if construct to check equality of two numbers.
•In the above program, we have initialized two variables with num1, num2 with value
as 1, 2 respectively.
•Then, we have used if with a test-expression to check which number is the smallest
and which number is the largest. We have used a relational expression in if construct.
Since the value of num1 is smaller than num2, the condition will evaluate to true.
•Thus it will print the statement inside the block of If. After that, the control will go
outside of the block and program will be terminated with a successful result.
Relational Operators

C has six relational operators that can be used to formulate a Boolean


expression for making a decision and testing conditions, which returns true or
false :
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to
The If-Else statement
The if-else is statement is an extended version of If. The general form of if-else is as
follows:
if (test-expression)
{
True block of statements
}
Else
{
False block of statements
}
Statements;
n this type of a construct, if the value of test-expression is true, then the true block of
statements will be executed. If the value of test-expression if false, then the false block of
statements will be executed. In any case, after the execution, the control will be
automatically transferred to the statements appearing outside the block of If.
We will initialize a variable with some value and write a program to determine if the
value is less than ten or greater than ten.
Let’s start.
#include<stdio.h>
int main()
{
int num=19;
if(num<10)
{
printf("The value is less than 10");
}
else
{
printf("The value is greater than 10");
}
return 0;
}
Loops in C: For, While, Do While looping
Statements

What is Loop in C?
Looping Statements in C execute the sequence of statements many times
until the stated condition becomes false. A loop in C consists of two parts,
a body of a loop and a control statement. The control statement is a
combination of some conditions that direct the body of the loop to
execute until the specified condition becomes false. The purpose of the C
loop is to repeat the same code a number of times.
While Loop in C

A while loop is the most straightforward looping structure. While loop syntax in C
programming language is as follows:
Syntax of While Loop in C:

while (condition) {statements;}

It is an entry-controlled loop. In while loop, a condition is evaluated before processing


a body of the loop. If a condition is true then and only then the body of a loop is
executed. After the body of a loop is executed then control again goes back at the
beginning, and the condition is checked if it is true, the same process is executed until
the condition becomes false. Once the condition becomes false, the control goes out of
the loop.
Following program illustrates while loop in C programming
example:

#include<stdio.h>
#include<conio.h>
int main()
{
int num=1; //initializing the variable
while(num<=10) //while loop with condition
{
printf("%d\n",num);
num++; //incrementing operation
}
return 0;
}
Do-While loop in C

A do…while loop in C is similar to the while loop except that the condition is
always executed after the body of a loop. It is also called an exit-controlled loop.
Syntax of do while loop in C programming language is as follows:

Syntax of Do-While Loop in C:

do { statements} while (expression);

As we saw in a while loop, the body is executed if and only if the condition is
true. In some cases, we have to execute a body of the loop at least once
even if the condition is false. This type of operation can be achieved by
using a do-while loop.
Below is a do-while loop in C example to print a table of number 2:

#include<stdio.h>
#include<conio.h>
int main()
{
int num=1; //initializing the variable
do //do-while loop
{
printf("%d\n",2*num);
num++; //incrementing operation
}
while(num<=10);
return 0;
}
For loop in C
A for loop is a more efficient loop structure in ‘C’ programming. The
general structure of for loop syntax in C is as follows:
Syntax of For Loop in C:

for (initial value; condition; incrementation or


decrementation ) { statements;}

 The initial value of the for loop is performed only once.


 The condition is a Boolean expression that tests and compares the
counter to a fixed value after each iteration, stopping the for loop
when false is returned.
 The incrementation/decrementation increases (or decreases) the
counter by a set value.
Following program illustrates the for loop in C programming example:
#include<stdio.h>
int main(){
int number;
for(number=1;number<=10;number++) //for loop to print 1-10
numbers
{
printf("%d\n",number); //to print the number
}
return 0;
}
Functions in C Programming

What is a Function in C?

Function in C programming is a reusable block of code that makes a program


easier to understand, test and can be easily modified without changing the calling
program. Functions divide the code and modularize the program for better and
effective results. In short, a larger program is divided into various subprograms
which are called as functions
When you divide a large program into various functions, it becomes
easy to manage each function individually. Whenever an error occurs
in the program, you can easily investigate faulty functions and correct
only those errors. You can easily call and use functions whenever they
are required which automatically leads in saving time and space.
Library Vs. User-defined Functions
Every ‘C’ program has at least one function which is the main function, but a program can
have any number of functions. The main () function in C is a starting point of a program.
In ‘C’ programming, functions are divided into two types:
1.Library functions
2.User-defined functions
The difference between the library and user-defined functions in C is that we do not need to
write a code for a library function. It is already present inside the header file which we
always include at the beginning of a program. You just have to type the name of a function
and use it along with the proper syntax. Printf, scanf are the examples of a library function.
Whereas, a user-defined function is a type of function in which we have to write a body of a
function and call the function whenever we require the function to perform some operation
in our program.
A user-defined function in C is always written by the user, but later it can be a part of ‘C’
library. It is a major advantage of ‘C’ programming.
C programming functions are divided into three activities such as,
1.Function declaration
2.Function definition
3.Function call

Function Declaration
Function declaration means writing a name of a program. It is a
compulsory part for using functions in code. In a function declaration, we
just specify the name of a function that we are going to use in our program
like a variable declaration. We cannot use a function unless it is declared in
a program. A function declaration is also called “Function prototype.”
The function declarations (called prototype) are usually done above the main ()
function and take the general form:
return_data_type function_name (data_type arguments);
 The return_data_type: is the data type of the value function returned back to
the calling statement.
 The function_name: is followed by parentheses
 Arguments names with their data type declarations optionally are placed
inside the parentheses.
Function Definition
Function definition means just writing the body of a function. A body of a function
consists of statements which are going to perform a specific task. A function body
consists of a single or a block of statements. It is also a mandatory part of a function.
int add(int a,int b) //function body
{
int c;
c=a+b;
return c;
}
Function call

A function call means calling a function whenever it is required in a program. Whenever we call a function, it performs an operation for
which it was designed.
#include <stdio.h>
int add(int a, int b); //function declaration
int main()
{
int a=10,b=20;
int c=add(10,20); //function call
printf("Addition:%d\n",c);
getch();
}
int add(int a,int b) //function body
{
int c;
c=a+b;
return c;
}
Output:
Addition:30
Function Arguments

A function’s arguments are used to receive the necessary values by the function call.
They are matched by position; the first argument is passed to the first parameter, the
second to the second parameter and so on.
By default, the arguments are passed by value in which a copy of data is given to the
called function. The actually passed variable will not change.
THANK YOU

You might also like