0% found this document useful (0 votes)
18 views76 pages

C Programming Basics and Examples

The document contains a collection of C programming examples, including basic syntax, data types, operators, and common errors. It showcases various programs for printing messages, handling different data types, and demonstrating arithmetic, relational, logical, and bitwise operations. Additionally, it highlights common syntax and runtime errors encountered in C programming.

Uploaded by

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

C Programming Basics and Examples

The document contains a collection of C programming examples, including basic syntax, data types, operators, and common errors. It showcases various programs for printing messages, handling different data types, and demonstrating arithmetic, relational, logical, and bitwise operations. Additionally, it highlights common syntax and runtime errors encountered in C programming.

Uploaded by

zc8q6jh4jw
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

[Link]

net/projects/embarcadero-devcpp/

1. //A simple C program to Print Hello world


#include<stdio.h>
void main()
{
/* This will print
Hello World! */
printf("Hello, World! \n our first program");
}
2. //A simple C program to Print Student details
#include<stdio.h>
void main()
{
/* This will print
student details*/
printf("Name:krishna \n Department:AIML\n");
printf("College:CBIT \n Address:Hyderabad");
}
C Programs for Primary Data Types
[Link] for char
// C program to take input from user and print for char
#include <stdio.h>
#include <limits.h>

int main()
{
char ch;

printf("Enter a character: ");


scanf(" %c", &ch); // notice space before %c to consume newline

printf("You entered: %c \n", ch);


printf("ASCII value: %d \n", ch);
printf("Size of data type: %zu \n", sizeof(ch));
printf("Address of variable: %d \n", &ch);
printf("Next variable address: %d \n", (&ch+1));
printf("CHAR_MIN: %d, CHAR_MAX: %d \n", CHAR_MIN, CHAR_MAX);

return 0;
}
//%zu → "print an unsigned decimal integer of type size_t".
[Link] for short
// C program to take input from user and print for short
#include <stdio.h>
#include <limits.h>

int main()
{
short num;

printf("Enter a short integer: ");


scanf("%hd", &num);

printf("You entered: %hd \n", num);


printf("Size of data type: %zu \n", sizeof(num));
printf("Address of variable: %d \n", &num);
printf("Next variable address: %d \n", (&num+1));
printf("SHRT_MIN: %d, SHRT_MAX: %d \n", SHRT_MIN, SHRT_MAX);
return 0;
}
[Link] for int
// C program to take input from user and print for int
#include <stdio.h>
#include <limits.h>

int main()
{
int number;

printf("Enter an integer: ");


scanf("%d", &number);

printf("You entered: %d \n", number);


printf("Size of data type: %zu \n", sizeof(number));
printf("Address of variable: %d \n", &number);
printf("Next variable address: %d \n", (&number+1));
printf("INT_MIN: %d, INT_MAX: %d \n", INT_MIN, INT_MAX);

return 0;
}
[Link] for long
// C program to take input from user and print for long
#include <stdio.h>
#include <limits.h>

int main()
{
long num;

printf("Enter a long integer: ");


scanf("%ld", &num);

printf("You entered: %ld \n", num);


printf("Size of data type: %zu \n", sizeof(num));
printf("Address of variable: %d \n", &num);
printf("Next variable address: %d \n", (&num+1));
printf("LONG_MIN: %ld, LONG_MAX: %ld \n", LONG_MIN, LONG_MAX);

return 0;
}
[Link] for long long
// C program to take input from user and print for long long
#include <stdio.h>
#include <limits.h>

int main()
{
long longnum;

printf("Enter a long long integer: ");


scanf("%lld", &num);
printf("You entered: %lld \n", num);
printf("Size of data type: %zu \n", sizeof(num));
printf("Address of variable: %d \n", &num);
printf("Next variable address: %d \n", (&num+1));
printf("LLONG_MIN: %lld, LLONG_MAX: %lld \n", LLONG_MIN, LLONG_MAX);

return 0;
}
[Link] for float
// C program to take input from user and print for float
#include <stdio.h>
#include <float.h>

int main()
{
float num;

printf("Enter a float value: ");


scanf("%f", &num);

printf("You entered: %f \n", num);


printf("Size of data type: %zu \n", sizeof(num));
printf("Address of variable: %d \n", &num);
printf("Next variable address: %d \n", (&num+1));
printf("FLT_MIN: %e, FLT_MAX: %e \n", FLT_MIN, FLT_MAX);

return 0;
}
[Link] for double
// C program to take input from user and print for double
#include <stdio.h>
#include <float.h>

int main()
{
double num;

printf("Enter a double value: ");


scanf("%lf", &num);

printf("You entered: %lf \n", num);


printf("Size of data type: %zu \n", sizeof(num));
printf("Address of variable: %d \n", &num);
printf("Next variable address: %d \n", (&num+1));
printf("DBL_MIN: %e, DBL_MAX: %e \n", DBL_MIN, DBL_MAX);

return 0;
}
[Link] for long double
// C program to take input from user and print for long double
#include <stdio.h>
#include <float.h>

int main()
{
long double num;

printf("Enter a long double value: ");


scanf("%Lf", &num);

printf("You entered: %Lf \n", num);


printf("Size of data type: %zu \n", sizeof(num));
printf("Address of variable: %d \n", &num);
printf("Next variable address: %d \n", (&num+1));
printf("LDBL_MIN: %Le, LDBL_MAX: %Le \n", LDBL_MIN, LDBL_MAX);

return 0;
}
11.// C program to illustrate syntax error
#include<stdio.h>
void main()
{
int x = 10;
int y = 15;
printf("%d", (x, y)) // semicolon missed
}

Output:
error: expected ';' before '}' token

12.// C program to illustrate run-time error


#include<stdio.h>
void main()
{
int n = 9, div = 0,d=0;
// wrong logic number is divided by 0,
// so this program abnormally terminates
div = n/d;
printf("resut = %d", div);
}

Output:
warning: division by zero [-Wdiv-by-zero] div = n/0;

13.//Program to find modulus – logical error


#include<stdio.h>
int main()
{
int a=10,b=2;
int mod;
mod = a/b; // Logical Error. Correct statement “mod=a%b;”
return 0;
}

Output:
the remainder value is 5

14. //C program to illustrate syntax error_2


#include <stdio.h>
int main(void) {
//closing double quote is missing
printf(“Hello world);
return 0;
}
Output:
Syntax error
prog.c: In function ‘main’:
prog.c:6:9: warning: missing terminating “; character
C:\Users\hp\Documents\C_Programs\sytaxerorr.c [Error] expected ')' before 'world'
15.//C program to illustrate syntax error_3
#include <stio.h>
int main(void){
printf(“Hello world”);
return 0;
}
Output:
Syntax error
prog.c:1:18: fatal error: stio.h: No such file or directory

16.// Missing semicolon


