KEMBAR78
C Logic Building Programs-2 | PDF | Integer (Computer Science) | Mathematics
0% found this document useful (0 votes)
22 views15 pages

C Logic Building Programs-2

The document provides an overview of essential C programming concepts, including data types, variables, operators, control structures, functions, arrays, and pointers. It includes example programs that demonstrate logic-building in C, such as finding the largest of three numbers, checking for prime numbers, reversing strings, calculating factorials, and more. Additional examples cover topics like sorting arrays, checking palindromes, calculating GCD, and counting character frequencies.

Uploaded by

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

C Logic Building Programs-2

The document provides an overview of essential C programming concepts, including data types, variables, operators, control structures, functions, arrays, and pointers. It includes example programs that demonstrate logic-building in C, such as finding the largest of three numbers, checking for prime numbers, reversing strings, calculating factorials, and more. Additional examples cover topics like sorting arrays, checking palindromes, calculating GCD, and counting character frequencies.

Uploaded by

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

To help you with C basics and logic-building programs, I'll provide an overview of

essential C
programming concepts and include some example programs that focus on building
logic.

C Basics
Data Types and Variables:

Data Types: int, char, float, double, etc.


Variables: Named storage locations in memory for holding data. Declared with a
type, e.g., int num;.
Operators:

Arithmetic Operators: +, -, *, /, %
Relational Operators: ==, !=, >, <, >=, <=
Logical Operators: && (AND), || (OR), ! (NOT)
Assignment Operators: =, +=, -=, *=, /=, %=
Control Structures:

Conditional Statements: if, else if, else


Loops: for, while, do-while
Switch Statement: For multi-way branching
Functions:

Reusable blocks of code defined with a return type, name, and parameters.
Example: int add(int a, int b) { return a + b; }
Arrays:

A collection of elements of the same data type.


Declared as int arr[5]; for an array of 5 integers.
Pointers:

Variables that store memory addresses.


Declared with an asterisk, e.g., int *ptr;
Logic-Building Programs
Here are a few example programs to help you practice logic building in C:

1. Program to Find the Largest of Three Numbers


c
Copy code
#include <stdio.h>

int main() {
int num1, num2, num3;

printf("Enter three numbers: ");


scanf("%d %d %d", &num1, &num2, &num3);

if (num1 >= num2 && num1 >= num3) {


printf("The largest number is: %d\n", num1);
} else if (num2 >= num1 && num2 >= num3) {
printf("The largest number is: %d\n", num2);
} else {
printf("The largest number is: %d\n", num3);
}

return 0;
}
Explanation:
The program reads three integers from the user.
It uses if-else statements to compare the numbers and determine the largest.
2. Program to Check if a Number is Prime
c
Copy code
#include <stdio.h>

int main() {
int num, i, flag = 0;

printf("Enter a positive integer: ");


scanf("%d", &num);

if (num <= 1) {
printf("%d is not a prime number.\n", num);
return 0;
}

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


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

if (flag == 0) {
printf("%d is a prime number.\n", num);
} else {
printf("%d is not a prime number.\n", num);
}

return 0;
}
Explanation:

The program checks if a number is prime by dividing it by all numbers from 2 to


num/2.
If it's divisible by any of these numbers, it's not prime.
3. Program to Reverse a String
c
Copy code
#include <stdio.h>
#include <string.h>

int main() {
char str[100], temp;
int i, j;

printf("Enter a string: ");


scanf("%s", str);

j = strlen(str) - 1;

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


temp = str[i];
str[i] = str[j];
str[j] = temp;
}
printf("Reversed string: %s\n", str);

return 0;
}
Explanation:

The program takes a string as input and reverses it by swapping characters from the
ends towards the middle.
4. Program to Calculate Factorial Using a Loop
c
Copy code
#include <stdio.h>

int main() {
int num, i;
unsigned long long factorial = 1;

printf("Enter a positive integer: ");


scanf("%d", &num);

if (num < 0) {
printf("Factorial is not defined for negative numbers.\n");
} else {
for (i = 1; i <= num; i++) {
factorial *= i;
}
printf("Factorial of %d = %llu\n", num, factorial);
}

return 0;
}
Explanation:

This program calculates the factorial of a given number using a for loop.
It multiplies all numbers from 1 to the input number.
Tips for Logic Building in C
Understand the Problem: Clearly define the problem before writing code.
Break Down the Problem: Divide the problem into smaller, manageable tasks.
Write Pseudocode: Draft the logic in plain language to organize your thoughts.
Test with Different Inputs: Ensure your logic handles various cases, including edge
cases.
Practice Regularly: The more problems you solve, the better you'll understand
different logic patterns.
If you need more specific notes or have questions on particular concepts, feel free
to ask!

