Skip to main content

Featured

C Program to Solve Two Sum Using Brute Force (With Algorithm & Output)

 Introduction The Two Sum problem is a popular coding interview question where we must find two indices of an array whose values add up to a given target. This program demonstrates a simple brute-force solution in C using nested loops and dynamic memory allocation. Problem Statement Given an integer array and a target value, return the indices of the two numbers such that they add up to the target. Each input has exactly one solution, and the same element cannot be used twice. The result should return the indices, not the values. If no solution exists, return NULL.  Algorithm / Logic Explanation Start the program. Traverse the array using a loop from index 0 to numsSize - 1 . Inside this loop, use another loop starting from i + 1 to numsSize - 1 . For every pair (i, j) , check if nums[i] + nums[j] == target . If condition becomes true: Allocate memory for 2 integers using malloc() . Store indices i and j . Set returnSize = 2 . Return the result poi...

C Program to Find the Second Last Character of a String

Second Last Character of String in C (scanf) - No Newline Handling

✅ C Program to Find the Second Last Character of a String (Clean scanf Version)

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

int main() {
    char str[100];

    printf("Enter a string: ");
    scanf("%[^\n]", str);  // Reads until newline, no need to handle '\n'

    int len = strlen(str);

    if (len < 2) {
        printf("String is too short to have a second last character.\n");
    } else {
        printf("Second last character: %c\n", str[len - 2]);
    }

    return 0;
}
  

๐Ÿ“˜ Explanation:

This program reads a string from the user using scanf("%[^\n]"), which captures input until the newline character but does not include it in the string.

  • It directly uses strlen() to find the length of the input.
  • If the string has fewer than 2 characters, a warning is displayed.
  • Otherwise, str[len - 2] gives the second last character.
  • No need for additional newline removal logic in this version.

๐Ÿงพ Sample Output:

Enter a string: Hello World
Second last character: l

Enter a string: H
String is too short to have a second last character.
  

๐Ÿ”‘ Keywords:

scanf string C, second last character, strlen example, no newline handling, C string logic, interview question, clean code C

๐Ÿ“Œ Hashtags:

#CProgramming #StringIndexing #strlen #scanfInput #InterviewCode #BeginnerFriendly

๐Ÿ” Search Description:

Clean and efficient C program to find the second last character in a string using scanf without newline handling. Simple logic using strlen. Great for C beginners.

Comments

Popular Posts

๐ŸŒ™