#include <stdio.h>
intmain() {
int x = 10 // ❌ error: missing semicolon
printf("%d\n", x);
return 0;
}
17. //Undeclared variable
#include <stdio.h>
intmain() {
int x = 5;
printf("%d\n", y); // ❌ error: 'y' undeclared
return 0;
}
18. //Mismatched braces
#include <stdio.h>
intmain() {
int a = 10;
if(a > 5) {
printf("Greater\n");
// ❌ error: missing closing brace
return 0;
}
19. //Wrong format specifier, results garbage value
#include <stdio.h>
intmain() {
float pi = 3.14;
printf("%d\n", pi); // ❌ error: using %d for float so garbage value is printed
return 0;
}
20. //Extra comma in function call
#include <stdio.h>
intmain() {
printf("Hello", ); // ❌ error: stray comma
return 0;
}
21.// Assignment inside declaration without type
#include <stdio.h>
intmain() {
x = 10; // ❌ error: 'x' undeclared
printf("%d\n", x);
return 0;
}
22. //Wrong function return type
#include <stdio.h>
main() { // ❌ error in modern C: return type of 'main' defaults to 'int'
printf("Hello\n");
}
23. //Using reserved keyword as variable
#include <stdio.h>
intmain() {
int for = 5; // ❌ error: 'for' is a keyword
printf("%d\n", for);
return 0;
}
24.// Missing double quotes in string
#include <stdio.h>
intmain() {
printf(Hello World\n); // ❌ error: string not in quotes
return 0;
}
25.// Function declared but not defined
#include <stdio.h>
void greet(); // declaration only

int main() {
greet(); // ❌ error: implicit declaration / undefined reference
return 0;
}

26. Arithmetic Operators


Program:
#include <stdio.h>
int main() {
int a = 10, b = 3;
printf("a + b = %d\n", a + b);
printf("a - b = %d\n", a - b);
printf("a * b = %d\n", a * b);
printf("a / b = %d\n", a / b);
printf("a %% b = %d\n", a % b);
return 0;
}
Output:
a + b = 13
a-b=7
a * b = 30
a/b=3
a%b=1
27 Relational Operators
Program:
#include <stdio.h>
int main() {
int x = 5, y = 10;
printf("x == y: %d\n", x == y);
printf("x != y: %d\n", x != y);
printf("x > y : %d\n", x > y);
printf("x < y : %d\n", x < y);
printf("x >= y: %d\n", x >= y);
printf("x <= y: %d\n", x <= y);
return 0;
}
Output:
x == y: 0
x != y: 1
x>y:0
x<y:1
x >= y: 0
x <= y: 1
28. Logical Operators
Program:
#include <stdio.h>
int main() {
int a = 5, b = 10;
printf("(a > 0 && b > 0): %d\n", (a > 0 && b > 0));
printf("(a > 0 || b < 0): %d\n", (a > 0 || b < 0));
printf("!(a > b): %d\n", !(a > b));
return 0;
}
Output:
(a> 0 && b > 0): 1
(a > 0 || b < 0): 1
!(a > b): 1
29. Increment & Decrement Operators
Program:
#include <stdio.h>
int main() {
int a = 5;
printf("a = %d\n", a);
printf("++a = %d\n", ++a); // Pre-increment
printf("a++ = %d\n", a++); // Post-increment
printf("a = %d\n", a);
printf("--a = %d\n", --a); // Pre-decrement
printf("a-- = %d\n", a--); // Post-decrement
printf("a = %d\n", a);
return 0;
}
Output:
a =5
++a = 6
a++ = 6
a =7
--a = 6
a-- = 6
a =5
30. Assignment Operators
Program:
#include <stdio.h>
int main() {
int a = 10;
printf("a = %d\n", a);
a += 5; printf("a += 5: %d\n", a);
a -= 3; printf("a -= 3: %d\n", a);
a *= 2; printf("a *= 2: %d\n", a);
a /= 4; printf("a /= 4: %d\n", a);
a %= 3; printf("a %%= 3: %d\n", a);
return 0;
}
Output:
a = 10
a += 5: 15
a -= 3: 12
a *= 2: 24
a /= 4: 6
a %= 3: 0
31. Bitwise Operators
Program:
#include <stdio.h>
int main() {
int a = 5, b = 3;
printf("a & b = %d\n", a & b); // AND
printf("a | b = %d\n", a | b); // OR
printf("a ^ b = %d\n", a ^ b); // XOR
printf("~a = %d\n", ~a); // NOT
printf("a << 1 = %d\n", a << 1); // Left shift
printf("a >> 1 = %d\n", a >> 1); // Right shift
return 0;
}
Output:
a& b = 1
a|b=7
a^b=6
~a = -6
a << 1 = 10
a >> 1 = 2
32. Conditional (Ternary) Operator
Program:
#include <stdio.h>
intmain() {
int a = 10, b = 20;
int max = (a > b) ? a : b;
printf("Max of %d and %d is %d\n", a, b, max);
return 0;
}
Output:
Max of 10 and 20 is 20
Program 33: Pre-increment Example
Program:
#include <stdio.h>
intmain() {
int a = 5;
int b = ++a;
printf("a = %d, b = %d\n", a, b);
return 0;
}
Output:
a = 6, b = 6
Program 34: Post-increment Example
Program:
#include <stdio.h>
intmain() {
int a = 5;
int b = a++;
printf("a = %d, b = %d\n", a, b);
return 0;
}
Output:
a = 6, b = 5
Program 35: Pre-decrement Example
Program:
#include <stdio.h>
intmain() {
int a = 5;
int b = --a;
printf("a = %d, b = %d\n", a, b);
return 0;
}
Output:
a = 4, b = 4
Program 36: Post-decrement Example
Program:
#include <stdio.h>
intmain() {
int a = 5;
int b = a--;
printf("a = %d, b = %d\n", a, b);
return 0;
}
Output:
a = 4, b = 5
Program 37: Using Pre-increment in an Expression
Program:
#include <stdio.h>
intmain() {
int a = 5, b;
b = 10 + (++a);
printf("a = %d, b = %d\n", a, b);
return 0;
}
Output:
a = 6, b = 16
Program 38: Using Post-increment in an Expression
Program:
#include <stdio.h>
intmain() {
int a = 5, b;
b = 10 + (a++);
printf("a = %d, b = %d\n", a, b);
return 0;
}
Output:
a = 6, b = 15
Program 39: Multiple Pre/Post Increments
Program:
#include <stdio.h>
intmain() {
int a = 5;
int b = ++a + a++;
printf("a = %d, b = %d\n", a, b);
return 0;
}
Output:
a = 7, b = 12
Program 40: Pre-decrement in Expression
Program:
#include <stdio.h>
intmain() {
int a = 10, b;
b = 20 + (--a);
printf("a = %d, b = %d\n", a, b);
return 0;
}
Output:
a = 9, b = 29
Program 41: Post-decrement in Expression
Program:
#include <stdio.h>
intmain() {
int a = 10, b;
b = 20 + (a--);
printf("a = %d, b = %d\n", a, b);
return 0;
}
Output:
a = 9, b = 30
Program 42: Mix of All Increment & Decrement
Program:
#include <stdio.h>
intmain() {
int a = 5, b;
b = ++a + a-- + --a + a++;
printf("a = %d, b = %d\n", a, b);
return 0;
}
Output:
a = 5, b = 22

Program 43: Using printf and scanf


Program:
#include<stdio.h>
intmain() {
int age;
printf("Enter your age: ");
scanf("%d", &age);
printf("Your age is %d\n", age);
return0;
}
Input:
Enter your age:25
Output:
Your age is25
Program 44: Using puts and gets
Program:
#include<stdio.h>
intmain() {
char name[50];
printf("Enter your name: ");
gets(name); // unsafe, use fgets in modern C
puts("Your name is:");
puts(name);
return0;
}
Input:
Enter your name:Krishna
Output:
Your name is:
Krishna

Program 45: Using getchar and putchar


Program:
#include<stdio.h>
intmain() {
char c;
printf("Enter a character: ");
c = getchar();
printf("You entered: ");
putchar(c);
return0;
}
Input:
Enteracharacter: A
Output:
Youentered: A

Program 46: Using fgets and fputs


Program:
#include<stdio.h>
intmain() {
charstr[100];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin); // safer than gets
fputs("You entered: ", stdout);
fputs(str, stdout);
return0;
}
Input:
Enter a string: Hello World
Output:
You entered:HelloWorld

Program 47: Using fprintf and fscanf (File I/O)


Program:
#include<stdio.h>
intmain() {
FILE *fp;
int x, y;

fp = fopen("[Link]", "w");
fprintf(fp, "%d %d", 10, 20);
fclose(fp);

fp = fopen("[Link]", "r");
fscanf(fp, "%d %d", &x, &y);
fclose(fp);

printf("Read values: x = %d, y = %d\n", x, y);


return0;
}
Input (File content written):
10 20
Output (after reading from file):
Readvalues: x = 10, y = 20

48. Arithmetic Operator Precedence


Program:
 #include <stdio.h>
int main() {
int result = 10 + 5 * 2;
printf("Result = %d\n", result);
return 0;
}
Explanation: ‘*’ has higher precedence than ‘+’, so 5*2=10, then 10+10=20.
Output: Result = 20
49. Parentheses Change Precedence
Program:
 #include <stdio.h>
int main() {
int result = (10 + 5) * 2;
printf("Result = %d\n", result);
return 0;
}
Explanation: Parentheses are evaluated first, so (10+5)=15, then 15*2=30.
Output: Result = 30
50. Division and Multiplication (Same Level)
Program:
 #include <stdio.h>
int main() {
int result = 20 / 5 * 2;
printf("Result = %d\n", result);
return 0;
}
Explanation: Division and multiplication have same precedence, evaluated left to right.
(20/5)*2=8.
Output: Result = 8
51. Modulus with Multiplication
Program:
 #include <stdio.h>
int main() {
int result = 5 + 20 % 3 * 2;
printf("Result = %d\n", result);
return 0;
}
Explanation: ‘%’ and ‘*’ same precedence → (20%3)=2, 2*2=4, 5+4=9.
Output: Result = 9
52. Relational and Arithmetic Operators
Program:
 #include <stdio.h>
int main() {
int a = 10, b = 20, c = 5;
int result = a + b > c;
printf("Result = %d\n", result);
return 0;
}
Explanation: Arithmetic + is done before relational > → (10+20)>5 → 30>5 → true(1).
Output: Result = 1
53. Logical AND and OR Precedence
Program:
 #include <stdio.h>
int main() {
int a = 5, b = 10, c = 0;
int result = a > 2 && b < 20 || c != 0;
printf("Result = %d\n", result);
return 0;
}
Explanation: ‘&&’ has higher precedence than ‘||’. (a>2 && b<20)=1, 1||0=1.
Output: Result = 1
54. Assignment with Arithmetic
Program:
 #include <stdio.h>
int main() {
int x = 5;
int y = 10;
int z = x += y * 2;
printf("x = %d, z = %d\n", x, z);
return 0;
}
Explanation: ‘*’ first → y*2=20, then x+=20 → x=25, z=25.
Output: x = 25, z = 25
55. Unary Minus and Multiplication
Program:
 #include <stdio.h>
int main() {
int result = -5 * 2 + 10;
printf("Result = %d\n", result);
return 0;
}
Explanation: Unary minus applies first. (-5*2)+10 = -10+10 = 0.
Output: Result = 0
56. Mixed Increment and Arithmetic
Program:
 #include <stdio.h>
int main() {
int a = 5, b = 3;
int result = ++a * b++;
printf("a = %d, b = %d, result = %d\n", a, b, result);
return 0;
}
Explanation: ‘++a’ increments before use (a=6), ‘b++’ after use. So 6*3=18, b=4.
Output: a = 6, b = 4, result = 18
57. Complex Expression
Program:
 #include <stdio.h>
int main() {
int a = 4, b = 2, c = 3;
int result = a + b * c - ++b / a;
printf("a = %d, b = %d, result = %d\n", a, b, result);
return 0;
}
Explanation: ++b→b=3, b*c=9, b/a=0 (int division), so 4+9-0=13.
Output: a = 4, b = 3, result = 13
58. if Statement
Program:
#include <stdio.h>
intmain() {
intnum;
printf("Enter a number: ");
scanf("%d", &num);

if (num> 0) {
printf("The number is positive.\n");
}
return 0;
}
Input:
5
Output:
The number is positive.
59. if-else Statement
Program:
#include <stdio.h>
intmain() {
int age;
printf("Enter age: ");
scanf("%d", &age);

if (age >= 18) {


printf("You are eligible to vote.\n");
} else {
printf("You are not eligible to vote.\n");
}
return 0;
}
Input:
16
Output:
You are not eligible to vote.
60. else-if Ladder
Program:
#include <stdio.h>
int main() {
int marks;
printf("Enter marks: ");
scanf("%d", &marks);

if (marks >= 90) {


printf("Grade: A\n");
} else if (marks >= 75) {
printf("Grade: B\n");
} else if (marks >= 50) {
printf("Grade: C\n");
} else {
printf("Grade: Fail\n");
}
return 0;
}
Input:
80
Output:
Grade: B
61. nested – IF statement
Program:
#include <stdio.h>
int main() {
intnum;
printf("Enter a number: ");
scanf("%d", &num);

if (num>= 0) {
if (num % 2 == 0) {
printf("The number is positive and even.\n");
} else {
printf("The number is positive and odd.\n");
}
} else {
printf("The number is negative.\n");
}

return 0;
}
Input:
8
Output:
The number is positive and even
Input:
-5
Output:
The number is negative.

62. switch Statement


Program:
#include <stdio.h>
intmain() {
int choice;
printf("1. Add\n2. Subtract\n3. Multiply\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("You chose Addition.\n");
break;
case 2:
printf("You chose Subtraction.\n");
break;
case 3:
printf("You chose Multiplication.\n");
break;
default:
printf("Invalid choice.\n");
}
return 0;
}
Input:
2
Output:
You chose Subtraction.
63. while Loop
Program:
#include <stdio.h>
intmain() {
inti = 1;
while (i<= 5) {
printf("%d ", i);
i++;
}
return 0;
}
Output:
12345
64. for Loop
Program:
#include <stdio.h>
intmain() {
for (inti = 1; i<= 5; i++) {
printf("%d ", i);
}
return 0;
}
Output:
12345
65. do-while Loop
Program:
#include <stdio.h>
intmain() {
inti = 1;
do {
printf("%d ", i);
i++;
} while (i<= 5);
return 0;
}
Output:
12345
66. Goto Statement
Program:
#include <stdio.h>
intmain() {
intnum = 1;
start:
if (num<= 5) {
printf("%d ", num);
num++;
goto start;
}
return 0;
}
Output:
12345
67. break Statement
Program:
#include <stdio.h>
intmain() {
for (inti = 1; i<= 10; i++) {
if (i == 6)
break;
printf("%d ", i);
}
return 0;
}
Output:
12345
68. continue Statement
Program:
#include <stdio.h>
intmain() {
for (inti = 1; i<= 5; i++) {
if (i == 3)
continue;
printf("%d ", i);
}
return 0;
}
Output:
1245
69. Nested Loops
Program:
#include <stdio.h>
intmain() {
for (inti = 1; i<= 3; i++) {
for (int j = 1; j <= 3; j++) {
printf("%d,%d ", i, j);
}
printf("\n");
}
return 0;
}
Output:
1,1 1,2 1,3
2,1 2,2 2,3
3,1 3,2 3,3
70. Rectangle Pattern of Stars
Program Code:
#include <stdio.h>