You said:
More C examples?
ChatGPT said:
ChatGPT
Sure, here are more examples of C programs to help you further build your logic and
understanding of C programming. These examples cover a variety of topics including
loops, arrays, strings, and recursion.
5. Program to Find the Fibonacci Series up to n Terms
The Fibonacci series is a sequence where each number is the sum of the two
preceding ones, usually starting with 0 and 1.

c
Copy code
#include <stdio.h>

int main() {
int n, t1 = 0, t2 = 1, nextTerm;

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


scanf("%d", &n);

printf("Fibonacci Series: %d, %d", t1, t2);

for (int i = 3; i <= n; ++i) {


nextTerm = t1 + t2;
printf(", %d", nextTerm);
t1 = t2;
t2 = nextTerm;
}

printf("\n");
return 0;
}
Explanation:

This program calculates the Fibonacci series up to n terms.


The first two terms (t1 and t2) are initialized as 0 and 1. The next terms are
calculated as the sum of the two preceding terms.
6. Program to Sort an Array in Ascending Order
c
Copy code
#include <stdio.h>

int main() {
int n, i, j, temp;
int arr[100];

printf("Enter number of elements: ");


scanf("%d", &n);

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


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

// Bubble sort algorithm


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

You said:
Sure, here are more examples of C programs to help you further build your logic and
understanding of C programming. These examples cover a variety of topics including
loops, arrays, strings, and recursion.
ChatGPT said:
ChatGPT
Let's continue with more examples of C programs that cover various fundamental
topics, including loops, arrays, strings, and recursion. These examples are
designed to help you develop problem-solving skills and deepen your understanding
of C programming.

6. Program to Sort an Array in Ascending Order (Bubble Sort Algorithm)


c
Copy code
#include <stdio.h>

int main() {
int n, i, j, temp;
int arr[100];

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


scanf("%d", &n);

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


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

// Bubble sort algorithm


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

printf("Sorted array in ascending order:\n");


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

printf("\n");
return 0;
}
Explanation:

This program sorts an array of integers in ascending order using the bubble sort
algorithm.
It repeatedly steps through the list, compares adjacent elements, and swaps them if
they are in the wrong order.
7. Program to Find the Factorial of a Number Using Recursion
c
Copy code
#include <stdio.h>

// Function to calculate factorial using recursion


long long factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n -

2/2

You said:
Sure, here are more examples of C programs to help you further build your logic and
understanding of C programming. These examples cover a variety of topics including
loops, arrays, strings, and recursion.
ChatGPT said:
ChatGPT
Let's continue with additional C programming examples that cover various
fundamental concepts. These examples will help you enhance your logic-building
skills and deepen your understanding of different C programming topics like loops,
arrays, strings, and recursion.

6. Program to Sort an Array in Ascending Order (Bubble Sort Algorithm)


c
Copy code
#include <stdio.h>

int main() {
int n, i, j, temp;
int arr[100];

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


scanf("%d", &n);

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


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

// Bubble sort algorithm


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

printf("Sorted array in ascending order:\n");


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

printf("\n");
return 0;
}
Explanation:

The program sorts an array of integers in ascending order using the bubble sort
algorithm.
It repeatedly steps through the array, compares adjacent elements, and swaps them
if they are in the wrong order.
7. Program to Find the Factorial of a Number Using Recursion
c
Copy code
#include <stdio.h>

// Function to calculate factorial using recursion


long long factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}

int main() {
int num;

printf("Enter a positive integer: ");


scanf("%d", &num);

if (num < 0) {
printf("Factorial is not defined for negative numbers.\n");
} else {
printf("Factorial of %d = %lld\n", num, factorial(num));
}

return 0;
}
Explanation:

This program calculates the factorial of a given number using a recursive function.
The factorial function calls itself with decremented values of n until it reaches
the base case (n == 0).
8. Program to Check if a String is a Palindrome
A palindrome is a string that reads the same backward as forward.

c
Copy code
#include <stdio.h>
#include <string.h>

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

printf("Enter a string: ");


scanf("%s", str);

length = strlen(str);

for (i = 0; i < length / 2; i++) {


if (str[i] != str[length - i - 1]) {
flag = 1;
break;
}
}
if (flag == 0) {
printf("%s is a palindrome.\n", str);
} else {
printf("%s is not a palindrome.\n", str);
}

