c prog
c prog
Basics, Introduction
History of C language
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.
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?
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.
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:
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
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
#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.
#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
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:
#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:
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:
What is a Function in C?
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