intmain() {
int rows = 3, cols = 5;

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


for (int j = 1; j <= cols; j++) {
printf("* ");
}
printf("\n");
}
return 0;
}
Sample Output:
*****
*****
*****
71. Right Triangle Pattern
Program Code:
#include <stdio.h>

intmain() {
int n = 5;

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


for (int j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}
return 0;
}
Sample Output:
*
**
***
****
*****
72. Multiplication Table
Program Code:
#include <stdio.h>

intmain() {
int n = 5;

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


for (int j = 1; j <= 10; j++) {
printf("%d x %d = %d\t", i, j, i * j);
}
printf("\n");
}
return 0;
}
Sample Output:
1 x 1 = 1 ... 1 x 10 = 10
2 x 1 = 2 ... 2 x 10 = 20
3 x 1 = 3 ... 3 x 10 = 30
4 x 1 = 4 ... 4 x 10 = 40
5 x 1 = 5 ... 5 x 10 = 50
73. Number Pattern
Program Code:
#include <stdio.h>

intmain() {
int n = 4;

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


for (int j = 1; j <= i; j++) {
printf("%d ", j);
}
printf("\n");
}
return 0;
}
Sample Output:
1
12
123
1234
74. Inverted Triangle Pattern
Program Code:
#include <stdio.h>
intmain() {
int n = 5;

for (inti = n; i>= 1; i--) {


for (int j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}
return 0;
}
Sample Output:
*****
****
***
**
*
75. Nested While Loop Example
Program Code:
#include <stdio.h>

intmain() {
inti = 1;
while (i<= 3) {
int j = 1;
while (j <= 4) {
printf("%d ", j);
j++;
}
printf("\n");
i++;
}
return 0;
}
Sample Output:
1234
1234
1234

[Link]-while loop inside while loop


#include <stdio.h>
int main() {
inti = 1;
while (i<= 3) {
int j = 1;
do {
printf("%d ", j);
j++;
} while (j <= 3);
printf("\n");
i++;
}
return 0;
}
o/p:
123
123
123

[Link]-while loop inside for loop


#include <stdio.h>
int main() {
for (inti = 1; i<= 3; i++) {
int j = 1;
do {
printf("%d ", j);
j++;
} while (j <= 3);
printf("\n");
}
return 0;
}
o/p:
123
123
123

[Link] loop inside for loop

#include <stdio.h>

int main() {
for (inti = 1; i<= 3; i++) {
int j = 1;
while (j <= 3) {
printf("%d ", j);
j++;
}
printf("\n");
}
return 0;
}
o/p:
123
123
123
[Link] loop inside while loop
#include <stdio.h>

int main() {
inti = 1;
while (i<= 3) {
for (int j = 1; j <= 3; j++) {
printf("%d ", j);
}
printf("\n");
i++;
}
return 0;
}

o/p:
123
123
123

[Link] loop inside do-while loop

#include <stdio.h>

int main() {
inti = 1;
do {
for (int j = 1; j <= 3; j++) {
printf("%d ", j);
}
printf("\n");
i++;
} while (i<= 3);
return 0;
}
o/p:
123
123
123

81. Pyramid Pattern


Program Code:
#include <stdio.h>

intmain() {
int n = 5;
for (inti = 1; i<= n; i++) {
for (int space = 1; space <= n - i; space++) {
printf(" ");
}
for (int j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}
return 0;
}
Sample Output:
*
**
***
****
*****
82. Inverted Pyramid Pattern
Program Code:
#include <stdio.h>

intmain() {
int n = 5;
for (inti = n; i>= 1; i--) {
for (int space = 1; space <= n - i; space++) {
printf(" ");
}
for (int j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}
return 0;
}
Sample Output:
*****
****
***
**
*
83. Diamond Pattern
Program Code:
#include <stdio.h>

int main() {
int n = 5;

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


for (int space = 1; space <= n - i; space++) {
printf(" ");
}
for (int j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}

for (inti = n - 1; i>= 1; i--) {


for (int space = 1; space <= n - i; space++) {
printf(" ");
}
for (int j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}
return 0;
}
Sample Output:
*
**
***
****
*****
****
***
**
*
84. Hollow Square Pattern
Program Code:
#include <stdio.h>

intmain() {
int n = 5;
for (inti = 1; i<= n; i++) {
for (int j = 1; j <= n; j++) {
if (i == 1 || i == n || j == 1 || j == n)
printf("* ");
else
printf(" ");
}
printf("\n");
}
return 0;
}
Sample Output:
*****
* *
* *
* *
*****
85. Hollow Pyramid Pattern
Program Code:
#include <stdio.h>

int main() {
int n = 5;
for (inti = 1; i<= n; i++) {
for (int space = 1; space <= n - i; space++) {
printf(" ");
}
for (int j = 1; j <= i; j++) {
if (j == 1 || j == i || i == n)
printf("* ");
else
printf(" ");
}
printf("\n");
}
return 0;
}
Sample Output:
*
**
* *
* *
*****
86. Hollow Diamond Pattern
Program Code:
#include <stdio.h>

int main() {
int n = 5;

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


for (int space = 1; space <= n - i; space++)
printf(" ");
for (int j = 1; j <= i; j++) {
if (j == 1 || j == i)
printf("* ");
else
printf(" ");
}
printf("\n");
}

for (inti = n - 1; i>= 1; i--) {


for (int space = 1; space <= n - i; space++)
printf(" ");
for (int j = 1; j <= i; j++) {
if (j == 1 || j == i)
printf("* ");
else
printf(" ");
}
printf("\n");
}
return 0;
}
Sample Output:
*
**
* *
* *
* *
* *
* *
**
*
87. Right Pascal’s Triangle Pattern
Program Code:
#include <stdio.h>

int main() {
int n = 5;

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


for (int j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}
for (inti = n - 1; i>= 1; i--) {
for (int j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}
return 0;
}
Sample Output:
*
**
***
****
*****
****
***
**
*
88. Left Pascal’s Triangle Pattern
Program Code:
#include <stdio.h>

int main() {
int n = 5;

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


for (int space = 1; space <= n - i; space++) {
printf(" ");
}
for (int j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}
for (inti = n - 1; i>= 1; i--) {
for (int space = 1; space <= n - i; space++) {
printf(" ");
}
for (int j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}
return 0;
}
Sample Output:
*
**
***
****
*****
****
***
**
*
89. Hourglass Pattern
Program Code:
#include <stdio.h>

int main() {
int n = 5;

for (inti = n; i>= 1; i--) {


for (int space = 1; space <= n - i; space++)
printf(" ");
for (int j = 1; j <= i; j++)
printf("* ");
printf("\n");
}

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


for (int space = 1; space <= n - i; space++)
printf(" ");
for (int j = 1; j <= i; j++)
printf("* ");
printf("\n");
}
return 0;
}
Sample Output:
*****
****
***
**
*
**
***
****
*****

90. Factorial of a Number


Program Code:
#include <stdio.h>
int main() {
int n, i;
unsigned long long fact = 1;
printf("Enter a number: ");
scanf("%d", &n);
for(i = 1; i <= n; i++) {
fact *= i;
}
printf("Factorial of %d = %llu\n", n, fact);
return 0;
}
Input / Output Example:
Input: 5
Output: Factorial of 5 = 120
91. Fibonacci Series
Program Code:
#include <stdio.h>
int main() {
int n, t1 = 0, t2 = 1, next;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci Series: ");
for(int i = 1; i <= n; i++) {
printf("%d ", t1);
next = t1 + t2;
t1 = t2;
t2 = next;
}
return 0;
}
Input / Output Example:
Input: 7
Output: 0 1 1 2 3 5 8
92. Prime Number Check
Program Code:
#include <stdio.h>
int main() {
int n, i, flag = 0;
printf("Enter a number: ");
scanf("%d", &n);
for(i = 2; i <= n/2; i++) {
if(n % i == 0) {
flag = 1;
break;
}
}
if(flag == 0 && n > 1)
printf("%d is a prime number.\n", n);
else
printf("%d is not a prime number.\n", n);
return 0;
}
Input / Output Example:
Input: 13
Output: 13 is a prime number.
93. Sum of Natural Numbers
Program Code:
#include <stdio.h>
int main() {
int n, sum = 0;
printf("Enter n: ");
scanf("%d", &n);
for(int i = 1; i <= n; i++)
sum += i;
printf("Sum = %d\n", sum);
return 0;
}
Input / Output Example:
Input: 10
Output: Sum = 55
94. Reverse a Number
Program Code:
#include <stdio.h>
int main() {
int n, rev = 0, rem;
printf("Enter a number: ");
scanf("%d", &n);
while(n != 0) {
rem = n % 10;
rev = rev * 10 + rem;
n /= 10;
}
printf("Reversed number = %d\n", rev);
return 0;
}
Input / Output Example:
Input: 1234
Output: 4321
95. Palindrome Number Check
Program Code:
#include <stdio.h>
int main() {
int n, original, rev = 0, rem;
printf("Enter a number: ");
scanf("%d", &n);
original = n;
while(n != 0) {
rem = n % 10;
rev = rev * 10 + rem;
n /= 10;
}
if(original == rev)
printf("Palindrome Number\n");
else
printf("Not Palindrome\n");
return 0;
}
Input / Output Example:
Input: 121
Output: Palindrome Number
96. Armstrong Number Check
Program Code:
#include <stdio.h>
#include <math.h>
int main() {
int n, original, rem, result = 0;
int count = 0;
printf("Enter a number: ");
scanf("%d", &n);
original = n;

int temp = n;
while(temp != 0) {
temp /= 10;
count++;
}

temp = n;
while(temp != 0) {
rem = temp % 10;
result += pow(rem, count);
temp /= 10;
}

if(result == original)
printf("Armstrong Number\n");
else
printf("Not Armstrong Number\n");
return 0;
}
Input / Output Example:
Input: 153
Output: Armstrong Number
97. Multiplication Table
Program Code:
#include <stdio.h>
int main() {
int n;
printf("Enter a number: ");
scanf("%d", &n);
for(int i = 1; i <= 10; i++)
printf("%d x %d = %d\n", n, i, n * i);
return 0;
}
Input / Output Example:
Input: 5
Output: Table of 5 from 1 to 10
98. Sum of Digits
Program Code:
#include <stdio.h>
int main() {
int n, sum = 0, rem;
printf("Enter a number: ");
scanf("%d", &n);
while(n != 0) {
rem = n % 10;
sum += rem;
n /= 10;
}
printf("Sum of digits = %d\n", sum);
return 0;
}
Input / Output Example:
Input: 1234
Output: 10
99. Count Digits
Program Code:
#include <stdio.h>
int main() {
int n, count = 0;
printf("Enter a number: ");
scanf("%d", &n);
do {
count++;
n /= 10;
} while(n != 0);
printf("Number of digits = %d\n", count);
return 0;
}
Input / Output Example:
Input: 5678
Output: 4
100. Power of a Number
Program Code:
#include <stdio.h>
int main() {
int base, exp;
long long result = 1;
printf("Enter base and exponent: ");
scanf("%d %d", &base, &exp);
for(int i = 1; i <= exp; i++)
result *= base;
printf("%d^%d = %lld\n", base, exp, result);
return 0;
}
Input / Output Example:
Input: 2 5
Output: 2^5 = 32
101. Factor Count of a Number
Program Code:
#include <stdio.h>
int main() {
int n, count = 0;
printf("Enter a number: ");
scanf("%d", &n);
for(int i = 1; i <= n; i++) {
if(n % i == 0)
count++;
}
printf("Number of factors = %d\n", count);
return 0;
}
Input / Output Example:
Input: 12
Output: 6
102. Print Even Numbers
Program Code:
#include <stdio.h>
int main() {
int n;
printf("Enter limit: ");
scanf("%d", &n);
printf("Even numbers: ");
for(int i = 2; i <= n; i += 2)
printf("%d ", i);
return 0;
}
Input / Output Example:
Input: 10
Output: 2 4 6 8 10
103. Print Odd Numbers
Program Code:
#include <stdio.h>
int main() {
int n;
printf("Enter limit: ");
scanf("%d", &n);
printf("Odd numbers: ");
for(int i = 1; i <= n; i += 2)
printf("%d ", i);
return 0;
}
Input / Output Example:
Input: 9
Output: 1 3 5 7 9
104. Sum of Even and Odd Numbers Separately
Program Code:
#include <stdio.h>
int main() {
int n, evenSum = 0, oddSum = 0;
printf("Enter n: ");
scanf("%d", &n);
for(int i = 1; i <= n; i++) {
if(i % 2 == 0)
evenSum += i;
else
oddSum += i;
}
printf("Sum of even numbers = %d\n", evenSum);
printf("Sum of odd numbers = %d\n", oddSum);
return 0;
}
Input / Output Example:
Input: 10
Output: Sum of even numbers = 30
Sum of odd numbers = 25

[Link] declaration
#include<stdio.h>
void main()
{
int a[]={25,23,21,42};
int i;
for(i=0;i<4;i++)
{
printf("a[%d]=%d\n",i,a[i]);
printf("adress=%u\n",&a[i]);
}
}
Output:

a[0]=25
adress=6684208
a[1]=23
adress=6684212
a[2]=21
adress=6684216
a[3]=42
adress=6684220

[Link] declaration and initialization.

#include<stdio.h>
void main()
{
int i,number[10]={1,5,8};
float num[5]={0.5,15.8,-10};
char name[8]={'n','i','k'};
for(i=0;i<10;i++)
{
printf("number[%d] = %d\n",i,number[i]);
}
for(i=0;i<5;i++)
{
printf("num[%d] = %f\n",i,num[i]);
}
for(i=0;i<8;i++)
{
printf("name[%d] = %c\n",i,name[i]);
}
}
Output:
number[0] = 1
number[1] = 5
number[2] = 8
number[3] = 0
number[4] = 0
number[5] = 0
number[6] = 0
number[7] = 0
number[8] = 0
number[9] = 0
num[0] = 0.500000
num[1] = 15.800000
num[2] = -10.000000
num[3] = 0.000000
num[4] = 0.000000
name[0] = n
name[1] = i
name[2] = k
name[3] =
name[4] =
name[5] =
name[6] =
name[7] =

107. Read and display array elements

#include<stdio.h>
void main()
{
int arr[5], i;
printf("enter array elements:");
for(i = 0; i < 5; i++)
{
scanf("%d", &arr[i]);
}
printf("\nPrinting elements of the array: \n\n");
for(i = 0; i < 5; i++)
{
printf("%d ", arr[i]);
}
}
Output:
enter array elements:1 6 3 2 9

Printing elements of the array:

16329

[Link] to find average marks obtained by 10 students in a test

#include<stdio.h>
void main()
{
int sum=0, avg, i, marks[10];
for(i=0;i<10;i++)
{
printf("Enter marks:");
scanf("%d",&marks[i]);
}
for(i=0;i<10;i++)
{
sum=sum+ marks[i];
}
avg=sum/10;
printf("\nAverage marks= %d\n", avg);
}
Output:
Enter marks:5
Enter marks:2
Enter marks:8
Enter marks:21
Enter marks:67
Enter marks:32
Enter marks:25
Enter marks:90
Enter marks:32
Enter marks:55

Average marks= 33

[Link] toNotations for retrieving array elements

#include<stdio.h>
void main()
{
int a[]={25,23,21,42};
int i;
for(i=0;i<4;i++)
{
printf("address=%u, ",&a[i]);
printf("a[%d]=%d %d %d %d \n",i,a[i], *(a+i), *(i+a), i[a]);
}
}
Output:
address=6684208, a[0]=25 25 25 25
address=6684212, a[1]=23 23 23 23
address=6684216, a[2]=21 21 21 21
address=6684220, a[3]=42 42 42 42

110. Program to find largest and smallest number of the array

#include<stdio.h>
void main()
{
int a[50], i, n, large, small;
printf("How many elements:");
scanf("%d",&n);

printf("Enter the Array:");


for(i=0; i<n; ++i)
{
scanf("%d",&a[i]);
}

large = small = a[0];

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


{
if(a[i] > large)
large = a[i];

if(a[i] < small)


small = a[i];
}

printf("The largest element is %d", large);


printf("\nThe smallest element is %d", small);
}
Output:
How many elements:5
Enter the Array:2 9 1 6 4
The largest element is 9
The smallest element is 1

[Link] to initialize Two dimensional array, print the array elements and its respective
address

#include<stdio.h>
void main()
{
int students[4][2]={101,88,102,97,103,65,104,85};
int i,j;
for(i=0;i<4;i++)
for(j=0;j<2;j++)
{
printf("students[%d][%d] = %d", i,j,students[i][j]);
printf(" address = %u\n", &students[i][j]);
}
}
Output:
students[0][0] = 101 address = 6684192
students[0][1] = 88 address = 6684196
students[1][0] = 102 address = 6684200
students[1][1] = 97 address = 6684204
students[2][0] = 103 address = 6684208
students[2][1] = 65 address = 6684212
students[3][0] = 104 address = 6684216
students[3][1] = 85 address = 6684220

[Link] to Read and display 2-D array from keyboard

#include<stdio.h>
void main()
{
int arr[10][10], row, col, i, j;
printf("Enter number of row for Array (max 10) : ");
scanf("%d",&row);
printf("Enter number of column for Array (max 10) : ");
scanf("%d",&col);
printf("Now Enter %d*%d Array Elements : ",row, col);
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
scanf("%d",&arr[i][j]);
}
}
printf("The Array is :\n");
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
printf("%d ",arr[i][j]);
}
printf("\n");
}
}
Output:
Enter number of row for Array (max 10) : 5
Enter number of column for Array (max 10) : 2
Now Enter 5*2 Array Elements : 1 2 3 4 5 6 7 8 9 10
The Array is :
1 2
3 4
5 6
7 8
9 10
[Link] to show how 2-D array is stored
#include<stdio.h>
void main()
{
int s[4][2]={101,88,102,76,103,54,104,46};
printf("Base Address = %u\n",s);
printf("zeroth 1-d address = %u\n",s[0]);
printf("first 1-d address = %u\n",s[1]);
printf("second 1-d address = %u\n",s[2]);
printf("third 1-d address = %u\n",s[3]);
}

