0% found this document useful (0 votes)
7 views5 pages

C and Python Programming Examples

c programming solutions

Uploaded by

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

C and Python Programming Examples

c programming solutions

Uploaded by

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

1.

Write a function in C and Python to calculate the Fibonacci sequence up to the


7th term.

#include <stdio.h>

int main(void) {
int term = 7;
printf(" %d ", fibonocci_term(term));
}

int fibonocci_term(int term){


int n1 = 0, n2 = 1;
int i;
int n3;
if(term == 1){
return 0;
}
if(term == 2){
return 1;
}
for (i = 3; i <= term; i++)
{
n3 = n1 + n2;
n1 = n2;
n2 = n3;
}
return n3;
}

2. Write a program in both C and Python to perform bitwise manipulation, such as


checking if a number is even or odd, without using conditional statements.
#include <stdio.h>

int main(){
int num;
int no = 1;
printf("enter a number :");
scanf("%d", & num);

if(num & no == 1){


printf("%d is odd", num);
}
else{
printf("%d is even", num);
}
return 0;
}

OUTPUT
enter a number :7
7 is odd
3. Implement a function in C that uses pointers to reverse an array in place.
Then, write an equivalent function in Python.

#include <stdio.h>
void reverse_array(int numbers[], int length);

int main(){
int nums[12] = {1,3,5,6,7,8,11,22,33,44,55,66};
int num = 12;
int i = 0;
printf("Array contents before reverse is :\n");
for (i = 0; i < num; i++){
printf("%d \n", nums[i]);
}
reverse_array(nums, num);

printf("Array contents after reverse function is called :\n");


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

void reverse_array(int numbers[], int length){


int temp;
int st = 0;
int end = length - 1;
while ( st < end){
temp = numbers[st];
numbers[st] = numbers[end];
numbers[end] = temp;
st++;
end--;
}
return;
}

OUTPUT
Array contents before reverse is :
1
3
5
6
7
8
11
22
33
44
55
66
Array contents after reverse function is called :
66
55
44
33
22
11
8
7
6
5
3
1

4. Implement the Armstrong number check using both a recursive and an iterative
approach in both C and Python.

[Link]

5. Write a program in C and Python to compare two strings without using string
library functions.
#include <stdio.h>
int my_strcmp(char *s1, char *s2);
int main(){
char str1[] = "aello";
char str2[] = "abcd";

int m = my_strcmp(str1, str2);


printf("%d", m);

}
int my_strcmp(char *s1, char *s2){
while (*s1 == *s2){
s1++;
s2++;

if(*s1 == '\0')
return 0;
}

return *s1 - *s2;


}

OUTPUT
3

8 .Implement a program in C to count the number of vowels in a given string


using pointers. Write an equivalent function in Python without using the
count method.

9. Check whether a given number is super prime? By using C and Python ( For example
7331 is super prime because 7331 is prime, 733 is prime, 73 is prime,7 is prime, Such
numbers are called super prime)

// super prime
#include <stdio.h>
#include <math.h>

int is_prime(int n);

int main(){
int num = 120;
int flag = 0;
while( num > 0){
if(is_prime(num) == 0){
flag = 1;
break;
}
num = num / 10;
}

if(flag == 1){
printf("number is not super prime");
}
else
printf("number is super prime");
}

int is_prime(int n){


int i = 0;
int flag = 0;
for (i = 2; i < sqrt(n); i ++){

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

10. Implement the Sieve of Eratosthenes algorithm in both C and Python to generate
prime numbers up to a large value
[Link]

19. Write a program in both C and Python to implement a recursive function that
calculates the factorial of a number. Compare the memory usage and execution speed
of both programs when calculating large factorials (e.g., factorial of 100). Why might C
handle this task differently from Python, and how does memory management in each
language affect the result?

#include <stdio.h>
int main()
{
int num = 5;
printf("%d", factorial(num));
}

int factorial(int num){


if (num == 1)
return 1;

return num * factorial (num - 1);


}

Common questions

Powered by AI

Reversing an array in place using pointers involves iteratively swapping elements from the start and end of the array moving towards the center. In C, two pointers are used: one starting from the beginning and the other from the end. They progressively swap elements until they meet. In Python, this can be translated into a swapping routine within a loop, using list indices or Python's built-in capabilities which inherently handle lists like arrays. Python's flexibility allows list reversal with simple slicing or the `reverse` method, while the C version requires explicit pointer manipulation .

The C implementation uses an iterative approach with explicit loop and variable management to calculate the Fibonacci sequence. It uses simple variables for state, a for loop to iterate through terms, and conditional checks to handle initial terms independently. Python's implementation, on the other hand, tends to be more concise, often using recursion or list comprehensions. Python's syntax allows for less verbose code, and dynamic typing provides greater flexibility without explicit type declarations .

Recursive and iterative approaches differ primarily in their execution style. A recursive approach breaks the problem into smaller parts that replicate the original task, by recursively summing the powers of digits. The iterative method uses standard loops to achieve the same sum without function overhead. Recursion can add overhead due to stack usage and might be slower for larger numbers, while iteration typically uses less memory and is more efficient. However, recursion can be more intuitive and easier to implement for mathematical problems like Armstrong checks, despite potential inefficiencies .

In C, pointers enable direct manipulation of string data within memory, allowing a program to increment through a character array and identify vowels by checking ASCII values directly. This approach leverages pointer arithmetic for efficient iteration. In Python, character iteration handles strings as iterable objects, potentially using list comprehensions or generator expressions for the same purpose. Python abstracts memory handling with built-in functions and lacks explicit pointer usage, focusing instead on higher-level string manipulation methods .

Bitwise operations directly manipulate binary digits of numbers, where the least significant bit (LSB) indicates evenness. For an integer, a bitwise AND with 1 (num & 1) yields 0 if the number is even and 1 if odd. This exploits the fundamental property that even numbers have an LSB of 0 in binary form, while odd numbers have an LSB of 1, allowing the determination of parity without if-else structures .

Without string library functions, comparison is performed by iterating over each character of both strings simultaneously. Each pair of corresponding characters from the two strings is compared using their ASCII values. When a difference is found or if one string ends before the other, a conclusion is reached based on which character has a higher ASCII value. This approach manually replicates the operation performed by standard library functions through low-level handling of each character, making explicit comparisons .

C is lower-level and allows closer-to-hardware operations, resulting in faster execution speeds due to static typing and less overhead—memory is manually managed, and recursive calls are stored precisely in stack memory. Python, being high-level, manages memory dynamically, introducing overhead from garbage collection and type-checking that C doesn't encounter. Python requires more memory due to its stack frames and object models. C's need for explicit memory management makes it more efficient for recursion-based tasks like computing large factorials, despite its complexity and potential for errors .

Super prime numbers are those that remain prime as digits are successively removed from the end. In C, determining if a number is super prime involves iteratively checking sub-numbers for primality as digits are truncated from the right. This involves dividing the number by 10 in a loop, using an `is_prime` function to test each smaller number. As soon as a non-prime truncated number is found, the loop exits, establishing the original number as non-super prime. If all truncated numbers are primes, then the original number is confirmed as super prime .

C's manual memory management allows for efficient use of resources, with minimal overhead and direct memory access that speeds up large computations like the Sieve of Eratosthenes. This gives it an advantage in resource-constrained environments. However, it also requires careful handling to avoid errors like memory leaks or segmentation faults, which are less of a concern in Python due to automatic garbage collection. Python’s ease of use and error management make it more suitable for rapid development, although at the cost of performance, particularly in memory-intensive tasks. The trade-off between speed and safety is a key consideration .

The Sieve of Eratosthenes algorithm begins by creating a boolean array marking all numbers as potential primes. Starting from the first prime, 2, the algorithm iteratively marks multiples of each prime number as non-prime, ensuring each number is processed once. In Python, efficient use of list comprehensions and range functions accelerates the execution. This method reduces time complexity to O(n log log n) compared to basic iteration, which checks each number individually up to its square root, exhibiting O(n√n) complexity for every number, making the sieve much more efficient .

You might also like