First Program of C

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 69

1:

C :-
C is a programming language developed at AT & T’s Bell Laboratories of
USA in 1972. It was designed and written by a man named Dennis
Ritchie. In the late seventies C began to replace the more familiar
languages of that time like PL/I, ALGOL, etc. No one pushed C. It wasn’t
made the ‘official’ Bell Labs language.

First program of c -:

#include<stdio.h>

int main(){

printf("Hello, World! \n");

return 0;

Output-:

C Character Set -:
The C character set consists of upper and
lowercase alphabets, digits, special
characters and white spaces.
2:
Constants, Variables and Keywords -:
1. Variables: A variable in simple terms is a storage place which has
some memory allocated to it. Example: Height, age, etc.
2. Keywords: Keywords are specific reserved words in C each of which
has a specific feature associated with it. There are a total of 32
keywords in C: auto, break, case, char, const, continue, default, do,
double, else, enum, extern, float, for, goto, if, int, long, register, return,
short, signed, sizeof, static, struct, switch, typedef, union, unsigned,
void, volatile, while
3. Constants: Constants are the fixed values that never change during
the execution of a program. Example, 111, 1234.
ex-
#include<stdio.h>
void main( ){
int p,n;
float r,si;

printf ("Enter values of p,n,r");

scanf ("%d %d %f",&p,&n,&r);

si=p*n*r/100;

printf("%f",si);

Output-:
3:
Data types -:
Mainly data types are categories into:

1. Primary data type or functional data types:

(i). Void: As the name suggests, it holds no value and is generally used
for specifying the type of function or what it returns. If the function has
a void type, it means that the function will not return any value.

(ii). Int: Used to denote an integer type.

(iii). Char: Used to denote a character type.

(iv). Float/Double: Used to denote a floating point type.

ex-

int age;

char letter;

float height, width;

2. Derived data types:

(i). Arrays: Arrays are sequences of data items having homogeneous


values. They have adjacent memory locations to store values.

(ii). References: Function pointers allow referencing functions with a


particular signature.

(iii). Pointers: These are powerful C features which are used to access
the memory and deal with their addresses.
4:
Data type Format specifier -:
Integer - %d or %I
Long - %ld
Float - %f
Double - %lf
Character %c
String - %s

ex-

#include <stdio.h>

int main(){

int a = 4000; // positive integer data type


float b = 5.2324; // float data type
char c = 'Z'; // char data type
long d = 41657; // long positive integer data type
double i = 4.1234567890; // double float data type
printf(“%d\n%f\n%c\n%ld\n%lf\n”,a,b,c,d,i);
}
Output-:
5:
Type Conversion -:
The type conversion process in C is basically converting one type of
data type to other to perform some operation.

1. Implicit Type Conversion: This type of conversion is usually


performed by the compiler when necessary without any commands by
the user. Thus it is also called "Automatic Type Conversion".

int a = 20;

double b = 20.5;

a + b;

Here, first operand is int type and other is of type double. So, as per
rule 2, the variable a will be converted to double. Therefore, the final
answer is double a + b = 40.500000.

2. Explicit Type Conversion: Explicit type conversion rules out the use
of compiler for converting one data type to another instead the user
explicitly defines within the program the datatype of the operands in
the expression. Example:

double da = 4.5;

double db = 4.6;

double dc = 4.9;

int result = (int)da + (int)db + (int)dc;

printf("result = %d", result);


6:
Operators precedence and associativity -:
1. Operators precedence: Operator precedence determines which
operator is performed first in an expression with more than one
operators with different precedence. For example: 10 + 20 * 30 is
calculated as 10 + (20 * 30) and not as (10 + 20) * 30

2. Operators Associativity: Operators Associativity is used when two


operators of same precedence appear in an expression. Associativity
can be either Left to Right or Right to Left. For example: 100 / 10 * 10 is
treated as (100 / 10) * 10

C Programming Operators -:
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:

(i). Arithmetic Operators: An arithmetic operator performs


mathematical operations such as addition, subtraction, multiplication,
division etc on numerical values (constants and variables).

#include <stdio.h>

int main(){

int a = 9,b = 4, c;

c = a+b;

printf("a+b = %d \n",c);

c = a-b;
7:
printf("a-b = %d \n",c);

c = a*b;

printf("a*b = %d \n",c);

c = a/b;

printf("a/b = %d \n",c);

c = a%b;

printf("Remainder when a divided by b = %d \n",c);

return 0;

Output-:

2. Increment and Decrement Operators: C programming has two


operators increment ++ and decrement -- to change the value of an
operand (constant or variable) by 1.

#include <stdio.h>

int main(){
8:
int a = 10, b = 100;

float c = 10.5, d = 100.5;

printf("++a = %d \n", ++a);

printf("--b = %d \n", --b);

printf("++c = %f \n", ++c);

printf("--d = %f \n", --d);

return 0;

Output-:

3. Relational Operators: A relational operator checks the relationship


between two operands.

Operator Meaning of Operator Example


== Equal to 5 == 3 is evaluated to 0
> Greater than 5 > 3 is evaluated to 1
< Less than 5 < 3 is evaluated to 0
!= Not equal to 5 != 3 is evaluated to 1
>= Greater than or equal to 5 >= 3 is evaluated to 1
<= Less than or equal to 5 <= 3 is evaluated to 0
9:
#include <stdio.h>
int main(){
int a = 5, b = 5, c = 10;
printf("%d == %d is %d \n", a, b, a == b);
printf("%d == %d is %d \n", a, c, a == c);
printf("%d > %d is %d \n", a, b, a > b);
printf("%d > %d is %d \n", a, c, a > c);
printf("%d < %d is %d \n", a, b, a < b);
printf("%d < %d is %d \n", a, c, a < c);
printf("%d != %d is %d \n", a, b, a != b);
printf("%d != %d is %d \n", a, c, a != c);
printf("%d >= %d is %d \n", a, b, a >= b);
printf("%d >= %d is %d \n", a, c, a >= c);
printf("%d <= %d is %d \n", a, b, a <= b);
printf("%d <= %d is %d \n", a, c, a <= c);
return 0;
}
Output-:
10:
4. Logical Operators: An expression containing logical operator returns
either 0 or 1 depending upon whether expression results true or false.
Logical operators are commonly used in decision making in C
programming.

Operator Meaning Example


Logical AND. True only if all If c = 5 and d = 2 then, expression
&&
operands are true ((c==5) && (d>5)) equals to 0.
Logical OR. True only if If c = 5 and d = 2 then, expression
||
either one operand is true ((c==5) || (d>5)) equals to 1.
Logical NOT. True only if If c = 5 then, expression !(c==5)
!
the operand is 0 equals to 0.

#include <stdio.h>
int main(){
int a = 5, b = 5, c = 10, result;
result = (a == b) && (c > b);
printf("(a == b) && (c > b) is %d \n", result);
result = (a == b) && (c < b);
printf("(a == b) && (c < b) is %d \n", result);
result = (a == b) || (c < b);
printf("(a == b) || (c < b) is %d \n", result);
result = (a != b) || (c < b);
printf("(a != b) || (c < b) is %d \n", result);
result = !(a != b);
printf("!(a == b) is %d \n", result);
result = !(a == b);
printf("!(a == b) is %d \n", result);
return 0;
}
11:
Output-:

5. Conditional Operators: The conditional operators ? and : are


sometimes called ternary operators since they take three arguments. In
fact, they form a kind of foreshortened if-then-else. Their general form
is, expression 1 ? expression 2 : expression 3
int x, y ;

scanf ( "%d", &x ) ;

y=(x>5?3:4);

ASCII code -:
A character variable holds ASCII value (an integer number between 0
and 127) rather than that character itself in C programming. That value
is known as ASCII value

A–Z 65 – 90

a–z 97 – 122

0–9 48 – 57
12:
Control Statements -:

1. if Statement: An if statement consists of a Boolean expression


followed by one or more statements.

#include<stdio.h>

int main (){

int a =10;

if (a <20){

printf("a is less than 20\n");

printf("value of a is : %d\n",a);

return 0;

}
13:
Output-:

2. if...else: An if statement can be followed by an optional else


statement, which executes when the Boolean expression is false

#include<stdio.h>

int main (){

int a =100;

if (a <20){

printf("a is less than 20\n");

else{

printf("a is not less than 20\n");

printf("value of a is : %d\n",a);

return 0;

Output-:
14:
3. Switch Statement: As switch statement allows a variable to be tested
for equality against a list of values. Each value is called a case, and the
variable being switched on is checked for each switch case.

#include<stdio.h>

int main (){

char grade ='B';

switch(grade){

case'A':

printf("Excellent!\n");

break;

case'B':

printf("Well done\n");

break;

case'C':

printf("You passed\n");

break;

case'D':

printf("Better try again\n");

break;
15:
default:

printf("Invalid grade\n");

printf("Your grade is %c\n",grade );

return 0;

Output-:

4. While Loop: A while loop in C programming repeatedly executes a


target statement as long as a given condition is true.

#include<stdio.h>

int main (){

int a =10;

while(a <20){

printf("%d ",a);

a++;

return 0;
16:
}

Output-:

5. For Loop: A for loop is a repetition control structure that allows you
to efficiently write a loop that needs to execute a specific number of
times.

#include<stdio.h>

int main (){

for(int a =10;a <20;a =a +1){

printf("%d ",a);

return 0;

Output-:

6. Do...while: Loop Unlike for and while loops, which test the loop
condition at the top of the loop, the do...while loop in C programming
checks its condition at the bottom of the loop. A do...while loop is
similar to a while loop, except the fact that it is guaranteed to execute
at least one time.
17:
#include<stdio.h>

int main (){

int a =10;

do{

printf("%d ",a);

a =a +1;

while(a <20);

return 0;

Output-:

7. Break Statement: The break statement in C programming has the


following two usages:

 When a break statement is encountered inside a loop, the loop is


immediately terminated and the program control resumes at the next
statement following the loop.

 It can be used to terminate a case in the switch statement. If you are


using nested loops, the break statement will stop the execution of the
innermost loop and start executing the next line of code after the block.
18:
#include<stdio.h>

int main (){

int a =10;

while(a <20){

printf("%d ",a);

a++;

if(a >15){

break;

return 0;

Output-:

8. Continue Statement: The continue statement in C programming


works somewhat like the break statement. Instead of forcing
termination, it forces the next iteration of the loop to take place,
skipping any code in between. For the for loop, continue statement
causes the conditional test and increment portions of the loop to
execute. For the while and do...while loops, continue statement causes
the program control to pass to the conditional tests.
19:
#include<stdio.h>

int main (){

int a =10;

do{

if(a ==15){

a =a +1;

continue;

printf("value of a: %d\n",a);

a++;

while(a <20);

return 0;

Output-:

9. Goto Statement: A goto statement in C programming provides an


unconditional jump from the ‘goto’ to a labeled statement in the same
function.
20:
NOTE: Use of goto statement is highly discouraged in any programming
language because it makes difficult to trace the control flow of a
program, making the program hard to understand and hard to modify.
Any program that uses a goto can be rewritten to avoid them.

#include<stdio.h>

int main (){

int a =10;

LOOP: do{

if(a ==15){

a =a +1;

goto LOOP;

printf("value of a: %d\n",a);

a++;

while(a <20);

return 0;

Output-:
21:
Function -:
A function is a self-contained block of statements that perform a
coherent task of some kind. Every C program can be thought of as a
collection of these functions. A function definition in C programming
consists of a function header and a function body. Here are all the parts
of a function:

Return Type: A function may return a value. There turn_type is the


data type of the value the function returns. Some functions perform the
desired operations without returning a value. In this case, the
return_type is the keyword void.

Function Name: This is the actual name of the function. The function
name and the parameter list together constitute the function signature.

Parameters: A parameter is like a place holder. When a function is


invoked, you pass a value to the parameter. This value is referred to as
actual parameter or argument. The parameter list refers to the type,
order, and number of the parameters of a function. Parameters are
optional; that is, a function may contain no parameters.

Function Body: The function body contains a collection of statements


that define what the function does.

#include<stdio.h>

void message();

void main( ){
22:
message( ) ;

printf ( "\nCry, and you stop the monotony!" ) ;

void message( ){

printf ( "\nSmile, and the world smiles with you..." ) ;

Output-:

Call by Value and Call by Reference -:


There are two ways to pass arguments/parameters to function calls -
call by value and call by reference. The major difference between call
by value and call by reference is that in call by value a copy of actual
arguments is passed to respective formal arguments. While, in call by
reference the location (address) of actual arguments is passed to
formal arguments, hence any change made to formal arguments will
also reflect in actual arguments

Call by value:

#include <stdio.h>

void swap(int x, int y);


23:
int main (){

int a = 100;

int b = 200;

printf("Before swap, value of a : %d\n", a );

printf("Before swap, value of b : %d\n", b );

swap(a, b);

printf("After swap, value of a : %d\n", a );

printf("After swap, value of b : %d\n", b );

return 0;

void swap(int x, int y){

int t;

t = y;

y = x;

x = t;
}

Output-:
24:

Call by reference:

#include<stdio.h>

void swap(int*x,int*y);

int main (){

int a =100;

int b =200;

printf("Before swap, value of a : %d\n",a );

printf("Before swap, value of b : %d\n",b );

swap(&a,&b);

printf("After swap, value of a : %d\n",a );

printf("After swap, value of b : %d\n",b );

return 0;

void swap(int *x, int *y){

int t;

t = *y;
25:
*y = *x;

*x = t;
}

Output-:

Local and Global Variables -:


Variables that are declared inside a function or block are called local
variables. They can be used only by statements that are inside that
function or block of code. Local variables are not known to functions
outside their own. The following example shows how local variables are
used. Here all the variables a, b, and c are local to main() function.

#include<stdio.h>

int main (){

int a,b;

int c;

a =10;

b =20;
26:
c =a +b;

printf ("value of a = %d, b = %d and c = %d\n",a,b,c);

return 0;

Output-:

Global variables are defined outside a function, usually on top of the


program. Global variables hold their values throughout the lifetime of
your program and they can be accessed inside any of the functions
defined for the program. A global variable can be accessed by any
function. That is, a global variable is available for use throughout your
entire program after its declaration. The following program shows how
global variables are used in a program.

#include<stdio.h>

int c:

int main (){

int a,b;

a =10;

b =20;

c =a +b;

printf ("value of a = %d, b = %d and c = %d\n",a,b,c);


27:
return 0;

Output-:

Array -:
An array is a collection of similar elements. These similar elements
could be all ints, or all floats, or all chars, etc. Usually, the array of
characters is called a ‘string’, whereas an array of ints or floats is called
simply an array.

#include<stdio.h>
void main( ){

int avg, sum = 0 ;

int i ;

int marks[5];

for ( i = 0 ; i <= 4 ; i++ ){

printf ("\nEnter marks ");

scanf ( "%d", &marks[i] );

}
28:
for ( i = 0 ; i <= 4 ; i++ )

sum = sum + marks[i];

avg = sum / 5;

printf ("\nAverage marks = %d", avg);

Output-:

Pointers -:

 Pointers in C language is a variable that stores/points the address


of another variable. A Pointer in C is used to allocate memory
dynamically i.e. at run time. The pointer variable might be
belonging to any of the data type such as int, float, char, double,
short etc.

 Pointer Syntax : data_type *var_name; Example : int *p; char *p;


 Where, * is used to denote that “p” is pointer variable and not a
normal variable.

#include <stdio.h>
29:
int main(){
int *ptr, q;
q = 50;
ptr = &q;
printf("%d", *ptr);
return 0;
}
Output-:

Array Of The Pointers -:


The way there can be an array of ints or an array of floats, similarly
there can be an array of pointers. Since a pointer variable always
contains an address, an array of pointers would be nothing but a
collection of addresses. The addresses present in the array of pointers
can be addresses of isolated variables or addresses of array elements or
any other addresses. All rules that apply to an ordinary array apply to
the array of pointers as well. I think a program would clarify the
concept.

#include<stdio.h>

void main( ){

int *arr[4] ;

int i = 31, j = 5, k = 19, l = 71, m ;

arr[0] = &i ;
30:
arr[1] = &j ;

arr[2] = &k ;

arr[3] = &l ;

for ( m = 0 ; m <= 3 ; m++ )

printf ( "%d ", * ( arr[m] ) ) ;

Output-:

NULL Pointers -:
It is always a good practice to assign a NULL value to a pointer variable
in case you do not have an exact address to be assigned. This is done at
the time of variable declaration. A pointer that is assigned NULL is
called a null pointer. The NULL pointer is a constant with a value of zero
defined in several standard libraries. Consider the following program:

#include <stdio.h>

int main (){

int *ptr = NULL;

printf("The value of ptr is : %x\n", ptr );

return 0;
31:
}

Output-:

Strings -:
The way a group of integers can be stored in an integer array, similarly
a group of characters can be stored in a character array. Character
arrays are many a time also called strings. A string constant is a one-
dimensional array of characters terminated by a null ( ‘\0’ ).

ex-

#include<stdio.h>

char name[ ] = { 'H', 'A', 'E', 'S', 'L', 'E', 'R', '\0' } ;

void main( ){

char name[ ] = "Klinsman" ;

int i = 0 ;

while ( i <= 7 ){

printf ( "%c", name[i] ) ;

i++ ;

Output-:
32:

Standard Library String Functions -:

 strcat - concatenate two strings


 strchr - string scanning operation
 strcmp - compare two strings
 strcpy - copy a string
 strlen - get string length
 strncat - concatenate one string with part of another
 strncmp - compare parts of two strings
 strncpy - copy part of a string
 strrchr - string scanning operation

User defined data types -:

1. Structures: Structure is a user-defined data type in C language which


allows us to combine data of different types together. Structure helps
to construct a complex data type which is more meaningful. It is
somewhat similar to an Array, but an array holds data of similar type
only. But structure on the other hand, can store data of any type, which
is practical more useful.

For example: If I have to write a program to store Student information,


which will have Student's name, age, branch, permanent address,
father's name etc, which included string values, integer values etc, how
can I use arrays for this problem, I will require something which can
hold data of different types together.

#include<stdio.h>
#include<string.h>
33:
struct Student{
char name[25];
int age;
char branch[10];
char gender;
};
int main(){
struct Student s1;
s1.age = 18;
strcpy(s1.name, "Viraaj");
printf("Name of Student 1: %s\n", s1.name);
printf("Age of Student 1: %d\n", s1.age);
return 0;
}
Output-:

2. Union: A union is a special data type available in C that allows to


store different data types in the same memory location. You can define
a union with many members, but only one member can contain a value
at any given time. Unions provide an efficient way of using the same
memory location for multiple purpose
ex-
#include<stdio.h>
#include<string.h>
union Data{
int i;
float f;
char str[20];
};
34:
int main(){
union Data data;
printf("Memory size occupied by data : %d\n",sizeof(data));
return 0;
}
Output-:

Typedef -:
The C programming language provides a keyword called typedef, which
you can use to give a type, a new name. Following is an example to
define a term BYTE for one-byte numbers: typede funsigned char BYTE;

Typedef vs #define -:
#define is a C-directive which is also used to define the aliases for
various data types similar to typedef but with the following differences:
typedef is limited to giving symbolic names to types only, where as
#define can be used to define alias for values as well, e.g., you can
define 1 as ONE, etc.
typedef interpretation is performed by the compiler where as #define
statements are processed by the preprocessor.
#include<stdio.h>
#defineTRUE 1
#defineFALSE 0
int main(){
printf("Value of TRUE : %d\n",TRUE);
printf("Value of FALSE : %d\n",FALSE);
return 0;
}
35:
Output-:

Text Files and Binary Files -:


All the programs that we wrote so far worked on text files. Some of
them would not work correctly on binary files. A text file contains only
textual information like alphabets, digits and special symbols. In
actuality the ASCII codes of these characters are stored in text files. A
good example of a text file is any C program, say PR1.C. As against this,
a binary file is merely a collection of bytes. This collection might be a
compiled version of a C program (say PR1.EXE), or music data stored in
a wave file or a picture stored in a graphic file. A very easy way to find
out whether a file is a text file or a binary file is to open that file in
Turbo C/C++. If on opening the file you can make out what is displayed
then it is a text file, otherwise it is a binary file.

Macros with Arguments -:


The macros that we have used so far are called simple macros. Macros
can have arguments, just as functions can. Here is an example that
illustrates this fact.

#include<stdio.h>

#define AREA(x) ( 3.14 * x * x )

void main( ){
36:
float r1 = 6.25, r2 = 2.5, a ;

a = AREA ( r1 ) ;

printf ( "\nArea of circle = %f", a ) ;

a = AREA ( r2 ) ;

printf ( "\nArea of circle = %f", a ) ;

Output-:

Some Shortcuts keys of c -:


S.No. Shortcuts keys Action
1 F1 For Help
2. F2 Save
3. F3 Open
4. F4 Go to cursor
5. F5 Zoom
6. F6 Next
7. F7 Trace into
8. F8 Step over
9. F9 Make
10. F10 Menu
11. Alt+X Quit
37:
12. Alt+Bksp Undo
13. Shift+Alt+Bksp Redo
14. Shift+Del Cut
15. Ctrl+Ins Copy
16. Shift+Ins Paste
17. Ctrl+Del Clear
18. Ctrl+L Search again
19. Alt+F7 Previous error
20. Alt+F8 Next error
Ctrl+F9 'or'
21. Run
Alt+R+Enter
22. Ctrl+F2 Program reset
23. Alt+F9 Compile
24. Alt+F4 Inspect
25. Ctrl+F4 Evaluate/Modify
26. Ctrl+F3 Call stack
27. Ctrl+F8 Toggle breakpoint
28. Ctrl+F5 Size/Move
29. Alt+F3 Close
30. Alt+F5 User screen
31. Alt+0 List all
32. Shift+F1 Index
33. Ctrl+F1 Topic search
34. Alt+F1 Previous topic
35. Ctrl+F7 Add watch
Toggle screen mode(Full Screen /
36. Alt+Enter
Window)*
38:

PROGRAMMINGS

1. C Program to Check Whether a Number is Even or Odd -:


#include <stdio.h>

int main() {

int num;

printf("Enter an integer: ");

scanf("%d", &num);

if(num % 2 == 0)

printf("%d is even.", num);

else

printf("%d is odd.", num);

return 0;

Output –
39:
2. C Program to Count the Number of Digits -:

#include <stdio.h>

int main() {

long long n;

int count = 0;

printf("Enter an integer: ");

scanf("%lld", &n);

while (n != 0) {

n /= 10;

++count;

printf("Number of digits: %d", count);

Output –

3. C Program to count vowels, consonants etc -:

#include <stdio.h>

int main(){
40:
char line[150];

int i, vowels, consonants, digits, spaces;

vowels = consonants = digits = spaces = 0;

printf("Enter a line of string: ");

scanf("%[^\n]", line);

for(i=0; line[i]!='\0'; ++i){

if(line[i]=='a' || line[i]=='e' || line[i]=='i' ||line[i]=='o' ||

line[i]=='u' || line[i]=='A' || line[i]=='E' || line[i]=='I' ||

line[i]=='O' || line[i]=='U') {

++vowels;

else if((line[i]>='a'&& line[i]<='z') || (line[i]>='A'&&

line[i]<='Z')) {

++consonants;

else if(line[i]>='0' && line[i]<='9') {

++digits;

else if (line[i]==' ') {


41:
++spaces;

printf("Vowels: %d",vowels);

printf("\nConsonants: %d",consonants);

printf("\nDigits: %d",digits);

printf("\nWhite spaces: %d", spaces);

return 0;

Output –

4. C Program to Find the Largest Number Among Three

Numbers -:

#include <stdio.h>

int main() {
42:
double n1, n2, n3;

printf("Enter three numbers: ");

scanf("%lf %lf %lf", &n1, &n2, &n3);

if (n1 >= n2 && n1 >= n3)

printf("%.2lf is the largest number.", n1);

else if (n2 >= n1 && n2 >= n3)

printf("%.2lf is the largest number.", n2);

else

printf("%.2lf is the largest number.", n3);

return 0;

Output –

5. C Program to Check Leap Year -:

#include <stdio.h>

int main() {

int year;
43:
printf("Enter a year: ");

scanf("%d", &year);

if (year % 4 == 0) {

if (year % 100 == 0) {

if (year % 400 == 0)

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

else

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

else

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

else

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

return 0;

Output –
44:
6. C Program for Factorial of a Number-:

#include <stdio.h>

int main() {

int n, i;

unsigned long long fact = 1;

printf("Enter an integer: ");

scanf("%d", &n);

if (n < 0)

printf("Error! Factorial of a negative number doesn't

exist.");

else {

for (i = 1; i <= n; ++i) {

fact *= i;

printf("Factorial of %d = %llu", n, fact);

return 0;

}
45:
Output –

7. C Program for Fibonacci Series up to n terms -:

#include <stdio.h>

int main() {

int i, n, t1 = 0, t2 = 1, nextTerm;

printf("Enter the number of terms: ");

scanf("%d", &n);

printf("Fibonacci Series: ");

for (i = 1; i <= n; ++i) {

printf("%d, ", t1);

nextTerm = t1 + t2;

t1 = t2;

t2 = nextTerm;

return 0;

Output –
46:

8. C Program for LCM of two numbers -:

#include <stdio.h>

int main() {

int n1, n2, min;

printf("Enter two positive integers: ");

scanf("%d %d", &n1, &n2);

min = (n1 > n2) ? n1 : n2;

while (1) {

if (min % n1 == 0 && min % n2 == 0) {

printf("The LCM of %d and %d is %d.", n1, n2,

min);

break;

++min;

return 0;

}
47:
Output –

9. C Program to Check Palindrome -:

#include <stdio.h>

int main() {

int n, reversedN = 0, remainder, originalN;

printf("Enter an integer: ");

scanf("%d", &n);

originalN = n;

while (n != 0) {

remainder = n % 10;

reversedN = reversedN * 10 + remainder;

n /= 10;

if (originalN == reversedN)

printf("%d is a palindrome.", originalN);

else

printf("%d is not a palindrome.", originalN);


48:
return 0;

Output –

10. C Program to Check Prime Number -:

#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) {

if (n % i == 0) {

flag = 1;

break;

if (n == 1) {

printf("1 is neither prime nor composite.");


49:
}

else {

if (flag == 0)

printf("%d is a prime number.", n);

else

printf("%d is not a prime number.", n);

return 0;

Output –

11. C Program to Check Armstrong Number -:

#include <stdio.h>

int main() {

int num, originalNum, remainder, result = 0;

printf("Enter a three-digit integer: ");

scanf("%d", &num);

originalNum = num;
50:
while (originalNum != 0) {

remainder = originalNum % 10;

result += remainder * remainder * remainder;

originalNum /= 10;

if (result == num)

printf("%d is an Armstrong number.", num);

else

printf("%d is not an Armstrong number.", num);

return 0;

Output –

12. C Programs to print triangles -:

#include <stdio.h>

int main() {

int i, j, rows;

printf("Enter number of rows: ");


51:
scanf("%d", &rows);

for (i = 1; i <= rows; ++i) {

for (j = 1; j <= i; ++j) {

printf("* ");

printf("\n");

return 0;

Output –

#include<stdio.h>

int main() {

int i, j, rows;

printf("Enter number of rows: ");


52:
scanf("%d", &rows);

for (i=rows; i>=1; --i) {

for (j=1; j<=i; ++j) {

printf("* ");

printf("\n");

return 0;

Output –

#include <stdio.h>

int main() {

int i, space, rows, k = 0;

printf("Enter number of rows: ");


53:
scanf("%d", &rows);

for (i = 1; i <= rows; ++i, k = 0) {

for (space = 1; space <= rows - i; ++space) {

printf(" ");

while (k != 2 * i - 1) {

printf("* ");

++k;

printf("\n");

return 0;

Output –
54:
#include <stdio.h>

int main() {

int rows, i, j, space;

printf("Enter number of rows: ");

scanf("%d", &rows);

for (i = rows; i >= 1; --i) {

for (space = 0; space < rows - i; ++space)

printf(" ");

for (j = i; j <= 2 * i - 1; ++j)

printf("* ");

for (j = 0; j < i - 1; ++j)

printf("* ");

printf("\n");

return 0;

}
55:
Output –

13. C Program to Print Pascal's triangle -:


#include <stdio.h>

int main() {

int rows, coef=1, space, i, j;

printf("Enter number of rows: ");

scanf("%d", &rows);

for (i=0; i<rows; i++) {

for (space=1; space<=rows-i; space++)

printf(" ");

for (j=0; j<=i; j++) {

if (j==0||i==0)

coef=1;

else
56:
coef=coef*(i-j+1)/j;

printf("%4d", coef);

printf("\n");

return 0;

Output –

14. C Program to Display Largest Element of an array -:

#include <stdio.h>

int main(){

int i, n;

float arr[100];
57:
printf("Enter total number of elements(1 to 100): ");

scanf("%d", &n);

printf("\n");

for(i = 0; i < n; ++i) {

printf("Enter Number %d: ", i+1);

scanf("%f", &arr[i]);

for(i = 1; i < n; ++i) {

if(arr[0] < arr[i])

arr[0] = arr[i];

printf("Largest element = %.2f", arr[0]);

return 0;

Output –
58:
15. C Program for Reverse a sentence using recursion -:

#include <stdio.h>

void reverseSentence();

int main() {

printf("Enter a sentence: ");

reverseSentence();

return 0;

void reverseSentence() {

char c;

scanf("%c", &c);

if( c != '\n') {

reverseSentence();

printf("%c",c);

Output –
59:
16. C Program to Find Transpose of a Matrix -:

#include <stdio.h>

int main() {

int a[10][10], transpose[10][10], r, c, i, j;

printf("Enter rows and columns of matrix: ");

scanf("%d %d", &r, &c);

printf("Enter elements of matrix:\n");

for(i=0; i<r; ++i)

for(j=0; j<c; ++j) {

scanf("%d", &a[i][j]);

for(i=0; i<r; ++i)

for(j=0; j<c; ++j) {

transpose[j][i] = a[i][j];

printf("Transpose of Matrix:\n");

for(i=0; i<c; ++i)

for(j=0; j<r; ++j) {


60:
printf("%d ",transpose[i][j]);

if(j==r-1)

printf("\n");

return 0;

Output –

17. C Program to Copy String Manually Without Using


strcpy() -:

#include <stdio.h>

int main() {

char s1[100], s2[100], i;


61:
printf("Enter string s1: ");

scanf("%s",s1);

for(i = 0; s1[i] != '\0'; ++i) {

s2[i] = s1[i];

s2[i] = '\0';

printf("String s2: %s", s2);

return 0;

Output –

18. C Program to swap two numbers without third variable -:

#include<stdio.h>

int main() {

int a=10, b=20;

printf("Before swap a=%d b=%d",a,b);

a=a+b;
62:
b=a-b;

a=a-b;

printf("\nAfter swap a=%d b=%d",a,b);

return 0;

Output –

19. C Program without main() function -:


#include<stdio.h>
#define start main
void start() {
printf("Hello");
}

Output –

20. C Program to Calculate the Power of a Number -:

#include <stdio.h>

int main() {

int base, exp;


63:
long long result = 1;

printf("Enter a base number: ");

scanf("%d", &base);

printf("Enter an exponent: ");

scanf("%d", &exp);

while (exp != 0) {

result *= base;

--exp;

printf("Answer = %lld", result);

return 0;

Output-

21. C Program to Make a Simple Calculator Using switch...case


#include <stdio.h>

int main() {
64:
char operator;

double first, second;

printf("Enter an operator (+, -, *,): ");

scanf("%c", &operator);

printf("Enter two operands: ");

scanf("%lf %lf", &first, &second);

switch (operator) {

case '+':

printf("%.1lf + %.1lf = %.1lf", first, second, first +

second);

break;

case '-':

printf("%.1lf - %.1lf = %.1lf", first, second, first –

second);

break;

case '*':

printf("%.1lf * %.1lf = %.1lf", first, second, first *

second);

break;
65:
case '/':

printf("%.1lf / %.1lf = %.1lf", first, second, first /

second);

break;

default:

printf("Error! operator is not correct");

return 0;

Output-

22. C Program for converting lowercase to uppercase and vise


versa -:
#include <stdio.h>

#include <string.h>

int main() {

char s[100];
66:
int i;

printf("\nEnter a string : ");

gets(s);

for (i = 0; s[i]!='\0'; i++) {

if(s[i] >= 'a' && s[i] <= 'z') {

s[i] = s[i] - 32;

printf("\nString in Upper Case = %s", s);

for (i = 0; s[i]!='\0'; i++) {

if(s[i] >= 'A' && s[i] <= 'Z') {

s[i] = s[i] + 32;

printf("\nString in Lower Case = %s", s);

return 0;

}
67:
Output-

23. C Program to convert days into years weeks and days -:


#include <stdio.h>

#define DAYSINWEEK 7

void main() {

int ndays, year, week, days;

printf("Enter the number of days");

scanf("%d",&ndays);

year = ndays/365;

week = (ndays % 365)/DAYSINWEEK;

days = (ndays%365) % DAYSINWEEK;

printf ("%d is equivalent to %d years, %d weeks and %d daysn",

ndays, year, week, days);

Output-
68:
24. C Program of Binary Search -:
#include <stdio.h>

int main() {

int c, first, last, middle, n, search, array[100];

printf("Enter number of elements\n");

scanf("%d",&n);

printf("Enter %d integers\n", n);

for (c = 0; c < n; c++)

scanf("%d",&array[c]);

printf("Enter value to find\n");

scanf("%d", &search);

first = 0;

last = n - 1;

middle = (first+last)/2;

while (first <= last) {

if (array[middle] < search)

first = middle + 1;

else if (array[middle] == search) {

printf("%d found at location %d.\n", search,


69:
middle+1);

break;

else

last = middle - 1;

middle = (first + last)/2;

if (first > last)

printf("Not found! %d isn't present in the list.\n",

search);

return 0;

Output-

You might also like