Output:
Base Address = 6684208
zeroth 1-d address = 6684208
first 1-d address = 6684216
second 1-d address = 6684224
third 1-d address = 6684232

114. program for Addition of two matrices


#include<stdio.h>
void main()
{
int mat1[3][3], mat2[3][3], mat3[3][3], i, j, k;
printf("Enter first matrix element (3*3) : ");
for(i=0; i<3; i++)
for(j=0; j<3; j++)
scanf("%d",&mat1[i][j]);
printf("Enter second matrix element (3*3) : ");
for(i=0; i<3; i++)
for(j=0; j<3; j++)
scanf("%d",&mat2[i][j]);
printf("\nMatrix 1:\n");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
printf("%2d ",mat1[i][j]);
}
printf("\n");
}
printf("\nMatrix 2:\n");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
printf("%2d ",mat2[i][j]);
}
printf("\n");
}
//Addition of 2 matrices
printf("\nsum matrix:\n");
for(i=0; i<3; i++)
for(j=0; j<3; j++)
mat3[i][j]=mat1[i][j]+mat2[i][j];
//print sum matrix
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
printf("%2d ",mat3[i][j]);
}
printf("\n");
}
}
Output:
Enter first matrix element (3*3) : 1 2 3 4 5 6 7 8 9
Enter second matrix element (3*3) : 1 2 3 4 5 6 7 8 9

Matrix 1:
1 2 3
4 5 6
7 8 9

Matrix 2:
1 2 3
4 5 6
7 8 9

sum matrix:
2 4 6
8 10 12
14 16 18

[Link] for Multiplication of two matrices

#include<stdio.h>
#include<stdlib.h>//for exit() function
void main()
{
int mat1[5][5], mat2[5][5], mat3[5][5], i, j, k, m, n, p, q;
printf("Enter first matrix dimensions: ");
scanf("%d %d",&m, &n);
printf("Enter second matrix dimensions: ");
scanf("%d %d", &p, &q);
if(n!=p)
{
printf("Enter valid dimensions\n");
exit(0);
}
printf("Enter first matrix (%d*%d) : ",m,n);
for(i=0; i<m; i++)
for(j=0; j<n; j++)
scanf("%d",&mat1[i][j]);

printf("Enter second matrix (%d*%d) : ",p,q);


for(i=0; i<p; i++)
for(j=0; j<q; j++)
scanf("%d",&mat2[i][j]);
printf("\nMatrix 1:\n");
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
printf("%2d ",mat1[i][j]);
printf("\n");
}
printf("\nMatrix 2:\n");
for(i=0; i<p; i++)
{
for(j=0; j<q; j++)
printf("%2d ",mat2[i][j]);
printf("\n");
}
//Multiplication of 2 matrices
printf("\nMultiplication matrix:\n");
for(i=0; i<m; i++)
{
for(j=0; j<q; j++)
{
mat3[i][j]=0;
for(k=0; k<n; k++)
mat3[i][j] = mat3[i][j]+mat1[i][k] *mat2[k][j];
}
}
//print Multiplied matrix
for(i=0; i<m; i++)
{
for(j=0; j<q; j++)
{
printf("%2d ",mat3[i][j]);
}
printf("\n");
}
}
Output:

