0% found this document useful (0 votes)
2 views

Copy-C Language TUTION Copy 1

C programming is a general-purpose language developed in 1972, primarily for UNIX operating system development, and is known for its efficiency and versatility. It supports various programming constructs including variables, data types, operators, and storage classes, and is widely used in system programming and software development. Key components include the use of compilers and interpreters, a defined character set, and rules for naming identifiers and constants.

Uploaded by

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

Copy-C Language TUTION Copy 1

C programming is a general-purpose language developed in 1972, primarily for UNIX operating system development, and is known for its efficiency and versatility. It supports various programming constructs including variables, data types, operators, and storage classes, and is widely used in system programming and software development. Key components include the use of compilers and interpreters, a defined character set, and rules for naming identifiers and constants.

Uploaded by

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

C PROGRAMMING LANGUAGE

C programming is a general-purpose, procedural, imperative computer


programming language developed in 1972 by Dennis M. Ritchie at the
Bell Telephone Laboratories to develop the UNIX operating system. C is
the most widely used computer language.
. I will list down some of the key advantages of learning C Programming:
1. Easy to learn
2. Structured language
3. It produces efficient programs
4. It can handle low-level activities
5. It can be compiled on a variety of computer platforms
 C was invented to write an operating system called UNIX.
 C is a successor of B language which was introduced around the early 1970s.
 The language was formalized in 1988 by the American National Standard
Institute (ANSI).
 The UNIX OS was totally written in C.
 Today C is the most widely used and popular System Programming Language.
 Most of the state-of-the-art software have been implemented using C.
 Today's most popular Linux OS and RDBMS MySQL have been written in C.
Some examples of the use of C are -
1. Operating Systems
2. Language Compilers
3. Assemblers
4. Text Editors
5. Print Spoolers
6. Network Drivers
7. Modern Programs
8. Databases
9. Language Interpreters
10. Utilities
To Write C-Program you need the following two software
tools available on your computer, (a) Text Editor and (b) The
C Compiler.
Text Editor:
This will be used to type your program. Examples of few a
editors include Windows Notepad, OS Edit command, Brief,
Epsilon, EMACS, and vim or vi.
The files you create with your editor are called the source
files and they contain the program source codes. The source
files for C programs are typically named with the extension
".c".
The C Compiler:
The source code written in source file is the human readable
source for your program. It needs to be "compiled", into
machine language so that your CPU can actually execute the
program as per the instructions given.
The compiler compiles the source codes into final executable
programs. The most frequently used and free available
compiler is the GNU C/C++ compiler, otherwise you can have
compilers either from HP or Solaris if you have the respective
operating systems.
What is Compiler?
A compiler is a computer program that transforms code
written in a high-level programming language into the machine
code. It is a program which translates the human-readable
code to a language a computer processor understands (binary
1 and 0 bits). The computer processes the machine code to
perform the corresponding tasks.
A compiler should comply with the syntax rule of that
programming language in which it is written. However, the
compiler is only a program and cannot fix errors found in that
program. So, if you make a mistake, you need to make changes
in the syntax of your program. Otherwise, it will not compile.
What is Interpreter?
An interpreter is a computer program, which coverts
each high-level program statement into the machine
code. This includes source code, pre-compiled code, and
scripts. Both compiler and interpreters do the same job
which is converting higher level programming language
to machine code. However, a compiler will convert the
code into machine code (create an exe) before program
run. Interpreters convert code into machine code when
the program is run.
C Character Set
As every language contains a set of characters used to
construct words, statements, etc., C language also has a set of
characters which include alphabets, digits, and special
symbols. C language supports a total of 256 characters.
Every C program contains statements. These statements are
constructed using words and these words are constructed
using characters from C character set. C language character
set contains the following set of characters...
 Alphabets
 Digits
 Special Symbols
