11.28 Tutorial7
intro-to-computer-science-gtiit-tutorial-07-2024.pdf
Tutorial 6: Algorithmic Problems, Input/Output, argc
-
Design and implement a program in C
That receives as input from standard input, a positive integer numbern
, and prints out the list of the firstn
natural numbers, indicating which are prime numbers, and which are composite numbers.- The prime numbers must be highlighted in green, and the composite numbers in red.
- Number 1 should be left with the default color.
#include <stdio.h> #define GREEN "\x1b[32m" #define RED "\x1b[31m" #define DEFAULT "\x1b[37m" int main() { int number; scanf("%d", &number); printf("1\n"); for (int i = 2; i <= number; i++) { int divisors = 0; for (int j = 3; j < i; j++) { if (i % j == 0) divisors++; } if (divisors > 0) { printf("%s", RED); // Composite numbers in red } else { printf("%s", GREEN); // Prime numbers in green } printf("%d\n", i); // Print the number } printf("%s", DEFAULT); // Reset color to default return 0; }
-
Design and implement a program in C
That receives as input from standard input, a positive integer numbern
, and prints out the number in base 2, i.e., as a sequence of 0s and 1s.#include <stdio.h> #include <math.h> int main() { int input_number; scanf("%d", &input_number); int exponent = 0; // Determine the largest exponent such that 2^exponent <= input_number while (pow(2, exponent) <= input_number) { exponent++; } exponent--; // Adjust to the correct exponent // Iterate from the largest exponent down to 0 for (int i = exponent; i >= 0; i--) { if (input_number >= pow(2, i)) { input_number -= pow(2, i); printf("1"); // Print '1' for binary representation } else { printf("0"); // Print '0' for binary representation } } return 0; }
-
Design and implement a program in C
That receives as input from standard input, a sequence of 0s and 1s (a sequence of characters) representing a binary number, and prints out the corresponding number in base 10.Method 1:
Easy to comprehend, but we need input the binary digit reversely
#include <stdio.h> #include <math.h> #define LINEBREAK '\n' int main() { int currDigit; int digits = 0; int result = 0; currDigit = getchar(); while (currDigit != LINEBREAK) { if(currDigit == '1') { result += pow(2,digits); } digits++; currDigit = getchar(); } printf("%d\n", result); return 0; }
Method 2:
Hard to comprehend
#include <stdio.h> int main() { int result = 0; char currDigit; while ((currDigit = getchar()) != '\n') { result = result * 2; if (currDigit == '1') { result += 1; } } printf("%d\n", result); return 0; }
Method 3:
Use array
#include <stdio.h> #define MAX_BITS 64 int main() { int bits[MAX_BITS]; int used_bits = 0; int current_bit = getchar(); while (current_bit != '\n') { bits[used_bits] = current_bit; used_bits++; current_bit = getchar(); } int result = 0; for (int i = 0; i < used_bits; i++) { if (bits[i] == '1') { int power_of_2 = 1; for (int j = 0; j < used_bits - (i + 1); j++) { power_of_2 *= 2; } result += power_of_2; } } printf("%d\n", result); return 0; }
-
Design and implement a program in C
That receives as input from standard input, a positive integer numbern
(the number of inputs that follow), followed byn
integer numbersx1, …, xn
, computes the sumx1 + x2 + … + xn
, and outputs it on standard output.#include <stdio.h> int main() { int currNumber; int result = 0; while (scanf("%d", &currNumber) > 0) { result += currNumber; } printf("%d\n", result); return 0; }
-
Design and implement a program in C
That receives as input from standard input, a positive integer numbern
(the number of inputs that follow), followed byn
integer numbersx1, …, xn
, and computes the median ofx1, …, xn
. The result should be outputted on standard output.#include <stdio.h> int main() { unsigned digits; // Number of elements to process, positive scanf("%d", &digits); int bits[digits]; for (int i = 0; i < digits; i++) { scanf("%d", &bits[i]); } int low_position, up_position; int low_limit = 0; int up_limit = digits - 1; // Iterate towards the center of the array while (low_limit < up_limit - 1) { low_position = low_limit; up_position = up_limit; // Find the smallest and largest elements in the current segment for (int i = low_limit; i <= up_limit; i++) { if (bits[low_position] > bits[i]) { low_position = i; } if (bits[up_position] < bits[i]) { up_position = i; } } // Swap the smallest element with the element at low_limit int temp = bits[low_limit]; bits[low_limit] = bits[low_position]; bits[low_position] = temp; // Swap the largest element with the element at up_limit int temp2 = bits[up_limit]; bits[up_limit] = bits[up_position]; bits[up_position] = temp2; low_limit++; up_limit--; } int result; // Calculate the result based on the final two elements if (bits[low_limit] == bits[up_limit]) { result = bits[low_limit]; } else { result = (bits[low_limit] + bits[up_limit]) / 2; } printf("The median is %d", result); return 0; }
-
Design and implement a program in C
That receives as input from standard input, a string of characters, and outputs each character with its corresponding frequency (number of times it appears in the input string).- Only characters with positive frequencies should be printed out.
- The characters with a maximum frequency must be highlighted in green.
- The characters with a minimum (positive) frequency should be highlighted in red.
#include<stdio.h> #define red "\e[31m" #define green "\e[32m" #define defaul "\e[39m" int main() { char sequence[1024]; // Store the sequence of characters int samenumber[1024]; // Store the frequency of each character char samech[1024]; // Store unique characters corresponding to their frequencies // Initialize the character count int digits = 0; // Read the first character from input char currentch = getchar(); while (currentch != EOF) { // If the character is between 'A' and 'Z' or 'a' and 'z', add it to the sequence if ((currentch >= 'A' && currentch <= 'Z') || (currentch >= 'a' && currentch <= 'z')) { sequence[digits] = currentch; digits++; } // Read the next character currentch = getchar(); } // Track the maximum and minimum frequency of characters and their positions int maxchar = 1; int minchar = 1; int maxposition, minposition; // l is the index for the samenumber and samech arrays int l = 0; // Iterate through the sequence to count occurrences of each unique character for (int j = 0; j < digits; j++) { int samechar = 0; int flag = 0; // Flag to check if the character has been counted before // Check if the current character has already been processed for (int p = 0; p < j; p++) { if (sequence[j] == sequence[p]) { flag = 1; } } // If the character is unique, count its occurrences if (flag == 0) { samech[l] = sequence[j]; // Store the unique character in the array // Count how many times the current character appears in the sequence for (int k = 0; k < digits; k++) { if (sequence[j] == sequence[k]) { samechar++; } } // Store the frequency of the unique character samenumber[l] = samechar; l++; // Update the maximum and minimum character counts and their positions if (samechar > maxchar) { maxchar = samechar; maxposition = j; } if (samechar < minchar) { minchar = samechar; minposition = j; } } } // Display the character frequencies for (int n = 0; n < l; n++) { // If the character has the highest frequency, print in red if (maxchar == samenumber[n]) printf("%sThe character \"%c\" has %d occurrences\n%s", red, samech[n], samenumber[n], defaul); // If the character has the lowest frequency, print in green else if (minchar == samenumber[n]) printf("%sThe character \"%c\" has %d occurrences\n%s", green, samech[n], samenumber[n], defaul); // Print other characters in the default color else printf("The character \"%c\" has %d occurrences\n", samech[n], samenumber[n]); } return 0; }
-
Design and implement a program in C
That receives as input from standard input, a positive numbern
in the interval [0,127], and a string of characters, and generates (and prints out) a new string where every character in the input string is replaced by the corresponding character “left shifted”n
times (e.g., ifn
is 3, the character with ASCII code 53 will be replaced by the character with ASCII code 50).Use modulo if the encoding goes below 0, to always get a code in the range [0,127].
#include<stdio.h> int main() { int n; int ch, newch; do { printf("Please enter a number n between [0,127]:"); scanf("%d", &n); } while(n < 0 || n > 127); ch = getchar(); while(ch != EOF) { newch = ch - n; if(newch < 0) newch %= 128; printf("%c", newch); ch = getchar(); } return 0; }
-
Write a program
That reads a positive integer from standard input and checks if it is a prime number. If the program is called with parameters, it must print an error message (in red) indicating that the input is expected from standard input, and terminate.#include <stdio.h> // Function to check if a number is prime int isPrime(int number) { if (number <= 1) return 0; // 0 and 1 are not prime if (number == 2) return 1; // 2 is the only even prime number if (number % 2 == 0) return 0; // Exclude even numbers // Check for factors up to the square root of the number for(int i = 3; i * i <= number; i += 2) { if(number % i == 0) return 0; } return 1; } int main(int argc) { // Check if any command-line arguments are provided if(argc > 1) { // Print error message in red using ANSI escape codes printf("\033[31mError: This program expects input from standard input.\033[0m\n"); return 1; // Terminate with error code } int n; // Prompt the user for input printf("Enter a positive integer: "); // Read input from standard input if(scanf("%d", &n) != 1) { // Check if input is an integer printf("\033[31mError: Invalid input. Please enter a positive integer.\033[0m\n"); return 1; } // Additional validation: ensure n is positive if(n <= 0) { printf("\033[31mError: Please enter a positive integer.\033[0m\n"); return 1; } // Check if the number is prime if(isPrime(n)) { printf("%d is a prime number.\n", n); } else { printf("%d is not a prime number.\n", n); } return 0; // Successful termination }