Search This Blog

Showing posts with label learn c. Show all posts
Showing posts with label learn c. Show all posts

C Programming Strings

WELCOME BACK TO codejunction.in , In this article, you'll learn to handle strings and its operations in C programming. You'll learn to declare them, initialize them and use them for various I/O operations.


Table of Contents
C strings
How to declare a string?
How to initialize strings?
Read string from the user
Example: scanf() to read string
Example: gets() and puts()
Passing strings to a function
Example: Passing strings to a function
Strings and pointers
Example: Strings and pointers
Commonly used string functions
In C programming, a string is an array of characters terminated with a null character \0.

For example:


"c string"
When compiler encounters a sequence of characters enclosed in the double quotation marks, it appends a null character \0 at the end.


Memory diagram of strings in C programming

How to declare a string?
Before you can work with strings, you need to declare them first. Since string is an array of characters. You declare strings in a similar way like you do with arrays.

If you don't know what arrays are, we recommend you to check C arrays.

Here's how you declare a string:

char s[5];
string declaration in C programming

How to initialize strings?
You can initialize strings in a number of ways.

char c[] = "abcd";

char c[50] = "abcd";

char c[] = {'a', 'b', 'c', 'd', '\0'};

char c[5] = {'a', 'b', 'c', 'd', '\0'};
Initialization of strings in C programming

Read String from the user
You can use the scanf() function to read a string.

The scanf() function reads the sequence of characters until it encounters a whitespace (space, newline, tab etc.).

Example 1:

 scanf() to read a string
#include <stdio.h>
int main()
{
    char name[20];
    printf("Enter name: ");
    scanf("%s", name);
    printf("Your name is %s.", name);
    return 0;
}

Output

Enter name: Dennis Ritchie
Your name is Dennis.
Even though Dennis Ritchie was entered in the above program, only "Ritchie" was stored in the name string. It's because there was a space after Ritche.

How to read a line of text?
You can use gets() function to read a line of string. And, you can use puts() to display the string.

Example 2:


 gets() and puts()
#include <stdio.h>
int main()
{
    char name[30];
    printf("Enter name: ");
    gets(name);     // read string
    printf("Name: ");
    puts(name);    // display string
    return 0;
}
When you run the program, the output will be:

Enter name: Tom Hanks
Name: Tom Hanks
Passing Strings to Function
Strings can be passed to a function in a similar way as arrays. Learn more about passing array to a function.

Example 3:


 Passing string to a Function
#include <stdio.h>
void displayString(char str[]);

int main()
{
    char str[50];
    printf("Enter string: ");
    gets(str);           
    displayString(str);     // Passing string to a function.   
    return 0;
}
void displayString(char str[])
{
    printf("String Output: ");
    puts(str);
}

Strings and Pointers
Similar like arrays, string names are "decayed" to pointers. Hence, you can use pointer with the same name as string to manipulate elements of the string. We recommended you to check C Arrays and Pointers before you check this example:

Example 4: 


Strings and Pointers
#include <stdio.h>

int main(void) {
  char name[] = "Harry Potter";

  printf("%c", *name);     // Output: H
  printf("%c", *(name+1));   // Output: a
  printf("%c", *(name+7));   // Output: o

  char *namePtr;

  namePtr = name;
  printf("%c", *namePtr);     // Output: H
  printf("%c", *(namePtr+1));   // Output: a
  printf("%c", *(namePtr+7));   // Output: o
}

C Programming Arrays

In this article, you will learn to work with arrays. You will learn to declare, initialize and, access array elements with the help of examples.


Table of Contents


C Arrays
How to declate arrays?
How to access array elements?
How to initialize an array?
How to insert elements to an array?
Initialize array during declaration
Example: Arrays
Be careful while using arrays in C
C arrays


An array is a collection of a fixed number of values of a single type. For example: if you want to store 100 integers in sequence, you can create an array for it.

int data[100];
The size and type of arrays cannot be changed after its declaration.


Arrays are of two types:


One-dimensional arrays
Multidimensional arrays (will be discussed in next chapter)


How to declare arrays?


data_type array_name[array_size];
For example,

float mark[5];
Here, we declared an array, mark, of floating-point type and size 5. Meaning, it can hold 5 floating-point values.

Elements of an Array and How to access them?
You can access elements of an array by indices.