Alphabets
C language supports all the alphabets from the English language.
Lower and upper case letters together support 52 alphabets.
lower case letters - a to z
UPPER CASE LETTERS - A to Z
Digits
C language supports 10 digits which are used to construct numerical
values in C language.
Digits - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special Symbols
C language supports a rich set of special symbols that include
symbols to perform mathematical operations, to check conditions,
white spaces, backspaces, and other special symbols.
Special Symbols - ~ @ # $ % ^ & * ( ) _ - + = { } [ ] ; : ' " / ? . > , < \ |
tab newline
C Keywords
Keywords are predefined, reserved words in C language
and each of which is associated with specific features.
These words help us to use the functionality of C
language. They have special meaning to the compilers.
There are total 32 keywords in C.
C Identifiers
C identifiers represent the name in the C program, for
example, variables, functions, arrays, structures,
unions, labels, etc. An identifier can be composed of
letters such as uppercase, lowercase letters,
underscore, digits, but the starting letter should be
either an alphabet or an underscore.
We can say that an identifier is a collection of
alphanumeric characters that begins either with an
alphabetical character or an underscore, which are
used to represent various programming elements
such as variables, functions, arrays, structures,
unions, labels, etc.
There are 52 alphabetical characters (uppercase
and lowercase), underscore character, and ten
numerical digits (0-9) that represent the identifiers.
There is a total of 63 alphanumerical characters
that represent the identifiers.
Example of valid identifiers:
 total,
 sum,
 average,
 _m _
 sum_1 etc.
Example of invalid identifiers:
 2sum (starts with a numerical digit)
 int (reserved word)
 char (reserved word)
 m+n (special character, i.e., '+')
RULES FOR NAMING IDENTIFIERS:
1. An identifier can only have alphanumeric characters (a-z ,
A-Z , 0-9) (i.e. letters & digits) and underscore( _ ) symbol.
2. Identifier names must be unique
3. The first character must be an alphabet or underscore.
4. You cannot use a keyword as identifiers.
5. Only the first thirty-one (31) characters are significant.
6. It must not contain white spaces.
7. Identifiers are case-sensitive.
C - Constants and Literals
Constants refer to fixed values that the program
may not alter during its execution. These fixed
values are also called literals.
Constants can be of any of the basic data types
like an integer constant, a floating constant, a
character constant, or a string literal. There are
enumeration constants as well.
Constants are treated just like regular variables
except that their values cannot be modified after
their definition.
Integer Literals:
An integer literal can be a decimal, octal, or hexadecimal
constant. A prefix specifies the base or radix: 0x or 0X for
hexadecimal, 0 for octal, and nothing for decimal.
An integer literal can also have a suffix that is a
combination of U and L, for unsigned and long,
respectively.
Example:
85 - decimal
0213- octal
0x4b- hexadecimal
30 - int
30u- unsigned int
30l - long
Floating-point Literals:
A floating-point literal has an integer part, a decimal
point, a fractional part, and an exponent part.
Here are some examples of floating-point literals −
3.14159

Character Constants:
Character literals are enclosed in single quotes, e.g., 'x'
can be stored in a simple variable of char type.
Example:
'A'
'c'
String Literals:
String literals or constants are enclosed in double quotes "".
A string contains characters that are similar to character
literals: plain characters, escape sequences, and universal
characters.
Example:
"Hello"
"ram" etc.

There are two simple ways in C to define constants −


 Using #define preprocessor:
Example: #define LENGTH 10
 Using const keyword.
VARIABLES
A variable is nothing but a name given to a storage area
that our programs can manipulate. Each variable in C
has a specific type, which determines the size and
layout of the variable's memory; the range of values
that can be stored within that memory; and the set of
operations that can be applied to the variable.
The name of a variable can be composed of letters,
digits, and the underscore character. It must begin with
either a letter or an underscore. Upper and lowercase
letters are distinct because C is case-sensitive. Based on
the basic types explained in the previous chapter, there
will be the following basic variable types −
1. char:Typically a single octet(one byte). It is an
integer type.