Enter first matrix dimensions: 3 3


Enter second matrix dimensions: 3
3
Enter first matrix (3*3) : 1 1 1 1 1 1 1 1 1
Enter second matrix (3*3) : 2 2 2 2 2 2 2 2 2

Matrix 1:
1 1 1
1 1 1
1 1 1

Matrix 2:
2 2 2
2 2 2
2 2 2

Multiplication matrix:
6 6 6
6 6 6
6 6 6

[Link] for Transpose of 3X3 matrices

#include<stdio.h>
void main()
{
int mat1[3][3], mat2[3][3], i, j;
printf("Enter first matrix element (3*3) : ");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
scanf("%d",&mat1[i][j]);
}
}
printf("\nMatrix 1:\n");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
printf("%2d ",mat1[i][j]);
}
printf("\n");
}
//Transpose of matrix 1
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
mat2[i][j]=mat1[j][i];
}
}
//print transpose matrix
printf("\nTranspose Matrix:\n");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
printf("%2d ",mat2[i][j]);
}
printf("\n");
}
}

Enter first matrix element (3*3) : 1 2 3 1 2 3 1 2 3

Matrix 1:
1 2 3
1 2 3
1 2 3

Transpose Matrix:
1 1 1
2 2 2
3 3 3

[Link] for Transpose of 3X2 matrices


#include<stdio.h>
void main()
{
int mat1[3][2], mat2[2][3], i, j;
printf("Enter first matrix element (3*2) : ");
for(i=0; i<3; i++)
{
for(j=0; j<2; j++)
{
scanf("%d",&mat1[i][j]);
}
}
printf("\nMatrix 1:\n");
for(i=0; i<3; i++)
{
for(j=0; j<2; j++)
{
printf("%2d ",mat1[i][j]);
}
printf("\n");
}
//Transpose of matrix 1
for(i=0; i<2; i++)
{
for(j=0; j<3; j++)
{
mat2[i][j]=mat1[j][i];
}
}
//print transpose matrix
printf("\nTranspose Matrix:\n");
for(i=0; i<2; i++)
{
for(j=0; j<3; j++)
{
printf("%2d ",mat2[i][j]);
}
printf("\n");
}
}
Output:
Enter first matrix element (3*2) : 1 2 3 4 5 6

Matrix 1:
1 2
3 4
5 6

Transpose Matrix:
1 3 5
2 4 6
118. program for Trace of matrices

#include<stdio.h>
void main()
{
int mat1[3][3], i, j, sum;
sum=0;
printf("Enter first matrix element (3*3) : ");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
scanf("%d",&mat1[i][j]);
}
}
printf("\nMatrix 1:\n");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
printf("%2d ",mat1[i][j]);
}
printf("\n");
}
//Trace of matrix 1
for(i=0; i<3; i++)
{
sum=sum+mat1[i][i];
}
//print trace matrix
printf("\nTrace of Matrix1 = %d\n", sum);
}

Output:
Enter first matrix element (3*3) : 1 2 3 4 5 6 7 8 9

Matrix 1:
1 2 3
4 5 6
7 8 9

Trace of Matrix1 = 15

119. program for Normal of matrices

#include <stdio.h>
#include <math.h>
void main ()
{
int array[10][10];
int i,j,m,n,sum,normal;
sum=0;
printf("Enter the order of the matrix\n");
scanf("%d %d", &m, &n);
printf("Enter the elements of the matrix \n");
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
scanf("%d", &array[i][j]);
}
}
printf("\nMatrix :\n");
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
printf("%2d ",array[i][j]);
sum=sum+ array[i][j] * array[i][j]; // calculate sum of square of elementsl
}
printf("\n");
}
normal = sqrt(sum);
printf("The normal of the matrix is = %d\n", normal);
}
Output:
Enter the order of the matrix
33
Enter the elements of the matrix
123456789

Matrix :
1 2 3
4 5 6
7 8 9
The normal of the matrix is = 16

120. program for Memory allocation of character array


#include<stdio.h>
void main()
{
char name[]= { 'H', 'E', 'L', 'L', 'O','\0'};
int i=0;
while(i<5)
{
printf("'%c' = %u\n", name[i], &name[i]);
i++;
}
}
Output:
'H' = 6684230
'E' = 6684231
'L' = 6684232
'L' = 6684233
'O' = 6684234

[Link] for string access


#include<stdio.h>
void main()
{
char name[]= "HELLO",name2[10]; // sets aside 10 bytes under the array name2
int i=0;
printf("\n");
while(name[i]!='\0')
{
printf("%c",name[i]);
i++;
}
printf("\nEnter your name: ");
scanf("%s",name2); // fills in the characters until enter key is hit then places ‘\0’ in
the array
printf("Your name is %s.\n",name2);
}
Output:

HELLO
Enter your name: krishna
Your name is krishna.

122.A program to show how gets() and puts() functions are used

#include<stdio.h>
void main()
{
char name[20];
printf("Enter your name: ");
gets(name);
puts("Hello!");
puts(name);
}

Output:
Enter your name: venkata krishna rao
Hello!
venkata krishna rao

[Link] for vowels count in a string


#include <stdio.h>
#include <string.h>

int main() {
char str[100];
int i, count = 0;

printf("Enter a string: ");


gets(str); // note: gets() is unsafe, but okay for simple practice programs

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


// check if the character is a vowel
if (str[i] == 'a' || str[i] == 'e' || str[i] == 'i' ||
str[i] == 'o' || str[i] == 'u' || str[i] == 'A' ||
str[i] == 'E' || str[i] == 'I' || str[i] == 'O' ||
str[i] == 'U') {
count++;
}
}

printf("Number of vowels in the string: %d\n", count);

return 0;
}

Output:
Enter a string: Hello World
Number of vowels in the string: 3

[Link] for Vowel frequency


#include <stdio.h>
#include <string.h>

int main() {
char str[100];
int i;
int a = 0, e = 0, i_count = 0, o = 0, u = 0;

printf("Enter a string: ");


fgets(str, sizeof(str), stdin); // safer than gets()

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


switch(str[i]) {
case 'a':
case 'A':
a++;
break;
case 'e':
case 'E':
e++;
break;
case 'i':
case 'I':
i_count++;
break;
case 'o':
case 'O':
o++;
break;
case 'u':
case 'U':
u++;
break;
}
}

printf("\nVowel frequencies:\n");
printf("A or a: %d\n", a);
printf("E or e: %d\n", e);
printf("I or i: %d\n", i_count);
printf("O or o: %d\n", o);
printf("U or u: %d\n", u);

return 0;
}

Output:
Enter a string: hello world this is great

Vowel frequencies:
A or a: 1
E or e: 2
I or i: 2
O or o: 2
U or u: 0

[Link] for access to 2d character array


#include<stdio.h>
void main()
{
char name_list[6][10]={"ram", "sham", "priya", "ramya", "raju", "ravi"};
char name_list2[3][10];
int i;
printf("6 names:\n");
for(i=0;i<6;i++)
puts(name_list[i]);
printf("Enter some name:\n");
for(i=0;i<3;i++)
gets(name_list2[i]);
printf("3 names\n");
for(i=0;i<3;i++)
puts(name_list2[i]);
}

Output:
6 names:
ram
sham
priya
ramya
raju
ravi
Enter some name:
krishna
ramesh
rajesh
3 names
krishna
ramesh
rajesh
126. Count the Number of Vowels, Consonants, and Digits

#include <stdio.h>
#include <ctype.h>

int main() {
char str[100];
int vowels = 0, consonants = 0, digits = 0, i;

printf("Enter a string: ");


gets(str);

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


char ch = tolower(str[i]);
if (ch >= 'a' && ch <= 'z') {
if (ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')
vowels++;
else
consonants++;
} else if (isdigit(ch)) {
digits++;
}
}

printf("\nVowels: %d\nConsonants: %d\nDigits: %d\n", vowels, consonants, digits);


return 0;
}
output:
Enter a string: aaa 23 joij 56
Vowels: 5
Consonants: 2
Digits: 4
127. Reverse a String

#include <stdio.h>
#include <string.h>

int main() {
char str[100], rev[100];
int i, len;

printf("Enter a string: ");


gets(str);

len = strlen(str);
for (i = 0; i <len; i++)
rev[i] = str[len - i - 1];
rev[len] = '\0';

printf("Reversed string: %s\n", rev);


return 0;
}
Output:
Enter a string: abcdef
Reversed string: fedcba
128.. Check Whether a String is a Palindrome

#include<stdio.h>
#include<string.h>
int main() {
char str[100];
int i, len, flag = 0;
printf("Enter a string: ");
gets(str);
len = strlen(str);
for (i = 0; i < len / 2; i++) {
if (str[i] != str[len - i - 1]) {
flag = 1;
break;
}
}
if (flag == 0)
printf("The string is a palindrome.\n");
else
printf("The string is not a palindrome.\n");

return 0;
}
Output:
Enter a string: abcdcba
The string is a palindrome.

129. Convert String to Uppercase and Lowercase

#include <stdio.h>
int main() {
char str[100];
int i;
printf("Enter a string: ");
gets(str);
for (i = 0; str[i] != '\0'; i++) {
// If character is lowercase (a–z)
if (str[i] >= 'a' && str[i] <= 'z') {
str[i] = str[i] - 32; // Convert to uppercase (ASCII difference = 32)
}
// If character is uppercase (A–Z)
else if (str[i] >= 'A' && str[i] <= 'Z') {
str[i] = str[i] + 32; // Convert to lowercase
}
}
printf("Converted string: %s", str);
return 0;
}
OUTPUT:
Enter a string: abcABC
Converted string: ABCabc

[Link] for 3 – D array

#include <stdio.h>
void main() {
int arr[2][2][2] = { { {1, 2}, {3, 4} }, { {5, 6}, {7, 8} } };
for (int i = 0; i < 2; i++) {
printf("block %d\n",i+1);
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
printf("arr[%d][%d][%d] = %d\t", i, j, k, arr[i][j][k]);
} printf("\n");
} printf("\n\n\n");
}
}

block 1
arr[0][0][0] = 1 arr[0][0][1] = 2
arr[0][1][0] = 3 arr[0][1][1] = 4