Suppose you declared an array mark as above. The first element is mark[0], second element is mark[1] and so on.

C Array declaration 


Few key notes:
Arrays have 0 as the first index not 1. In this example, mark[0]
If the size of an array is n, to access the last element, (n-1) index is used. In this example, mark[4]
Suppose the starting address of mark[0] is 2120d. Then, the next address, a[1], will be 2124d, address of a[2] will be 2128d and so on. It's because the size of a float is 4 bytes.
How to initialize an array?
It's possible to initialize an array during declaration. For example,

int mark[5] = {19, 10, 8, 17, 9};

Another method to initialize array during declaration:

int mark[] = {19, 10, 8, 17, 9};

Initialize an array in C programming

Here,

mark[0] is equal to 19
mark[1] is equal to 10
mark[2] is equal to 8
mark[3] is equal to 17
mark[4] is equal to 9
How to insert and print array elements?
int mark[5] = {19, 10, 8, 17, 9}

// insert different value to third element
mark[3] = 9;

// take input from the user and insert in third element
​scanf("%d", &mark[2]);

// take input from the user and insert in (i+1)th element
scanf("%d", &mark[i]);

// print first element of an array
printf("%d", mark[0]);

// print ith element of an array
printf("%d", mark[i-1]);
Example: C Arrays
// Program to find the average of n (n < 10) numbers using arrays


CODE


#include <stdio.h>
int main()
{
     int marks[10], i, n, sum = 0, average;
     printf("Enter n: ");
     scanf("%d", &n);
     for(i=0; i<n; ++i)
     {
          printf("Enter number%d: ",i+1);
          scanf("%d", &marks[i]);
          sum += marks[i];
     }
     average = sum/n;

     printf("Average = %d", average);

     return 0;
}



OUTPUT


Enter n: 5
Enter number1: 45
Enter number2: 35
Enter number3: 38
Enter number4: 31
Enter number5: 49
Average = 39

Important thing to remember when working with C arrays
Suppose you declared an array of 10 elements. Let's say,

int testArray[10];
You can use the array members from testArray[0] to testArray[9].

If you try to access array elements outside of its bound, let's say testArray[12], the compiler may not show any error. However, this may cause unexpected output (undefined behavior).

C Program to Copy String Without Using strcpy()

WELCOME BACK TO codejunction.in , In this article, you'll learn to copy string without using the library function strcpy().


To understand this example, you should have the knowledge of following C programming topics:

C Programming Arrays
C Programming Strings
C Programming for Loop

You can use the strcpy() function to copy the content of one string to another but, this program copies the content of one string to another manually without using strcpy() function.

Example: Copy String Manually Without Using strcpy()


CODE


#include <stdio.h>
int main()
{
    char s1[100], s2[100], i;

    printf("Enter string s1: ");
    scanf("%s",s1);

    for(i = 0; s1[i] != '\0'; ++i)
    {
        s2[i] = s1[i];
    }

    s2[i] = '\0';
    printf("String s2: %s", s2);

    return 0;
}


OUTPUT



Arrays in C programming with examples

Welcome back to codejunction.in , hope you have a good day.


An array is a group (or collection) of same data types. For example an int array holds the elements of int types while a float array holds the elements of float types.

Why we need Array in C Programming?
Consider a scenario where you need to find out the average of 100 integer numbers entered by user. In C, you have two ways to do this: 1) Define 100 variables with int data type and then perform 100 scanf() operations to store the entered values in the variables and then at last calculate the average of them. 2) Have a single integer array to store all the values, loop the array to store all the entered values in array and later calculate the average.
Which solution is better according to you? Obviously the second solution, it is convenient to store same data types in one single variable and later access them using array index (we will discuss that later in this tutorial).



How to declare Array in C
int num[35];  /* An integer array of 35 elements */
char ch[10];  /* An array of characters for 10 elements */
Similarly an array can be of any data type such as double, float, short etc.

How to access element of an array in C
You can use array subscript (or index) to access any element stored in array. Subscript starts with 0, which means arr[0] represents the first element in the array arr.


In general arr[n-1] can be used to access nth element of an array. where n is any integer number.

For example:

int mydata[20];
mydata[0] /* first element of array mydata*/
mydata[19] /* last (20th) element of array mydata*/
Example of Array In C programming to find out the average of 4 integers