2. int:The most natural size of integer for the


machine.

3.float:A single-precision floating point value.

4.double:A double-precision floating point value.

5.void:Represents the absence of type.


SYNTAX OF VARIABLE:
type VariableName ;

A variable definition tells the compiler where and how


much storage to create for the variable.
EXAMPLES:
int i, j, k;
char ch;
float f, salary;
double d;
Variables can be initialized (assigned an initial value) in their
declaration:
type variable_name = value;
Example:
int x=5;
float y= 2.5;
STORAGE CLASS IN C
Every variable in C programming has two properties:
type and storage class.
Type refers to the data type of a variable. And, storage
class determines the scope, visibility and lifetime of a
variable.
There are 4 types of storage class:
 automatic
 external
 static
 register
Local Variable(Automatic):
The variables declared inside a block are automatic or
local variables. The local variables exist only inside the
block in which it is declared.
Example:
int main()
{
int n1;
}
void func()
{
int n2;
}
Global Variable(External)
Variables that are declared outside of all functions are known as external or
global variables. They are accessible from any function inside the program.
Example:
#include <stdio.h>
void display();
int n = 5;
int main()
{
++n;
display();
return 0;
}
void display()
{
++n;
printf("n = %d", n);
}
REGISTER:
The register storage class is used to define
local variables that should be stored in a
register instead of RAM. This means that the
variable has a maximum size equal to the
register size.
Example:
{
register int miles;
}
STATIC:
A variable declared as static once initialized, exists till the end
of the program. If a static variable is declared inside a
function, it remains into existence till the end of the program
and not get destroyed as the function exists (as in auto). If a
static variable is declared outside all the functions in a
program, it can be used only in the program in which it is
declared and is not visible to other program files(as in
extern).
Example:
static int count = 5;
DATA TYPES IN C
DATA TYPE specifies the type of a Variable or function.The type
of a variable determines how much space it occupies in storage
and how the bit pattern stored is interpreted.
C language supports 2 different type of data types:
1. Primary data types:
These are fundamental data types in C namely integer(int),
floating point(float), character(char) and void.
2. Derived data types:
Derived data types are nothing but primary datatypes but a
little twisted or grouped together like array, stucture, union and
pointer.
*Data type determines the type of data a variable will hold. If a
variable x is declared as int. it means x can hold only integer
values
Integer type:
Integers are used to store whole numbers.
Floating point type
Floating types are used to store real numbers.
Character type
Character types are used to store characters value.
void type
void type means no value. This is usually used to specify
the type of functions which returns nothing.
NOTE:We can use the sizeof() operator to check the size
of a variable.
E.g:
#include<studio.h>
Void main()
{
Printf( "Char %lu", sizeof(char));
getch();
}
OPERATORS IN C
An operator is a symbol that tells the compiler to
perform specific mathematical or logical
functions. C language is rich in built-in operators
and provides the following types of operators −
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Misc Operators
1. ARITHMETIC OPERATOR
2.Relational Operators
Assume variable A holds 10 and variable B holds 20 then
3.Logical Operators
Assume variable A holds 1 and variable B holds 0, then −
4.Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation.
Assume A = 60 and B = 13 in binary format, they will be as
follows−
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~A = 1100 0011
5.Assignment Operators
6.Misc Operators ↦ sizeof & ternary
EXPRESSIONS
An expression is a formula in which operands are linked
to each other by the use of operators to compute a
value. An operand can be a function reference, a
variable, an array element or a constant.
Let's see an example:
a-b;
In the above expression, minus character (-) is an
operator, and a, and b are the two operands.
Arithmetic Expressions
An arithmetic expression is an expression that
consists of operands and arithmetic operators. An
arithmetic expression computes a value of type int,
float or double.
E.g: 6*2/ (2+1 * 2/3 + 6) + 8 * (8/4)
Relational Expressions
A relational expression is an expression used to compare two operands.
It is a condition which is used to decide whether the action should be taken or
not.
E.g: a>=9 , x%2 = = 0
#include <stdio.h>
int main()
{

int x=4;
if(x%2==0)
{
printf("The number x is even");
}
else
printf("The number x is not even");
return 0;
}
Logical Expressions
A logical expression is an expression that computes either a zero or
non-zero value.
It is a complex test condition to take a decision.
#include <stdio.h>
int main()
{
int x = 4;
int y = 10;
if ( (x <10) && (y>5))
{
printf("Condition is true");
}
else
printf("Condition is false");
return 0;
}
Conditional Expressions
A conditional expression is an expression that returns 1 if the condition is true otherwise 0.
A conditional operator is also known as a ternary operator.
The Syntax of Conditional operator:
exp1 ? exp2 : exp3
#include<stdio.h>
#include<string.h>
int main()
{
int age = 25;
char status;
status = (age>22) ? 'M': 'U';
if(status == 'M')
printf("Married");
else
printf("Unmarried");
return 0;
}
C - Header Files
A header file is a file with extension .h which contains C
function declarations and macro definitions to be shared
between several source files. There are two types of header
files: the files that the programmer writes and the files that
comes with your compiler.
You request to use a header file in your program by including
it with the C preprocessing directive #include, like you have
seen inclusion of stdio.h header file, which comes along with
your compiler.
SYNTAX:
#include <file> :This form is used for system header files.
#include "file" :This form is used for header files of your own
program. It searches for a file named 'file' in the directory
containing the current file.
Library Files
Library is the place where the actual functionality is
implemented i.e. they contain function body.
Example : Math.h is a header file which includes the
prototype for function calls like sqrt(), pow() etc,
whereas libm.lib, libmmd.lib, libmmd.dll are some of
the math libraries. In simple terms a header file is like a
visiting card and libraries are like a real person, so we
use visiting card(Header file) to reach to the actual
person(Library).
PreProcessor Directives
Preprocessors are programs that process our source code before
compilation.Preprocessor programs provide preprocessors
directives which tell the compiler to preprocess the source code
before compiling. All of these preprocessor directives begin with a
‘#’ (hash) symbol. The ‘#’ symbol indicates that, whatever
statement starts with #, is going to the preprocessor program, and
preprocessor program will execute this statement.
 #define