block 2
arr[1][0][0] = 5 arr[1][0][1] = 6
arr[1][1][0] = 7 arr[1][1][1] = 8

[Link] for Formatted Printf statement

#include <stdio.h>

int main() {
int num = 123;
float pi = 3.1415926;
char str[] = "Hello";

// 1. Field width specification


printf("1. Field width specification:\n");
printf("Without width: |%d|\n", num);
printf("With width 10: |%10d|\n", num); // total width = 10
printf("\n");

// 2. Precision specifier
printf("2. Precision specifier:\n");
printf("Float default: |%f|\n", pi);
printf("Float with 2 decimals: |%.2f|\n", pi);
printf("String with precision 3: |%.3s|\n", str); // only first 3 chars printed
printf("\n");

// 3. Left Justification
printf("3. Left Justification:\n");
printf("Right justified (default): |%10d|\n", num);
printf("Left justified: |%-10d|\n", num);
printf("Left justified string: |%-10s|\n", str);

return 0;
}
Output:
1. Field width specification:
Without width: |123|
With width 10: | 123|

2. Precision specifier:
Float default: |3.141593|
Float with 2 decimals: |3.14|
String with precision 3: |Hel|

3. Left Justification:
Right justified (default): | 123|
Left justified: |123 |
Left justified string: |Hello |
[Link] for strcmp,strcpy,strcat

#include <stdio.h>
#include <string.h>

int main() {
char str1[50] = "Hello";
char str2[50] = "World";
char str3[50];
int n = 3;

printf("Initial Strings:\n");
printf("str1 = %s\n", str1);
printf("str2 = %s\n\n", str2);

// strcat(str1, str2)
strcat(str1, str2);
printf("After strcat(str1, str2): %s\n", str1);

// Reset str1
strcpy(str1, "Hello");

// strncat(str1, str2, n)
strncat(str1, str2, n);
printf("After strncat(str1, str2, %d): %s\n", n, str1);

// strcpy(str3, str2)
strcpy(str3, str2);
printf("After strcpy(str3, str2): %s\n", str3);

// strncpy(str3, str2, n)
strncpy(str3, "GoodMorning", n);
str3[n] = '\0'; // Add null terminator manually
printf("After strncpy(str3, \"GoodMorning\", %d): %s\n", n, str3);
printf("str 1 - %s \t str 2 - %s \t str 3 - %s\n",str1,str2,str3);
// strlen(str1)
printf("Length of str1 = %lu\n", strlen(str1));

// strcmp(str1, str2)
if (strcmp(str1, str2) == 0)
printf("strcmp(str1, str2): Strings are equal\n");
else
printf("strcmp(str1, str2): Strings are not equal\n");

// strncmp(str1, str2, n)
if (strncmp(str1, str2, n) == 0)
printf("strncmp(str1, str2, %d): First %d characters are equal\n", n, n);
else
printf("strncmp(str1, str2, %d): First %d characters are not equal\n", n, n);

// strcmpi(str1, str2) (Case-insensitive comparison — available in some compilers)

if (strcmpi(str1, str2) == 0)
printf("strcmpi(str1, str2): Strings are equal (case-insensitive)\n");
else
printf("strcmpi(str1, str2): Strings are not equal (case-insensitive)\n");
if (strcasecmp(str1, str2) == 0)
printf("strcasecmp(str1, str2): Strings are equal (case-insensitive)\n");
else
printf("strcasecmp(str1, str2): Strings are not equal (case-insensitive)\n");
return 0;
}

Output:
Initial Strings:
str1 = Hello
str2 = World

After strcat(str1, str2): HelloWorld


After strncat(str1, str2, 3): HelloWor
After strcpy(str3, str2): World
After strncpy(str3, "GoodMorning", 3): Goo
str 1 - HelloWor str 2 - World str 3 - Goo
Length of str1 = 8
strcmp(str1, str2): Strings are not equal
strncmp(str1, str2, 3): First 3 characters are not equal
strcmpi(str1, str2): Strings are not equal (case-insensitive)
strcasecmp(str1, str2): Strings are not equal (case-insensitive)

[Link] for strchr,strstr,dup,,lwr,upr

#include <stdio.h>
#include <string.h>
#include <stdlib.h> // for strdup()

int main() {
char str1[100] = "Hello World, Welcome to C Programming world";
char str2[50] = "World";
char ch = 'o';
char *ptr;

printf("Original String: %s\n\n", str1);

// strchr(str1, ch)
ptr = strchr(str1, ch);
if (ptr != NULL)
printf("strchr(str1, '%c') = %s\n", ch, ptr);
else
printf("Character '%c' not found using strchr.\n", ch);

// strrchr(str1, ch)
ptr = strrchr(str1, ch);
if (ptr != NULL)
printf("strrchr(str1, '%c') = %s\n", ch, ptr);
else
printf("Character '%c' not found using strrchr.\n", ch);

// strstr(str1, str2)
ptr = strstr(str1, str2);
if (ptr != NULL)
printf("strstr(str1, \"%s\") = %s\n", str2, ptr);
else
printf("Substring \"%s\" not found using strstr.\n", str2);
// strdup(str1) – duplicates a string (returns a new copy in heap)
char *copy = strdup(str1);
if (copy != NULL)
printf("strdup(str1) = %s\n", copy);
// strlwr(str1) – converts to lowercase (non-standard, works in Turbo C / Windows)
strlwr(str1);
printf("After strlwr(str1): %s\n", str1);

// strupr(str1) – converts to uppercase (non-standard, works in Turbo C / Windows)


strupr(str1);
printf("After strupr(str1): %s\n", str1);

return 0;
}

Output:
Original String: Hello World, Welcome to C Programming world

strchr(str1, 'o') = o World, Welcome to C Programming world


strrchr(str1, 'o') = orld
strstr(str1, "World") = World, Welcome to C Programming world
strdup(str1) = Hello World, Welcome to C Programming world
After strlwr(str1): hello world, welcome to c programming world
After strupr(str1): HELLO WORLD, WELCOME TO C PROGRAMMING WORLD

134. program for strrev,set,tok,spn

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() {
char str1[100] = "HelloWorld";
char str2[50] = "Welcome";
char temp[100];
char delim[] = " ,.-";
char *token;
int n = 5;

printf("Original String: %s\n\n", str1);

// strrev(str1) – reverses the string (non-standard in GCC)


strcpy(temp, str1); // make a copy to preserve original

strrev(temp);
printf("After strrev(str1): %s\n", temp);

// strset(str1, ch) – sets all characters of str1 to ch (non-standard)


strcpy(temp, str1);

strset(temp, '*');
printf("After strset(str1, '*'): %s\n", temp);
// strnset(str1, ch, n) – sets first n characters to ch (non-standard)
strcpy(temp, str1);

strnset(temp, '#', n);


printf("After strnset(str1, '#', %d): %s\n", n, temp);

// strtok(str, delimiter) – splits string into tokens


strcpy(temp, "Welcome,to,C,Programming");
printf("\nUsing strtok() on \"%s\"\nTokens:\n", temp);
token = strtok(temp, ",");
while (token != NULL) {
printf("%s\n", token);
token = strtok(NULL, ",");
}
Output:
Original String: HelloWorld

After strrev(str1): dlroWolleH


After strset(str1, '*'): **********
After strnset(str1, '#', 5): #####World

Using strtok() on "Welcome,to,C,Programming"


Tokens:
Welcome
to
C
Programming

str1 = abcdef123
str2 = abcxyz
strspn(str1, str2) = 3

135. C program for vowels,consonants,digits,spaces

#include<stdio.h>
int main( )
{
char line[150];
int i, v=0, c=0, ch=0, d=0, s=0, o=0;
printf("Enter a line of string:\n");
gets(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')
++v;
else if((line[i]>='a'&& line[i]<='z') || (line[i]>='A'&& line[i]<='Z'))
++c;
else if(line[i]>='0'&&c<='9')
++d;
else if (line[i]==' ')
++s;
}
printf("Vowels: %d", v);
printf("\nConsonants: %d", c);
printf("\nDigits: %d", d);
printf("\nWhite spaces: %d", s);
return 0;
}

Output:
Enter a line of string:
n v krishna rao
Vowels: 4
Consonants: 8
Digits: 0
White spaces: 3

[Link] function(write in observation)


#include<stdio.h>
#include<math.h>
void main()
{
int x;
x=sqrt(16);
printf("%d",x);
}

[Link] definition & function call(write in observation)


#include <stdio.h>

int sum(int a, int b) // function body


{
return a + b;
}

int main()
{
int add = sum(10, 30); // function call
printf("Sum is : %d", add);
return 0;
}

138. function declaration , definition,& function call(write in observation)


#include <stdio.h>
int sum(int, int);// declaration
int main()
{
int add = sum(10, 30); //function call_actual parameters
printf("Sum is : %d", add);
return 0;
}
int sum(int a, int b) // function body_ formal parameters
{ return a + b;
}

139. call by value(write in Record)


#include <stdio.h>
/* function declaration */
void swap(int x, int y);
int main ()
{
/* local variable definition */
int a = 100,b = 200;

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


/* calling a function to swap the values */
swap(a, b);
printf("in main function After swap, value of a : %d b : %d\n", a,b );

return 0;
}
/* function definition to swap the values */
void swap(int x, int y)
{
int temp; /* local variable definition */
printf("in subfunction before swap, value of a : %d b : %d\n", x,y );

temp = x; /* save the value of x */


x = y; /* put y into x */
y = temp; /* put temp into y */
printf("in subfunction After swap, value of a : %d b : %d\n", x,y );

[Link] by reference(write in Record)

#include <stdio.h>
/* function declaration */
void swap(int *x, int *y);
void main( )
{
/* local variable definition */
int a = 100,b = 200;
printf("in main function Before swap, value of a : %d b : %d\n", a,b );
/* calling a function to swap the values.
* &a indicates pointer to a i.e. address of variable a and
* &b indicates pointer to b i.e. address of variable b.
*/
swap(&a, &b);
printf("in main function After swap, value of a : %d b : %d\n", a,b );

}
/* function definition to swap the values */
void swap (int *x, int *y)
{
int temp;/* local variable definition */
printf("in subfunction before swap, value of a : %d b : %d\n", *x,*y );
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put temp into y */
printf("in subfunction After swap, value of a : %d b : %d\n", *x,*y );

[Link] Matrix operations with functions (write in Record)


#include <stdio.h>

#define MAX 10

// Function prototypes
void inputMatrix(int matrix[MAX][MAX], int rows, int cols);
void displayMatrix(int matrix[MAX][MAX], int rows, int cols);
void addMatrices(int a[MAX][MAX], int b[MAX][MAX], int r, int c);
void multiplyMatrices(int a[MAX][MAX], int b[MAX][MAX], int r1, int c1, int r2, int c2);
void transposeMatrix(int a[MAX][MAX], int r, int c);
void traceMatrix(int a[MAX][MAX], int n);

int main() {
int choice;
int a[MAX][MAX], b[MAX][MAX];
int r1, c1, r2, c2, n;

printf("Matrix Operations Menu:\n");


printf("1. Matrix Addition\n");
printf("2. Matrix Multiplication\n");
printf("3. Matrix Transpose\n");
printf("4. Matrix Trace\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("\nEnter rows and columns of matrices: ");
scanf("%d %d", &r1, &c1);
printf("Enter elements of Matrix A:\n");
inputMatrix(a, r1, c1);
printf("Enter elements of Matrix B:\n");
inputMatrix(b, r1, c1);
addMatrices(a, b, r1, c1);
break;

case 2:
printf("\nEnter rows and columns of Matrix A: ");
scanf("%d %d", &r1, &c1);
printf("Enter elements of Matrix A:\n");
inputMatrix(a, r1, c1);

printf("Enter rows and columns of Matrix B: ");


scanf("%d %d", &r2, &c2);

if (c1 != r2) {
printf("Matrix multiplication not possible!\n");
break;
}
printf("Enter elements of Matrix B:\n");
inputMatrix(b, r2, c2);
multiplyMatrices(a, b, r1, c1, r2, c2);
break;

case 3:
printf("\nEnter rows and columns of Matrix: ");
scanf("%d %d", &r1, &c1);
printf("Enter elements of Matrix:\n");
inputMatrix(a, r1, c1);
transposeMatrix(a, r1, c1);
break;

case 4:
printf("\nEnter order of square matrix: ");
scanf("%d", &n);
printf("Enter elements of Matrix:\n");
inputMatrix(a, n, n);
traceMatrix(a, n);
break;

default:
printf("Invalid choice!\n");
}

return 0;
}

// Function to input a matrix


void inputMatrix(int matrix[MAX][MAX], int rows, int cols) {
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
scanf("%d", &matrix[i][j]);
}

// Function to display a matrix


void displayMatrix(int matrix[MAX][MAX], int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++)
printf("%d ", matrix[i][j]);
printf("\n");
}
}

// Function to add two matrices


void addMatrices(int a[MAX][MAX], int b[MAX][MAX], int r, int c) {
int result[MAX][MAX];
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++)
result[i][j] = a[i][j] + b[i][j];

printf("\nResult of Matrix Addition:\n");


displayMatrix(result, r, c);
}
// Function to multiply two matrices
void multiplyMatrices(int a[MAX][MAX], int b[MAX][MAX], int r1, int c1, int r2, int c2) {
int result[MAX][MAX];
for (int i = 0; i < r1; i++)
for (int j = 0; j < c2; j++) {
result[i][j] = 0;
for (int k = 0; k < c1; k++)
result[i][j] += a[i][k] * b[k][j];
}

printf("\nResult of Matrix Multiplication:\n");


displayMatrix(result, r1, c2);
}