#include <stdio.h>
int main()
{
    int avg = 0;
    int sum =0;
    int x=0;

    /* Array- declaration – length 4*/
    int num[4];

    /* We are using a for loop to traverse through the array
     * while storing the entered values in the array
     */
    for (x=0; x<4;x++)
    {
        printf("Enter number %d \n", (x+1));
        scanf("%d", &num[x]);
    }
    for (x=0; x<4;x++)
    {
        sum = sum+num[x];
    }

    avg = sum/4;
    printf("Average of entered number is: %d", avg);
    return 0;
}


Output:

Enter number 1 
10
Enter number 2 
10
Enter number 3 
20
Enter number 4 
40
Average of entered number is: 20


Lets discuss the important parts of the above program:

Input data into the array
Here we are iterating the array from 0 to 3 because the size of the array is 4. Inside the loop we are displaying a message to the user to enter the values. All the input values are stored in the corresponding array elements using scanf function.

for (x=0; x<4;x++)
{
    printf("Enter number %d \n", (x+1));
    scanf("%d", &num[x]);
}


Reading out data from an array
Suppose, if we want to display the elements of the array then we can use the for loop in C like this.

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


Various ways to initialize an array
In the above example, we have just declared the array and later we initialized it with the values input by user. However you can also initialize the array during declaration like this:

int arr[5] = {1, 2, 3, 4 ,5};
OR (both are same)

int arr[] = {1, 2, 3, 4, 5};
Un-initialized array always contain garbage values.

C Array – Memory representation
c-arrays



More Topics on Arrays in C:


2D array – We can have multidimensional arrays in C like 2D and 3D array. However the most popular and frequently used array is 2D – two dimensional array. In this post you will learn how to declare, read and write data in 2D array along with various other features of it.

Passing an array to a function– Generally we pass values and variables while calling a function, likewise we can also pass arrays to a function. You can pass array’s element as well as whole array (by just specifying the array name, which works as a pointer) to a function.

Pointer to array – Array elements can be accessed and manipulated using pointers in C. Using pointers you can easily handle array. You can have access of all the elements of an array just by assigning the array’s base address to pointer variable.

Program to Print Alphabets from A to Z Using Loop

Welcome back coders , here is our new blog on PROGRAM TO PRINT ALPHABETS FROM A TO Z USING LOOP. 



In the below program, for loop is used to print the alphabets from A to Z. A loop variable is taken to do this of type ‘char’. The loop variable ‘i’ is initialized with the first alphabet ‘A’ and incremented by 1 on every iteration. In the loop, this character ‘i’ is printed as the alphabet.

CODE

#include <stdio.h>
  
int main()
{
    // Declare the variables
    char i;
  
    // Display the alphabets
    printf("The Alphabets from A to Z are: \n");
  
    // Traverse each character
    // with the help of for loop
    for (i = 'A'; i <= 'Z'; i++) {
  
        // Print the alphabet
        printf("%c ", i);
    }
  
    return 0;
}


 

OUTPUT


C program to perform addition, subtraction, multiplication and division

WELCOME BACK TO codejunction.in , Make sure to check out our other blogs .


  • C program to perform basic arithmetic operations which are addition, subtraction, multiplication, and division of two numbers. 
  • Numbers are assumed to be integers and will be entered by a user. In C language when we divide two integers we get an integer as a result, for example, 5/2 evaluates to 2. As a general rule integer/integer = integer and float/integer = float or integer/float = float. 
  • So we convert denominator to float in our program, you may also write float in the numerator. This explicit conversion is known as typecasting.



CODE


 #include <stdio.h>

 int main()
{
   int first, second, add, subtract, multiply;
   float divide;

   printf("Enter two integers\n");
   scanf("%d%d", &first, &second);

   add = first + second;
   subtract = first - second;
   multiply = first * second;
   divide = first / (float)second;   //typecasting

   printf("Sum = %d\n", add);
   printf("Difference = %d\n", subtract);
   printf("Multiplication = %d\n", multiply);
   printf("Division = %.2f\n", divide);

   return 0;
}



OUTPUT

  

  

C program to subtract two matrices

WELCOME BACK TO codejunction.in ,  GLAD TO SEE YOU AGAIN , HOPE YOU ARE ENJOYING OUR BLOGS.