Substitutes a preprocessor macro.A macro is a code snippet that
is replaced by some value of the code of macro. Any macro is
mostly described and defined by its #define directive.

 #include
Inserts a particular header from another file.The #include
preprocessor directive is used to paste code of given file into
current file. It is used include system-defined and user-defined
header files. If included file is not found, compiler renders error.

Preprocessors Examples:
#define MAX_ARRAY_LENGTH 20: This directive tells the CPP to
replace instances of MAX_ARRAY_LENGTH with 20.
#include <stdio.h>:These directives tell the CPP to get
stdio.h from System Libraries and add the text to the
current source file.

EXAMPLE:
#include <stdio.h>
#include <conio.h>
#define PI 3.1415
Void main()
{
printf("%f",PI);
getch();
}
EXAMPLE:WAP IN C TO DEFINE A MACRO Area() that will compute
the area of rectangle?
Ans:
#include <stdio.h>
// macro with parameter
#define AREA(l, b) (l * b)
int main()
{
int l1 = 10, l2 = 5, area;

area = AREA(l1, l2);

printf("Area of rectangle is: %d", area);

return 0;
}
COMMENT IN C LANGUAGE
A comment starts with a slash asterisk /* and ends with a
asterisk slash */ and can be anywhere in your program.
Comments can span several lines within your C program.
Comments are typically added directly above the related C
source code.
SYNTAX:
The syntax for a comment is:
/* comment goes here */
OR
/*
* comment goes here
*/
Q: WAP IN C TO CHECK TO ENTER A NUMBER AND CHECK WETHER THE NO IS POPOSITIVE OR NEGATIVE NO?
ANS:

/* Description: A program to check whether the input


* integer number is positive or negative.
* Written by: R .S. Jha
*/
#include <stdio.h>
#include<conio.h>
void main()
{
clrscr();
int num;
printf("Enter a number: \n");
scanf("%d", &num);
if (num > 0)
printf("%d is a positive number \n", num);
else if (num < 0)
printf("%d is a negative number \n", num);
else
printf("0 is neither positive nor negative");
Newline Character(\n)
A newline is a character used to represent the end of a line
of text and the beginning of a new line. In programming
languages, such as C, Java, and Perl, the newline character
is represented as a '\n' escape sequence.
ASCII VALUE
ASCII, stands for American Standard Code for
Information Interchange. It's a 7-bit character code
where every single bit represents a unique character.
All characters whether alphabet, digit or special
character have ASCII value. Input character from the user
will determine if it’s Alphabet, Number or Special
character.
ASCII value ranges-
For capital alphabets 65 – 90
For small alphabets 97 – 122
For digits 48 – 57
All other cases are Special Characters.
Q:Program to display ASCII value of a character entered by user?
Ans:
#include <stdio.h>
#include <conio.h>
Void main()
{
char ch;
printf("Enter any character:");
scanf("%c", &ch);
/* Using the format specifiers we can get the ASCII code
* of a character. When we use %d format specifier for a
* char variable then it displays the ASCII value of a char
*/
printf("ASCII value of character %c is: %d", ch, ch);
getch();
}
Q: Write a c program without using main() function ?
Ans:
#include<stdio.h>
#include<conio.h>
#define start main
void start()
{
printf("Hello");
getch();
}
Q: WAP IN C TO SWAP TWO NUMBERS?
ANS:
#include<stdio.h>
#include<conio.h>
void main()
{
int x = 10, y = 15, temp;
temp = x;
x = y;
y = temp;
printf("x = %d and y = %d", x, y);
getch();
}
Q: WAP IN C TO SWAP TWO NUMBERS WITHOUT USING THIRD
VARIABLE?
ANS:
#include<stdio.h>
int main()
{
int a=10, b=20;
printf("Before swap a=%d b=%d",a,b);
a=a+b; /*a=30 (10+20)*/
b=a-b; /*b=10 (30-20)*/
a=a-b; /*a=20 (30-10)*/
printf("\nAfter swap a=%d b=%d",a,b);
return 0;
}
MODULE ||
DECISION MAKING STATEMENTS
Decision making statements in programming languages decides the
direction of flow of program execution. Decision making statements
available in C or C++ are:
1. if statement
2. if..else statements
3. nested if statements
4. if-else-if ladder
5. switch statements
6. Jump Statements:
a. break
b. continue
c. goto
d. return
if STATEMENT
if statement is the most simple decision making statement. It is used to
decide whether a certain statement or block of statements will be
executed or not i.e if a certain condition is true then a block of
statement is executed otherwise not.
Syntax:
if(condition)
{
/* Statements to execute if
condition is true */
}
Here, condition after evaluation will be either true or false. C if
statement accepts boolean values – if the value is true then it will
execute the block of statements below it otherwise not.
Flowchart
Q: WAP IN C to illustrate If statement
ANS:
#include <stdio.h>
#include<conio.h>
void main() {
int i = 10;

if (i > 15)
{
printf("10 is less than 15");
}

printf("I am Not in if");


getch();
}
if-else in C
The if statement alone tells us that if a condition is true it will execute a block
of statements and if the condition is false it won’t. But what if we want to do
something else if the condition is false. Here comes the C else statement. We
can use the else statement with if statement to execute a block of code when
the condition is false.
Syntax:
if (condition)
{
/* Executes this block if
condition is true */
}
else
{
/* Executes this block if
condition is false */
}
Q: C program to illustrate If-else statement
#include <stdio.h>
#include<conio.h>
void main()
{
clrscr();
int i = 20;
if (i < 15)
printf("i is smaller than 15");
else
printf("i is greater than 15");

getch();
}
nested-if statement in C
A nested if in C is an if statement that is the target of another if
statement. Nested if statements means an if statement inside another
if statement. Yes, both C and C++ allows us to nested if statements
within if statements, i.e, we can place an if statement inside another if
statement.
Syntax:
if (condition1)
{
/*Executes when condition1 is true*/
if (condition2)
{
/* Executes when condition2 is true*/
}
}
Q: C program to illustrate nested-if statement
#include <stdio.h>
#include<conio.h>
void main()
{
clrscr();
int i = 10;
if (i == 10)
{
if (i < 15)
printf("i is smaller than 15\n");
if (i < 12)
printf("i is smaller than 12 too\n");
else
printf("i is greater than 15");
}
getch();
}
if-else-if ladder in C
Here, a user can decide among multiple options. The C if statements are
executed from the top down. As soon as one of the conditions controlling
the if is true, the statement associated with that if is executed, and the
rest of the C else-if ladder is bypassed. If none of the conditions are true,
then the final else statement will be executed.
Syntax:
if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;
Q: C program to illustrate nested-if statement?
#include <stdio.h>
#include<conio.h>
void main() {
clrscr();
int i = 20;
if (i == 10)
printf("i is 10");
else if (i == 15)
printf("i is 15");
else if (i == 20)
printf("i is 20");
else
printf("i is not present");
getch();
}
SWITCH STATEMENT
Switch statement in C tests the value of a variable and
compares it with multiple cases. Once the case match is
found, a block of statements associated with that particular
case is executed.
Each case in a block of a switch has a different
name/number which is referred to as an identifier. The
value provided by the user is compared with all the cases
inside the switch block until the match is found.
If a case match is NOT found, then the default statement is
executed, and the control goes out of the switch block.
Syntax:
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......

default:
code to be executed if all cases are not matched;
}
#include<stdio.h>
#include<conio.h>
int main(){
clrscr();
Int number=100;
switch(number){
case 10:
printf("number is equals to 10");
break;
case 50:
printf("number is equal to 50");
break;
case 100:
printf("number is equal to 100");
break;
default:
printf("number is not equal to 10, 50 or 100");
}
getch();
}
JUMP STATEMENTS
break statement
The break statement is used to terminate the loop or statement in
which it present. That is it terminates the loop or switch statement
and transfers execution to the statement immediately following the
loop or switch.
continue statement
The continue statement is also used inside loop. When compiler finds
the continue statement inside a loop, compiler will skip all the
followling statements in the loop and resume the loop.
Goto Statement
The goto statement is a jump statement which jumps from one point
to another point within a function.
Example of goto statement
#include<stdio.h>
#include<conio.h>
void main()
{
Clrscr();
printf("\nStatement 1.");
printf("\nStatement 2.");
printf("\nStatement 3.");
goto last;
printf("\nStatement 4.");
printf("\nStatement 5.");
last:
printf("\nEnd of Program.");
getch();
}
return Statement
The return statement returns the flow of the execution to the
function from where it is called. This statement does not
mandatorily need any conditional statements. As soon as the
statement is executed, the flow of the program stops immediately
and return the control from where it was called. The return
statement may or may not return anything for a void function, but
for a non-void function, a return value is must be returned.
Example of return statement:
#include <stdio.h>
int SUM(int a, int b)
{
int s1 = a + b;
return s1;
}
int main()
{
int num1 = 10;
int num2 = 10;
int sum_of = SUM(num1, num2);
printf("The sum is %d", sum_of);
return 0;
}
Loops in C
• A Loop executes the sequence of statements many times until the
stated condition becomes false. A loop 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 loop is to repeat the same code a number of times.
• Types of Loops in C:
• 1. Entry controlled loop

