Program 11 - CSU1128 - CSE 2026 - Shoolini University

Program to take input of a sentence, write it in the file, convert it in both lower and upper case and write them both to the file again

Code

                    
/*
 * -----------------------------------------------------------
 * Logic Building with Computer Programming (CSU1128P)
 * Instructor: Abdullahi Adem | Author: Divya Mohan
 * 
 * This code is a part of the educational initiative by dmj.one
 * with aim of empowering and inspiring learners in the field of
 * Computer Science and Engineering through the respective courses.
 * 
 * (c) 2022, Divya Mohan for dmj.one. All rights reserved.
 * -----------------------------------------------------------
 */

#include <stdio.h>
#include <ctype.h>
int main()
{
    printf("\n\n-- This program takes input of a sentence, writes it in the file, converts it in both lower and upper case and write them both to the file again. --\n\n");
    FILE *f; // file pointer

    // open the file in write mode
    f = fopen("file.txt", "a");
    if (f == NULL)
    {
        printf("Error opening file!\n");
        return 1;
    }

    char s[100]; // array to store the user's input

    printf("Enter a string: ");
    fgets(s, sizeof(s), stdin); // read the string from the user using fgets

    printf("Original: %s", s);     // print the original string to the screen
    fprintf(f, "Original: %s", s); // write the original string to the file

    // write the converted strings to the file and print them to the screen
    printf("Upper-case: ");
    fprintf(f, "Upper-case: ");
    for (int i = 0; s[i] != '\0'; i++)
    {
        printf("%c", toupper(s[i])); // print the upper-case character to the screen
        fputc(toupper(s[i]), f);     // write the upper-case character to the file
    }
    printf("\n");
    fprintf(f, "\n");

    printf("Lower-case: ");
    fprintf(f, "Lower-case: ");
    for (int i = 0; s[i] != '\0'; i++)
    {
        printf("%c", tolower(s[i])); // print the lower-case character to the screen
        fputc(tolower(s[i]), f);     // write the lower-case character to the file
    }
    printf("\n");
    fprintf(f, "\n");

    // close the file
    fclose(f);

    return 0;
}                    
                

Output

-- This program takes input of a sentence, writes it in the file, converts it in both lower and upper case and write them both to the file again. --

Enter a string: This is a demo string.
Original: This is a demo string.
Upper-case: THIS IS A DEMO STRING.

Lower-case: this is a demo string.