// Function to find the transpose of a matrix


void transposeMatrix(int a[MAX][MAX], int r, int c) {
int result[MAX][MAX];
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++)
result[j][i] = a[i][j];

printf("\nTranspose of the Matrix:\n");


displayMatrix(result, c, r);
}

// Function to calculate trace of a matrix


void traceMatrix(int a[MAX][MAX], int n) {
int trace = 0;
for (int i = 0; i < n; i++)
trace += a[i][i];

printf("\nTrace of the Matrix = %d\n", trace);


}

142. no argument and no return(write in Record)

#include <stdio.h>

// Function declaration
void greet();

int main() {
greet(); // Function call
return 0;
}

// Function definition
void greet() {
printf("Hello! Welcome to C programming.\n");
}

143. no return and with arguments(write in Record)


#include <stdio.h>

// Function declaration
void displaySum(int a, int b);

int main() {
int x = 5, y = 10;
displaySum(x, y); // Function call with arguments
return 0;
}

// Function definition
void displaySum(int a, int b) {
int sum = a + b;
printf("Sum = %d\n", sum);
}

144. return and no arguments(write in Record)

#include <stdio.h>

// Function declaration
int getNumber();

int main() {
int num = getNumber(); // Function call and storing return value
printf("You entered: %d\n", num);
return 0;
}

// Function definition
int getNumber() {
int n;
printf("Enter a number: ");
scanf("%d", &n);
return n;
}

145. return and arguments(write in Record)

#include <stdio.h>

// Function declaration
int multiply(int a, int b);

int main() {
int x = 4, y = 6;
int result = multiply(x, y); // Function call
printf("Product = %d\n", result);
return 0;
}

// Function definition
int multiply(int a, int b) {
return a * b;
}

[Link] scope(write in observation)


#include <stdio.h>
// variable with file scope
int x = 10;
void func() {
// x is available in func() function,
// x now equals 10 + 10 = 20
x += 10;
printf("Value of x in function is %d\n", x);
}
int main () {
func();
// x is also available in main() function
x += 30; // x now equals 20 + 30 = 50
printf("Value of x in main is %d", x);
return 0;
}

[Link] scope(write in observation)

#include <stdio.h>

int main() {
int a = 5;
int b = 10;

// inner block of code having block scope


{
int sum = a + b;
printf("Sum of a and b: %d", sum);
}

// the below statement will throw an error because,


// sum variable is not available outside the scope of above block,
// printf("Sum of a and b: %d", sum);

return 0;
}

[Link] scope(write in observation)

#include <stdio.h>
void findAge() {
// the age variable is not accessible outside the function findAge()
// as it is having local scope to the function i.e. function scope
int age = 18;
printf("Age is %d", age);
}
int main() {

//printf("Age is %d", age);


findAge();
return 0;
}
[Link] prototype scope(write in observation)

#include <stdio.h>

// variables a and b are available only inside the function and


// both variables have function prototype scope
int findSum(int a, int b) {
return a + b;
}

int main() {
int sum = findSum(3, 5);
printf("Sum of 3 and 5 is %d", sum);
return 0;
}

150. All scope variable (write in Record)

#include <stdio.h>
// global variables having file scope
int A = 10;
double B = 9.8;

// parameters a, b have prototype scope