• 2. Exit controlled loop

• In an entry controlled loop, a condition is checked before


executing the body of a loop. It is also called as a pre-checking
loop.

• In an exit controlled loop, a condition is checked after executing


the body of a loop. It is also called as a post-checking loop.
• TYPES OF LOOP :
• 1. The while loop

• 2. The do-while loop

• 3. The for loop

• While Loop: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.
• Q: WAP in C to print numbers from 1 to 10 ?
Ans:
#include<stdio.h>
#include<conio.h>
int main()
{ clrscr();
int num=1; //initializing the variable
while(num<=10) //while loop with condition
{
printf("%d\n",num);
num++; //incrementing operation
}
getch();
}
Do-While loop
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:

do {
statements
} while (expression);
Q:Wap in C to print the table of 2?
Ans:
#include<stdio.h>
#include<conio.h>
int main()
{ Clrscr();
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
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.
SYNTAX:
for (initial value; condition; incrementation or
decrementation )
{
statements;
}
Q: WAP in C to find the factorial of a number ?
Ans:
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int i,fact=1,number;
printf("Enter a number: ");
scanf("%d",&number);
for(i=1;i<=number;i++)
{
fact=fact*i;
}
printf("Factorial of %d is: %d",number,fact);
getch();
}
Q: WAP in C to check wether the entered chracter is Vowel or consonant ?
Soln:
include <stdio.h>