return 0;
}
Explanation:

The program checks if a string is a palindrome by comparing characters from the


beginning and end moving towards the center.
If any characters don't match, the string is not a palindrome.
9. Program to Find the GCD (Greatest Common Divisor) of Two Numbers Using Euclidean
Algorithm
c
Copy code
#include <stdio.h>

// Function to calculate GCD using the Euclidean algorithm


int gcd(int a, int b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}

int main() {
int num1, num2;

printf("Enter two integers: ");


scanf("%d %d", &num1, &num2);

printf("GCD of %d and %d is %d\n", num1, num2, gcd(num1, num2));

return 0;
}
Explanation:

This program calculates the GCD of two numbers using the Euclidean algorithm.
The gcd function uses recursion to find the GCD by repeatedly applying the modulus
operation.
10. Program to Count the Frequency of Characters in a String
c
Copy code
#include <stdio.h>
#include <string.h>

int main() {
char str[100];
int freq[256] = {0}; // Frequency array to store character counts
int i;

printf("Enter a string: ");


scanf("%s", str);

// Count frequency of each character


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

// Print characters and their frequencies


printf("Character frequencies:\n");
for (i = 0; i < 256; i++) {
if (freq[i] != 0) {
printf("%c: %d\n", i, freq[i]);
}
}

return 0;
}
Explanation:

This program counts the frequency of each character in a string.


It uses an array freq to store counts of all characters (assuming ASCII
characters).
It iterates over the string and increments the count of each character in the freq
array.
11. Program to Swap Two Numbers Without Using a Temporary Variable
c
Copy code
#include <stdio.h>

int main() {
int a, b;

printf("Enter two integers: ");


scanf("%d %d", &a, &b);

printf("Before swapping: a = %d, b = %d\n", a, b);

a = a + b; // Step 1: Sum of a and b is stored in a


b = a - b; // Step 2: Subtract b from new a to get the original a in b
a = a - b; // Step 3: Subtract new b (original a) from new a to get the
original b in a

printf("After swapping: a = %d, b = %d\n", a, b);

return 0;
}
Explanation:

This program swaps the values of two integers without using a temporary variable.
It uses simple arithmetic operations (addition and subtraction) to swap the
numbers.
12. Program to Find the Sum of Digits of a Number
c
Copy code
#include <stdio.h>

int main() {
int num, sum = 0, remainder;

printf("Enter an integer: ");


scanf("%d", &num);

while (num != 0) {
remainder = num % 10; // Get the last digit
sum += remainder; // Add the last digit to sum
num /= 10; // Remove the last digit
}

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

return 0;
}
Explanation:

The program calculates the sum of the digits of a number by extracting each digit
using the modulus operator and adding them up.
It repeatedly divides the number by 10 to remove the last digit until the number
becomes zero.
These examples should help you further build your understanding and ability to
write logic in C programming. If you have more specific requests or need additional
examples, feel free to ask!

You said:
Sure, here are more examples of C programs to help you further build your logic and
understanding of C programming. These examples cover a variety of topics including
loops, arrays, strings, and recursion.
ChatGPT said:
ChatGPT
Absolutely! Here are more C program examples to help you build your logic and
understanding of fundamental C programming concepts, including loops, arrays,
strings, and recursion.

13. Program to Find the Sum of an Array


This program calculates the sum of all the elements in an array.

c
Copy code
#include <stdio.h>

int main() {
int n, i, sum = 0;
int arr[100];

printf("Enter the number of elements in the array: ");


scanf("%d", &n);

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


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

// Calculate the sum of array elements


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

printf("Sum of the array elements: %d\n", sum);


return 0;
}
Explanation:

The program first reads the size of the array and its elements from the user.
It then calculates the sum of all elements in the array using a loop and prints the
result.
14. Program to Merge Two Arrays into a Third Array
This program merges two arrays into a third array.

c
Copy code
#include <stdio.h>

int main() {
int n1, n2, i, j;
int arr1[50], arr2[50], merged[100];

printf("Enter the number of elements in the first array: ");


scanf("%d", &n1);
printf("Enter %d elements of the first array:\n", n1);
for (i = 0; i < n1; i++) {
scanf("%d", &arr1[i]);
}

printf("Enter the number of elements in the second array: ");


scanf("%d", &n2);
printf("Enter %d elements of the second array:\n", n2);
for (i = 0; i < n2; i++) {
scanf("%d", &arr2[i]);
}

// Merging arrays
for (i = 0; i < n1; i++) {
merged[i] = arr1[i];
}
for (j = 0; j < n2; j++, i++) {
merged[i] = arr2[j];
}

printf("Merged array:\n");
for (i = 0; i < n1 + n2; i++) {
printf("%d ", merged[i]);
}

printf("\n");
return 0;
}
Explanation:

The program first reads two arrays and their sizes from the user.
It then merges the two arrays into a third array and prints the merged result.
15. Program to Find the Length of a String Without Using strlen
This program calculates the length of a string manually.

c
Copy code
#include <stdio.h>
int main() {
char str[100];
int i, length = 0;

printf("Enter a string: ");


scanf("%s", str);

// Calculate length of the string


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

printf("Length of the string: %d\n", length);

return 0;
}
Explanation:

The program reads a string from the user and calculates its length manually using a
loop that iterates until it reaches the null terminator (\0).
16. Program to Check Armstrong Number
An Armstrong number (also known as a narcissistic number) is a number that is equal
to the sum of its own digits raised to the power of the number of digits.

c
Copy code
#include <stdio.h>
#include <math.h>

int main() {
int num, originalNum, remainder, result = 0, n = 0;

printf("Enter an integer: ");


scanf("%d", &num);

originalNum = num;

// Count number of digits


while (originalNum != 0) {
originalNum /= 10;
n++;
}

originalNum = num;

// Compute the sum of nth power of each digit


while (originalNum != 0) {
remainder = originalNum % 10;
result += pow(remainder, n);
originalNum /= 10;
}

if (result == num) {
printf("%d is an Armstrong number.\n", num);
} else {
printf("%d is not an Armstrong number.\n", num);
}
return 0;
}
Explanation:

The program checks whether a number is an Armstrong number by calculating the sum
of each digit raised to the power of the total number of digits.
17. Program to Convert Decimal to Binary
This program converts a decimal number to its binary representation.

c
Copy code
#include <stdio.h>

int main() {
int num, binary[32], i = 0;

printf("Enter a decimal number: ");


scanf("%d", &num);

// Decimal to binary conversion


while (num > 0) {
binary[i] = num % 2;
num = num / 2;
i++;
}

printf("Binary representation: ");


for (int j = i - 1; j >= 0; j--) {
printf("%d", binary[j]);
}

printf("\n");
return 0;
}
Explanation:

The program converts a decimal number to binary by repeatedly dividing the number
by 2 and storing the remainder in an array.
The binary representation is then printed in reverse order.
18. Program to Generate Pascal's Triangle
Pascal's Triangle is a triangular array of binomial coefficients.

c
Copy code
#include <stdio.h>

int main() {
int rows, coef = 1;

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


scanf("%d", &rows);

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


for (int space = 1; space <= rows - i; space++) {
printf(" ");
}

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


if (j == 0 || i == 0) {
coef = 1;
} else {
coef = coef * (i - j + 1) / j;
}
printf("%4d", coef);
}
printf("\n");
}

return 0;
}
Explanation:

This program generates Pascal's Triangle up to a specified number of rows.


Each coefficient is calculated using the binomial coefficient formula.
19. Program to Calculate the Power of a Number Using Recursion
This program calculates the power of a number recursively.

c
Copy code
#include <stdio.h>

// Recursive function to calculate power


int power(int base, int exp) {
if (exp == 0) {
return 1;
} else {
return base * power(base, exp - 1);
}
}

int main() {
int base, exp;

printf("Enter base number: ");


scanf("%d", &base);
printf("Enter exponent: ");
scanf("%d", &exp);

printf("%d^%d = %d\n", base, exp, power(base, exp));

return 0;
}
Explanation:

The program calculates the power of a base number raised to an exponent using a
recursive function.
20. Program to Find the LCM (Least Common Multiple) of Two Numbers
This program finds the least common multiple of two numbers.

c
Copy code
#include <stdio.h>

// Function to calculate GCD


int gcd(int a, int b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}

// Function to calculate LCM


int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}

int main() {
int num1, num2;

printf("Enter two integers: ");


scanf("%d %d", &num1, &num2);

printf("LCM of %d and %d is %d\n", num1, num2, lcm(num1, num2));

return 0;
}
Explanation:

The program calculates the least common multiple (LCM) of two numbers using the
formula LCM(a, b) = (a * b) / GCD(a, b).
These examples provide a wide range of logic-building exercises in C programming,
covering various concepts and techniques. If you have any specific topics or more
examples you want to explore, feel free to ask!

You might also like