C program to read elements in two matrices and find the difference of two matrices. Program to subtract two matrices in C. Logic to subtract two matrices in C programming.


EXAMPLE:-

Input
Input elements in 3x3 matrix1:
1 2 3
4 5 6
7 8 9

Input elements in 3x3 matrix2:
9 8 7                 
6 5 4
3 2 1

Output
Difference of both matrices =
-8 -6 -4
-2  0  2
4  6  8


Matrix Subtraction
Elements of two matrices can only be subtracted if and only if both matrices are of same size. Matrix subtraction is done element wise (entry wise) i.e. Difference of two matrices A and B of size mXn is defined by
A - B = Aij - Bij (Where 1 ≤ i ≤ m and 1 ≤ j ≤ n)






CODE

#include <stdio.h>

#define SIZE 3 // Size of the matrix

int main()
{
    int A[SIZE][SIZE];  // Matrix 1
    int B[SIZE][SIZE];  // Matrix 2
    int C[SIZE][SIZE];  // Resultant matrix

    int row, col;

    /* Input elements in first matrix */
    printf("Enter elements in matrix A of size 3x3: \n");
    for(row=0; row<SIZE; row++)
    {
        for(col=0; col<SIZE; col++)
        {
            scanf("%d", &A[row][col]);
        }
    }

    /* Input elements in second matrix */
    printf("\nEnter elements in matrix B of size 3x3: \n");
    for(row=0; row<SIZE; row++)
    {
        for(col=0; col<SIZE; col++)
        {
            scanf("%d", &B[row][col]);
        }
    }

    /*
     * Subtract both matrices and store the result in matrix C
     */
    for(row=0; row<SIZE; row++)
    {
        for(col=0; col<SIZE; col++)
        {
            /* Cij = Aij - Bij */
            C[row][col] = A[row][col] - B[row][col];
        }
    }

    /* Print difference of both matrices A and B */
    printf("\nDifference of two matrices A-B = \n");
    for(row=0; row<SIZE; row++)
    {
        for(col=0; col<SIZE; col++)
        {
            printf("%d ", C[row][col]);
        }
        printf("\n");
    }

    return 0;
}



OUTPUT



C Program to Find Transpose of a Matrix

C Program to Find Transpose of a Matrix

WELCOME BACK CODERS , GOOD  TO SEE YOU AGAIN ON OUR BLOGS.

The transpose of a matrix is a new matrix whose rows are the columns of the original. ... Here is a matrix and its transpose: The superscript "T" means "transpose". Another way to look at the transpose is that the element at row r column c in the original is placed at row c column r of the transpose

This program takes a matrix of order r*c from the user and computes the transpose of that matrix.

In this program, user is asked to entered the number of rows r and columns c. The value of r and c should be less than 10 in this program.
The user is asked to enter elements of the matrix (of order r*c).
Then, the program computes the transpose of the matrix and displays it on the screen.

CODE

#include <stdio.h>

int main()
{
    int a[10][10], transpose[10][10], r, c, i, j;
    printf("Enter rows and columns of matrix: ");
    scanf("%d %d", &r, &c);

    // Storing elements of the matrix
    printf("\nEnter elements of matrix:\n");
    for(i=0; i<r; ++i)
        for(j=0; j<c; ++j)
        {
            printf("Enter element a%d%d: ",i+1, j+1);
            scanf("%d", &a[i][j]);
        }

    // Displaying the matrix a[][] */
    printf("\nEntered Matrix: \n");
    for(i=0; i<r; ++i)
        for(j=0; j<c; ++j)
        {
            printf("%d  ", a[i][j]);
            if (j == c-1)
                printf("\n\n");
        }

    // Finding the transpose of matrix a
    for(i=0; i<r; ++i)
        for(j=0; j<c; ++j)
        {
            transpose[j][i] = a[i][j];
        }

    // Displaying the transpose of matrix a
    printf("\nTranspose of Matrix:\n");
    for(i=0; i<c; ++i)
        for(j=0; j<r; ++j)
        {
            printf("%d  ",transpose[i][j]);
            if(j==r-1)
                printf("\n\n");
        }

    return 0;
}


OUTPUT



Download CEHv9 Study Guide PDF || Certified Ethical Hacker V9 Book

Download CEHv9 Study Guide PDF This book will be a great journey for our users in the field of cyber security . This book contains in ...