#include<conio.h>

int main()

clrscr();

char c;

int lowercase_vowel, uppercase_vowel;

printf("Enter an alphabet: ");

scanf("%c", &c);

// evaluates to 1 if variable c is a lowercase vowel

lowercase_vowel = (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');

// evaluates to 1 if variable c is a uppercase vowel

uppercase_vowel = (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U');

// evaluates to 1 (true) if c is a vowel

if (lowercase_vowel || uppercase_vowel)

printf("%c is a vowel.", c);

else

printf("%c is a consonant.", c);

getch();

}
Q:WAP IN C TO FIND THE LARGEST NUMBER AMONG 3 NUMBERS ?
Soln:
#include <stdio.h>
#include<conio.h>
int main()
{
clrscr();
int n1, n2, n3;
printf("Enter three different numbers: ");
scanf("%d %d %d", &n1, &n2, &n3);

// if n1 is greater than both n2 and n3, n1 is the largest


if (n1 >= n2 && n1 >= n3)
printf("%d is the largest number.", n1);

// if n2 is greater than both n1 and n3, n2 is the largest


if (n2 >= n1 && n2 >= n3)
printf("%d is the largest number.", n2);

// if n3 is greater than both n1 and n2, n3 is the largest


if (n3 >= n1 && n3 >= n2)
printf("%d is the largest number.", n3);

getch();
}
Q:WAP in C to check wether a year is leap year or not ?
#include <stdio.h>

int main() {

int year;

printf("Enter a year: ");

scanf("%d", &year);

// leap year if perfectly visible by 400

if (year % 400 == 0) {

printf("%d is a leap year.", year);

// not a leap year if visible by 100

// but not divisible by 400

else if (year % 100 == 0) {

printf("%d is not a leap year.", year);

// leap year if not divisible by 100

// but divisible by 4

else if (year % 4 == 0) {

printf("%d is a leap year.", year);

// all other years are not leap year

else {

printf("%d is not a leap year.", year);

}
Nesting of for loop
Q:wap in c to print the following pattern:

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Ans:
# include<stdio.h>
#include<conio.h>
Void main()
{
clrscr();
for (int i=1; i<=5; i++)
{
for (int j=1; j<=i; j++)
{
printf(j + " ");
}
printf(“\n”);
}
getch();
}
Example of continue statement
Q:WAP in C to print value from 1 to 10 except 6 ?
Ans:
#include <stdio.h>
#include<conio.h>
int main()
{
clrscr();
for (int i = 1; i <= 10; i++)
{
if (i == 6)
continue;
else
// otherwise print the value of i
printf("%d ", i);
}

return 0;
}
Q:WAP in C to print the following pattern:
*
**
***
****
*****
Ans:
#include <stdio.h>
#include<conio.h>
void main()
{
clrscr();
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; ++i) {
for (j = 1; j <= i; ++j) {
printf("* ");
}
printf("\n");
}
getch();
}
Q:WAP in C to print the following pattern:
12345
1234
123
12
1
Soln:
#include <stdio.h>
int main() {
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = rows; i >= 1; --i) {
for (j = 1; j <= i; ++j) {
printf("%d ", j);
}
printf("\n");
}
return 0;
}
Q: WAP in C to check wther the enterdnnumber is Prime number or not ?
Soln:A prime number is a positive integer that is divisible only by 1 and itself. For example: 2, 3, 5, 7, 11, 13, 17 etc.

#include <stdio.h>
int main() {
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);

for (i = 2; i <= n / 2; ++i) {

// condition for non-prime


if (n % i == 0) {
flag = 1;
break;
}
}

if (n == 1) {
printf("1 is neither prime nor composite.");
}
else {
if (flag == 0)
printf("%d is a prime number.", n);
else
printf("%d is not a prime number.", n);
}

return 0;
}
Q:WAP in C to check wether a no is PALINDROME no or not?
Ans:An integer is a palindrome if the reverse of that number is equal to the original number
#include <stdio.h>
int main() {
int n, reversedN = 0, remainder, originalN;
printf("Enter an integer: ");
scanf("%d", &n);
originalN = n;

/*reversed integer is stored in reversedN*/

while (n != 0) {
remainder = n % 10;
reversedN = reversedN * 10 + remainder;
n = n/10;
}

/*palindrome if orignalN and reversedN are equal*/

if (originalN == reversedN)
printf("%d is a palindrome.", originalN);
else
printf("%d is not a palindrome.", originalN);

return 0;
}
Q: WAP in C to find the factorial of a no?
Ans:
#include<stdio.h>
#include<conio.h>
Void main()
{
clrscr();
int num;
int fact=1;
Printf(“ Enter the number \n”);
Scanf(“%d”, &num);
for(int i=num; i>0 ; i- -)
{
fact= fact*i;
}
Printf(“Factorial of %d = %d”, num,fact);
getch();
}
Q: WAP IN C TO CHECK WETHER A NO IS ARMSTRONG NO NOT ?
Ans:A no is armstrong no if the sum of cubes of each digit is equal to the number itself. For
example, 153 is an Armstrong number.

#include <stdio.h>
int main()
{
int num, originalNum, remainder, result = 0;
printf("Enter a three-digit integer: ");
scanf("%d", &num);
originalNum = num;

while (originalNum != 0) {
/*remainder contains the last digit*/
remainder = originalNum % 10;

result += remainder * remainder * remainder;

/*removing last digit from the orignal number*/


originalNum /= 10;
}

if (result == num)
printf("%d is an Armstrong number.", num);
else
printf("%d is not an Armstrong number.", num);

return 0;
}
Q:WAP in C to print FIBONACCI Series ?
Ans:The Fibonacci sequence is a sequence where the next term is the sum of the
previous two terms. The first two terms of the Fibonacci sequence are 0 followed by 1.
The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21

#include<stdio.h>
int main()
{
int n1=0,n2=1,n3,i,number;
printf("Enter the number of elements:");
scanf("%d",&number);
printf("\n%d %d",n1,n2); /*printing 0 and 1*/
for(i=2;i<number;++i) /*loop starts from 2 because 0 and 1 are already printed*/
{
n3=n1+n2;
printf(" %d",n3);
n1=n2;
n2=n3;
}
return 0;
}

You might also like