int sumOfTwoNumbers(int a, int b) {
// sum variable has function scope
int sum = a + b;
printf("sum Function Prototype Scope Variables:\na : %d, b : %d\nsum Function Scope
Variable :\nsum : %d\n", a, b, sum);
return sum;
}
int main() {
// PI and radius variables have function scope
double PI = 3.14159;
int radius = 4;

printf("File Scope Variable:\nA : %d, B : %lf\n", A, B);

printf("main() Function Scope Variables\nPI: %lf, radius : %d\n", PI, radius);

{
// all variables declared inside have block scope
// int A, int C, int sum, double B and double Area
// variables have block scope
double Area = PI * radius * radius;
int A = 99;
double B = 10.97;
int C = 101;
int sum = sumOfTwoNumbers(A, C);

printf("Block Scope Variables:\nA : %d, B : %lf, C : %d, sum : %d, Area : %lf\n", A, B, C, sum,
Area);
}
// we can't use C and sum variables here
// (outside the block scope)
return 0;
}

151. AUTO storage(write in Record)


#include<stdio.h>
int main()
{
auto int x;//=2;
printf("%d",x);
return 0;
}

[Link] STORAGE(write in Record)

#include<stdio.h>
int main()
{
add();
add();
add();add();
}
void add()
{
static int x=0;
x++;
printf("%d ",x);
}
[Link] STORAGE(write in Record)
#include<stdio.h>
int main()
{
register int x=2;
printf("%d",x);
return 0;
}

154.1 SECOND FILE(write in Record)


#include<stdio.h>
int m = 5;
void add()
{
printf("\n in add function %d", m);
}
[Link] FILE(write in Record)
#include<stdio.h>
#include "[Link].c"
extern int m;
int main()
{
printf("in main function - %d", m);
add();
return 0;
}

155. Recursive Factorial(write in observation)


/* C program to find factorial of given Number */
/******************************************************/
#include<stdio.h>
long fact(long);
int main()
{
long n;
printf("Enter number to find factorial\n");
scanf("%ld",&n);
printf("The factorial of %ld is %ld",n,fact(n));
return 0;
}
long fact(long n)
{
if(n==0||n==1)
return 1;
else
return n*fact(n-1);
}

[Link] Fibonacci series(write in observation)

/* C program to generate Fibonacci series up to given 'N' numbers using recursion*/


/*******************************************************************/
#include<stdio.h>
int fib(int);
int main()
{
int n, i=0, c;
printf("Enter limit upto where Fibonacii series to be Generated\n");
scanf("%d", &n);
for(c=1;c<n;)
{
printf("%d\t",fib(i));
c=fib(i);
i++;
}
return 0;
}
int fib(int n)
{
if(n==0||n==1)
return n;
else
return (fib(n-1) +fib(n-2));
}

157./* C program to find GCD of given 2 numbers using recursion*/(write in Record)


/******************************************************/
#include<stdio.h>
int gcd(int, int);
int main()
{
int a,b;
printf("Enter two values to find GCD\n");
scanf("%d%d", &a, &b);
printf("GCD of %d and %d is %d\n",a, b, gcd(a, b));
return 0;
}
int gcd (int x, int y)
{
if(y==0)
return x;
else
return gcd (y, x%y);
}

[Link] search program(write in Record)


Linear search Algorithm
 Step 1 - Read the search element from the user.
 Step 2 - Compare the search element with the first element in the list.
 Step 3 - If both are matched, then display "Given element is found!!!" and terminate
the function
 Step 4 - If both are not matched, then compare search element with the next element
in the list.
 Step 5 - Repeat steps 3 and 4 until search element is compared with last element in the
list.
 Step 6 - If last element in the list also doesn't match, then display "Element is not
found!!!" and terminate the function.

/*C program to search the given key value in array elements using Linear searching
technique. */
/*************************************************************************/
#include<stdio.h>
int main()
{
int a[100], n, i, j, flag=0, key;
printf("Enter Number of elements in array: \n");
scanf("%d", &n);
printf("Enter %d Array Elements:\n", n);
for(i=0; i<n; i++)
scanf("%d", &a[i]);
printf("Enter Key value to search\n");
scanf("%d", &key);
for(i=0;i<n;i++)
{
if(key==a[i])
{
flag=1;
break;
}
}
if(flag==1)
printf("%d found at position %d\n",key,i+1);
else
printf("Sorry! %d not found in given elements\n",key);
return 0;
}

Output:
Enter Number of elements in array:
5
Enter 5 Array Elements:
25137
Enter Key value to search
1
1 found at position 3

[Link] search program with functions (write in Record)

#include<stdio.h>

int linearSearch(int arr[], int n, int key) {


for(int i = 0; i< n; i++) {
if(arr[i] == key)
return i;
}
return -1;
}

int main() {
int arr[50], n, key, pos;

printf("Enter number of elements: ");


scanf("%d", &n);

printf("Enter elements: ");


for(int i = 0; i< n; i++)
scanf("%d", &arr[i]);

printf("Enter key to search: ");


scanf("%d", &key);

pos = linearSearch(arr, n, key);

if(pos != -1)
printf("Element found at index %d\n", pos);
else
printf("Element not found\n");

return 0;
}
Output:
[Link] Search with recursive functions (write in observation)

#include <stdio.h>

int linearSearchRec(int arr[], int index, int n, int key) {


if(index >= n)
return -1;

if(arr[index] == key)
return index;

return linearSearchRec(arr, index + 1, n, key);


}

int main() {
int arr[50], n, key, pos;

printf("Enter number of elements: ");


scanf("%d", &n);

printf("Enter elements: ");


for(int i = 0; i< n; i++)
scanf("%d", &arr[i]);

printf("Enter key to search: ");


scanf("%d", &key);

pos = linearSearchRec(arr, 0, n, key);

if(pos != -1)
printf("Element found at index %d\n", pos);
else
printf("Element not found\n");

return 0;
}
Output:

[Link] search program (write in Record)

Algorithm:

Step 1 - Read the search element from the user.


Step 2 - Find the middle element in the sorted list.
Step 3 - Compare the search element with the middle element in the sorted list.
Step 4 - If both are matched, then display "Given element is found!!!" and terminate the
function.
Step 5 - If both are not matched, then check whether the search element is smaller or larger
than the middle element.
Step 6 - If the search element is smaller than middle element, repeat steps 2, 3, 4 and 5 for the
left sublist of the middle element.
Step 7 - If the search element is larger than middle element, repeat steps 2, 3, 4 and 5 for the
right sublist of the middle element.
Step 8 - Repeat the same process until we find the search element in the list or until sublist
contains only one element.
Step 9 - If that element also doesn't match with the search element, then display "Element is
not found in the list!!!" and terminate the function.

/*C program to search the given key value in array elements using Binary searching
technique.
***********************************************************************/
#include<stdio.h>
int main()
{
int a[100], n, i, high, low, mid, key;
printf("Enter Number of elements in array: \n");
scanf("%d", &n);
printf("Enter %d Array Elements in sorted order:\n", n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter Key value to search\n");
scanf("%d",&key);
low=0;
high=n-1;
while(low<=high){
mid=(low+high)/2;
if(key==a[mid])
{
printf("%d found at position %d\n",key,mid+1);
break;
}
else if(key>a[mid])
low=mid+1;
else
high=mid-1;
}
if(low>high)
printf ("Sorry! %d not found in given elements\n", key);
return 0;
}

Output:

Enter Number of elements in array:


5
Enter 5 Array Elements in sorted order:
13579
Enter Key value to search
7
7 found at position 4
[Link] search with functions (write in Record)
#include <stdio.h>

int binarySearch(int arr[], int n, int key) {


int low = 0, high = n - 1;

while(low <= high) {


int mid = (low + high) / 2;

if(arr[mid] == key)
return mid;
else if(arr[mid] < key)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}

int main() {
int arr[50], n, key, pos;

printf("Enter number of elements (sorted): ");


scanf("%d", &n);

printf("Enter sorted elements: ");


for(int i = 0; i< n; i++)
scanf("%d", &arr[i]);

printf("Enter key to search: ");


scanf("%d", &key);

pos = binarySearch(arr, n, key);

if(pos != -1)
printf("Element found at index %d\n", pos);
else
printf("Element not found\n");

return 0;
}
Output:

[Link] Search with recursive function (write in observation)


#include <stdio.h>

int binarySearchRec(int arr[], int low, int high, int key) {


if(low > high)
return -1;

int mid = (low + high) / 2;


if(arr[mid] == key)
return mid;
else if(arr[mid] < key)
return binarySearchRec(arr, mid + 1, high, key);
else
return binarySearchRec(arr, low, mid - 1, key);
}

int main() {
int arr[50], n, key, pos;

printf("Enter number of elements (sorted): ");


scanf("%d", &n);

printf("Enter sorted elements: ");


for(int i = 0; i< n; i++)
scanf("%d", &arr[i]);

printf("Enter key to search: ");


scanf("%d", &key);

pos = binarySearchRec(arr, 0, n - 1, key);

if(pos != -1)
printf("Element found at index %d\n", pos);
else
printf("Element not found\n");

return 0;
}
Output:

[Link] (write in Record)


Algorithm:
Step 1: read the list elements
Step 2: for(i = 0; i < n - 1; i++) {
step 3: for(j = 0; j < n - i - 1; j++) {
step 4: if(a[j] > a[j + 1]) { // swap if elements are in wrong order
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp; } } }
Step 5: print the sorted elements

/*C program to sort the given array elements using bubble sort */
/**************************************************************/
#include<stdio.h>
int main( )
{
int a[100], n, i, j, temp;
printf("Enter Number of elements in array: \n");
scanf("%d", &n);
printf("Enter %d Array Elements:\n",n);
for(i=0;i<n; i++)
scanf("%d", &a[i]);
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("Sorted order of given elements is:\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
printf("\n");
return 0;
}
Output:

Enter Number of elements in array:


5
Enter 5 Array Elements:
42713
Sorted order of given elements is:
1 2 3 4 7

[Link] sort with functions (write in Record)


#include <stdio.h>

void bubbleSort(int arr[], int n) {


for(int i = 0; i< n - 1; i++) {
for(int j = 0; j < n - i - 1; j++) {
if(arr[j] >arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}

int main() {
int arr[50], n;

printf("Enter number of elements: ");


scanf("%d", &n);

printf("Enter elements: ");


for(int i = 0; i< n; i++)
scanf("%d", &arr[i]);
bubbleSort(arr, n);

printf("Sorted array: ");


for(int i = 0; i< n; i++)
printf("%d ", arr[i]);

return 0;
}
Output:

[Link] sort with recursion (write in observation)


#include <stdio.h>

void bubbleSortRec(int arr[], int n) {


if(n == 1)
return;

for(int i = 0; i< n - 1; i++) {


if(arr[i] >arr[i+1]) {
int temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
}
}

bubbleSortRec(arr, n - 1);
}

int main() {
int arr[50], n;

printf("Enter number of elements: ");


scanf("%d", &n);

printf("Enter elements: ");


for(int i = 0; i< n; i++)
scanf("%d", &arr[i]);

bubbleSortRec(arr, n);

printf("Sorted array: ");


for(int i = 0; i< n; i++)
printf("%d ", arr[i]);

return 0;
}
Output:
[Link] sort (write in Record)

Algorithm:
The algorithm consists of two main loops and the swap operation.
Step 1: Read the elements
Step 2: Outer Loop (Passes)
 Iterate from the first element (index i=0) up to the second to last element (index i <
n-1) of the array, where n is the total number of elements.
 This loop divides the array into two parts: a sorted subarray (to the left of i) and an
unsorted subarray (from i to the end).
 In each pass i, we find the smallest element in the unsorted subarray A[i..n-1].
Step3: Inner Loop (Finding the Minimum)
 Inside the outer loop, initialize a variable, say min_index, to the starting index of the
unsorted part, i. This assumes the current element A[i] is the minimum.
 Iterate from the next element (j = i+1) up to the last element (j < n) of the array.
 Compare the element A[j] with the element at the current minimum index
A[min_index].
 If A[j] is smaller than A[min_index], update min_index to j.
 After the inner loop finishes, min_index will hold the index of the smallest element
in the unsorted subarray A[i..n-1].
Step 4: Swap
 Swap the element at the current position A[i] with the smallest element found at
A[min_index].
 This effectively moves the smallest element from the unsorted part to its correct
position in the sorted part.
Step 5: print the sorted elements

/*C program to sort the given array elements using


Selection sort. */
/
***********************************************************
******/
#include<stdio.h>
int main( )
{
int a[100], n, i, j, temp, min;
printf("Enter Number of elements in array: \n");
scanf("%d", &n);
printf("Enter %d Array Elements:\n", n);
for(i=0;i<n;i++)
scanf("%d", &a[i]);
for(i=0;i<n-1;i++)
{
min=i;
for(j=i+1;j<n;j++)
{
if(a[min]>a[j])
{
min=j;
}
}
if(min!=i)
{
temp=a[i];
a[i]=a[min];
a[min]=temp;
}
}
printf("Sorted order of given elements is:\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
printf("\n");
return 0;
}
Output:

Enter Number of elements in array:


5
Enter 5 Array Elements:
52618
Sorted order of given elements is:
1 2 5 6 8

[Link] sort with functions (write in Record)

#include <stdio.h>

void selectionSort(int arr[], int n) {


for(int i = 0; i< n - 1; i++) {
int minIndex = i;

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


if(arr[j] <arr[minIndex])
minIndex = j;
}

int temp = arr[i];


arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}

int main() {
int arr[50], n;

printf("Enter number of elements: ");


scanf("%d", &n);

printf("Enter elements: ");


for(int i = 0; i< n; i++)
scanf("%d", &arr[i]);

selectionSort(arr, n);

printf("Sorted array: ");


for(int i = 0; i< n; i++)
printf("%d ", arr[i]);

return 0;
}
Output:

[Link] sort with recursion (write in observation)

#include <stdio.h>

void selectionSortRec(int arr[], int start, int n) {


if(start == n - 1)
return;

int minIndex = start;


for(int i = start + 1; i< n; i++) {
if(arr[i] <arr[minIndex])
minIndex = i;
}

int temp = arr[start];


arr[start] = arr[minIndex];
arr[minIndex] = temp;

selectionSortRec(arr, start + 1, n);


}

int main() {
int arr[50], n;

printf("Enter number of elements: ");


scanf("%d", &n);

printf("Enter elements: ");


for(int i = 0; i< n; i++)
scanf("%d", &arr[i]);

selectionSortRec(arr, 0, n);

printf("Sorted array: ");


for(int i = 0; i< n; i++)
printf("%d ", arr[i]);

return 0;
}
Output:

[Link] arrays to functions (write in observation)

#include <stdio.h>

// Function to display elements of the array


void display(int arr[], int n) {
int i;
printf("Array elements are:\n");
for(i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}

// Function to find sum of array elements


int sum(int arr[], int n) {
int i, s = 0;
for(i = 0; i < n; i++) {
s += arr[i];
}
return s;
}

int main() {
int a[100], n, i;

printf("Enter number of elements: ");


scanf("%d", &n);

printf("Enter %d elements:\n", n);


for(i = 0; i < n; i++) {
scanf("%d", &a[i]);
}

// Passing array to functions


display(a, n);

printf("Sum of elements = %d\n", sum(a, n));

return 0;
}
Output:

You might also like